Jan
31
2013

Excellent set of JSON samples

Check out this site for a break set of JSON samples.

 

Some information from the site:

 

Over 100 code samples covering Json.NET's most commonly used functionality.

Samples

  • Serializing JSON - Serializing and deserializing JSON, serializer settings and serialization attributes
  • LINQ to JSON - Parsing, querying, modifying and writing JSON
  • JSON Schema - Loading schemas and validating JSON
  • Converting XML - Converting JSON to XML and XML to JSON
  • BSON - Serializing and deserializing BSON
  • Reading and Writing JSON - Reading JSON with JsonTextReader, writing JSON with JsonTextWriter
May
31
2012

The SharePoint & jQuery Guide

Repost from here...

 

So, you've finally succumbed to the hype and decided to use jQuery in SharePoint? Good for you. I'm sure you are fully prepared with the knowledge of the pros and cons using jQuery as well as have all the requisite knowledge.

You should NOT be writing jQuery in SharePoint if…

You don't? You mean you are going to copy and paste scripts from blogs and then ask the blogger to modify the script to work for your particular circumstance? Oh, that's nice.


Well, assuming you actually want to understand what you are doing, maybe even learn a thing or two, I've decided to link to several of my past jQuery blogs in an order which will hopefully help you learn how to successfully use SharePoint and jQuery together. I'll even do my best to keep this post updated as I write new blogs on the subject.

Good luck!

Before getting started…

Make sure you have some good background knowledge.

When you start using things like SPServices and the Client Object Model to query SharePoint list data you will need to understand SharePoint's query language CAML. I always refer to it as the ugly crossbreed of XML and SQL.

If you plan to use SPServices to access SharePoint's Web Services (which I also reference in several of the blogs below), you need to get that at http://spservices.codeplex.com.

When to Choose SPServices vs. the Client Side Object Model (CSOM)

Also, if you are wondering if you should use SPServices instead of the Client Object Model you can read the helpful post put together by Marc Anderson and myself.

Be sure to keep the jQuery.com site handy as this is by far the most up-to-date site to reference the jQuery api.

The Intro to jQuery and SharePoint blogs

Here are the blogs (in learning order) to help you deploy and get started using jQuery in SharePoint.

A Dummies Guide to SharePoint and jQuery–Getting Started

This blog assumes you know nothing. What is jQuery and how can I deploy it in SharePoint?

Undoubtedly one of the most common tasks you will perform with jQuery is getting and setting SharePoint form fields. This blog walks you through the process with the most common field types. A corresponding blog post to this one is Setting SharePoint Lookup Lists w/ jQuery (+/- 20 items) because unfortunately at some point you will fall victim to this SharePoint quirk.

Creating a SharePoint Parent/Child List Relationship–No SPD Version

So, now that you understand the basics of using jQuery in SharePoint and know how to get/set SharePoint form fields, this blog helps you apply that knowledge to perform the common task of creating an automatic parent/child list relationship. There are MANY ways of accomplishing this functionality, but I actually prefer this method. It may be a little more technical than the other solutions I've blogged about for creating a Parent/Child list relationship, but this solution has the least impact on SharePoint and should also upgrade easily.

Okay, at this point you should be ready to start interacting with SharePoint list data using SPServices. This blog post walks you through the basics with a VERY commented script. If you think you have your head wrapped around reading list data with SPServices, you might also check out the following blog posts using SPServices to accomplish some tasks normally achieved using server side code:

Using SPServices & jQuery to Clone a Parent Item and All its Children – Reads items from a SharePoint List and then creates copies of those items.

Using SPServices & jQuery to Find My Stuff from Multi-Select Person/Group Field – Determines the groups a current user belongs to in order to determine if the current user is part of a group or person assigned to a list item.

A Dummies Guide to SharePoint & jQuery – An Easy to Use Content Slider

Now that jQuery and SPServices is old hat, I walk you through the process of integrating SharePoint List Data into a third party jQuery library.

Other SharePoint tips and tricks using jQuery

So, here is a smattering of other blog posts on the subject which you may find helpful, or might give you ideas for your projects. Some of them are just academic, and some you can put into practice immediately.

Using jQuery to Print a Web Part – In this blog I use a very simple third party library to print a specific web part and not the entire page.

Using jQuery to Make a Field Read Only in SharePoint – Another tip you could use to make a SharePoint form field read only.

SharePoint List Views –Quick & Easy jQuery Filter – Using a very simple script, add a filter box to an out of the box list view that filters the rows based upon what the user enters.

Using Google Maps to Populate an Address in a SharePoint New Item Form – Before I started using the Bing Map api, I played around with the Google Maps API.

A Dummies' Guide to SharePoint and jQuery–A Real World Example – A mostly academic post on the types of things you can do with jQuery to modify a page in the _Layouts directory that you don't' have direct access to.

Essential Links for the SharePoint Client Side Developer – This is a list of a lot of the jQuery/JavaScript libraries I use along with some suggestions from others. I actually need to update this list soon.

So, What's next?

What? Is this not enough? I'd say for the price you paid, it's a bargain!!

I hope to do a few blog entries on more advanced topics like Callbacks, templates, and design patterns. Also, as we move towards SharePoint vNext I do think it might be a good idea to start to wean myself off of SPServices and start using the Client Object Model more (although nothing leads me to believe that SPServices will not work in vNext). So, look for me to start a series on the Client Object Model as well and provide any tips or tricks I learn along the way.

As always, let me know what YOU want to learn and I'll see what I can do! Thanks again for stopping by.

May
24
2012

Articles about Templates and jQuery

http://weblogs.asp.net/dwahlin/archive/2011/11/23/reducing-javascript-code-by-using-jsrender-templates-in-html5-applications.aspx

May
24
2012

Dynamically adding JavaScript script tags at runtime

This is a report from here...

First Let’s discuss about the issue of loading all the javascript files together at a stroke.

  1. 1. Javascript will not allow parallel download. So the browser will not start any other download until it loads the javascripts.
  2. 2. We use to load javascript files and methods which are unnecessary for that page. For eg: In Login page, we just need some javascripts essential for Login page, but developers will add all the javascripts in common headers.

 

<script language =”javascript” src=”scriptRequiredForUserProfile.js”></script>
<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>
<script language =”javascript” src=”scriptRequiredForReply.js”></script>

<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>

<script language =”javascript” src=”scriptRequiredForReply.js”></script>

How to solve the above 2 issuesjQuery15204168177171158769_1337868541848?

  • Include only one script in the header.

 

<script src="”loadJS.js”"></script>


 

Now we can load the javascript dynamically using 2 ways.

 

Method 1:

 

Generate dynamic // <![CDATA[
tag using DOM

 

Maintain the list of javascripts that you need to download for a respective page.

 

 

var jsFilesArray = new Array();
jsFilesArray['home.html'] = new Array( ‘validation.js’, ‘home.js’ );
jsFilesArray['login.html'] = new Array( ‘validation.js’, ‘error.js’ );

Code to get File Name of the current page

 

 

function getCurrentPageName() {
    var fileName = document.location.href;
    var end = (fileName.indexOf("?") == -1) ? fileName.length : fileName.indexOf("?");
    return fileName.substring(fileName.lastIndexOf("/")+1, end);
}

Code to generate dynamic tag and append to the head tag.

 

 

var head = document.getElementsByTagName("head")[0];

for (var i = 0;i<jsFilesArray[getFileName()].length;i++)
{
  script = document.createElement('script');
  script.id = "id_" + i;
  script.type = 'text/javascript';
  script.src = jsFilesArray[getCurrentPageName ()][i];
  head.appendChild(script);
}


 

 

Click to download the code.

 

Method 2:

 

Use AJAX to load the JS file dynamically whenever required

 

Get the required JS file using xmlHttPRequest and execute the output by passing it into eval() method. The eval() method executes the argument.

 

So guys, load your Javascripts dynamically and experience improved performance of your application.

 

Enjoy Coding :)

Sep
23
2011

A couple of great resources for Developer Cheat Sheets

Here are a couple of great sites that supply cheat sheets

http://john-sheehan.com/blog/net-cheat-sheets/

http://devcheatsheet.com/

http://www.addedbytes.com/cheat-sheets/

 

Here are a couple of specific links to cheat sheets

http://duartes.org/gustavo/articles/Asp.net-Runtime-Cheat-Sheet-HttpRequest-HttpRuntime.aspx

 

And here are a bunch of cheat sheets all in one place for you to grab :)

 

aspnet-lifecycle-events-poster.pdf (60.92 kb)

aspnet-lifecycle-events-poster.png (96.79 kb)

aspnet-mvc-lifecycle-poster.pdf (489.01 kb)

css-v2-cheat-sheet.pdf (315.28 kb)

dotnet-string-formatting-cheet-sheet.pdf (123.71 kb)

HTML5-cheat-sheet.pdf (148.82 kb)

html-character-entities-cheat-sheet.pdf (958.89 kb)

javascript-cheat-sheet-v1.pdf (452.93 kb)

jquery-1.4-cheat-sheet.pdf (436.00 kb)

jquery-1.6-cheat-sheet.pdf (347.90 kb)

linq-cheat-sheet.doc (69.00 kb)

microformats-cheat-sheet.pdf (603.49 kb)

msajax-client-lifecycle-events-cheat-sheet.pdf (101.83 kb)

python-cheat-sheet.pdf (388.90 kb)

regular-expressions-cheat-sheet.pdf (647.55 kb)

rgb-hex-cheat-sheet.pdf (198.65 kb)

ruby-on-rails-cheat-sheet.pdf (752.11 kb)

sql-server-cheat-sheet.pdf (937.46 kb)

subversion-cheat-sheet.pdf (292.49 kb)

wpf-cheat-sheet.pdf (38.51 kb)

xhtml-cheat-sheet.pdf (71.99 kb)

Jun
27
2011

Tool for Validating and Formatting JSOn

Here is a great tool for validating and formatting JSON

http://jsonformatter.curiousconcept.com/

Apr
1
2011

How to test jQuery enabled Apps using JSON with Visual Studio

Note: This artcile is a repost of one written by Andreas Grabner -- all credit goes to him for his excellent artcile

Visual Studio Team System offers a nice Web- and Load-Testing Feature that allows you to easily create tests to verify your web application’s functionality as well as verifying how it performs under load. Web Applications that make use of AJAX Frameworks likejQuery execute additonal web requests to request information from the Web Server without causing the browser to reload the complete page. JSON is one of the formats that is used to exchange information between the Web Server and the AJAX Framework running in the browser.

Challenges with AJAX in Web- and Load-Testing

Asynchronous calls executed by AJAX frameworks can be very hard to deal with for web- and loadtesting tools? Why? Because those requests can most often not easily be correlated to a Page Request done by the browser and therefore its not easy to create a nice script that shows the sequential logic of all user interactions.
The next problem with AJAX requests is that its hard to verify if the simulated request produced the correct result and whether the result of one request needs to feed a subsequent request. An example for this would be a login call that returns a user id. This user id needs to be used for subsequent calls. If the testing tool doesn’t understand JSON and is not able to automatically detect the dependency between those calls its up to the test engineer to add parsing statements for the first call and use the parsed value in subsequent calls.

How to test JSON with Visual Studio?

I’ve downloaded the following ASP.NET MVC Sample App (KIGG) that uses jQuery and JSON. My task was to create a web script with Visual Studio that creates new user accounts. In order to do that a user needs to sign on to the page with username, password and email. The user account can then be activated by following an activation link that is sent via email.

Necessary steps for the Test Script

  • Execute the request to sign up a new user by providing username, password and email
  • Get the information about the activation link
  • Execute the request to activate the user account

The default procedure for the activation uses an email that is sent out. As I didn’t want to bother with email during my web testing I extended the JSON message that is returned when signing up a new account to include the information about the activation link. Having that information as part of the response allows me to finish all the steps.

How to deal with JSON messages?

Here is the JSON message that is responded by the user signup request:

{"isSuccessful":true,"userId":"9JU51KDxp0-3Llw1BU2h7w","errorMessage":null}

 

The userId is the value that I am interested in. This is the value I need to use to call the Activate page. Another interesting value is the isSuccessful property. This allows me to add additional logic to my web script. I can verify if the sign-up request was successful. In order to do all this I need to extend Visual Studio Web Testing by writing my own Extraction andValidation Rule. Visual Studio offers an interface to provide custom implementations for value parsing and validation. Here is my implementation for the ExtractorRule using a helper class that parses the JSon string:

 

public override void Extract(object sender, Microsoft.VisualStudio.TestTools.WebTesting.ExtractionEventArgs e) {
  NameValueCollection jsonProperties = JSonHelper.ParseJSonString(e.Response.BodyString);
  string propertyValue = jsonProperties.Get(JSonPropertyName);
  if (propertyValue != null) {
    e.WebTest.Context.Add(ContextParameterName, propertyValue);
    e.Success = true;
  } else
    e.Success = false;
}

 

In a similar way I implemented the ValidationRule. Using it all in my web test allows me to specify the Extractor and Validation Rule in my web test.


 

Conclusion

With Visual Studios extensibility mechanisms its easy to build support for those emerging technologies like jQuery and JSON. Let me know if you need the library that implements the two extension Rules.

 

Jan
18
2011

Thoughts on performance improvements for JS and CSS files

I have been continuing some research on how to help improve our performance.  The first area I have been looking into have been around our CSS and JS libraries.  I thought I would share what looks to be the most promising options so far and start a conversation around them and other ideas.

 

Ideas/Tools

·         JavaScript

o   Compress existing JS files to reduce download

§  Yahoo seems to have the #1 tool out there and it is command line driven so it would be easy for us to automate it’s usage

·         http://developer.yahoo.com/yui/compressor/

o   Combine JS files into single file

§  We can use a feature built into ASP.NET to do this for us I think – it is a feature of the ScriptManager class

·         http://msdn.microsoft.com/en-us/library/cc488552.aspx

§  If this doesn’t work, here is a great JS compressor and combiner (also works with CSS)

·         http://svn.offwhite.net/trac/SmallSharpTools.Packer/wiki

·         CSS

o   Compress existing CSS files to reduce download time

§  Same Yahoo tool for JS will work on CSS

o   Combine CSS into single file

§  ASP.NET control for CSS that is just like the ScriptManager

·         http://gstylemanager.com/

§  Command line tools

·         http://cssmixer.codeplex.com/

·         http://csstidy.sourceforge.net/index.php

·         http://svn.offwhite.net/trac/SmallSharpTools.Packer/wiki

·         http://code.google.com/p/cssmerge/

 

Right now I like the ideas of the ScriptManager and StyleManager as these would require the least amount of work to implement and have the largest benefit (the compress and cache).  The main concern I have is that the ScriptManager may not play well with our JQuery code base – so we need to make sure we test carefully.  If it turns out these will not work, the Yahoo tool followed by the SmallSharpTools package looks to be our next best options based on what I have found so far.