SharePoint Saturday Recap

On March 26, 2013, in Speaking, by admin

SharePoint Saturday Richmond has come and went, and it was a huge success. Thank you for all the people who came out and networked and attended the sessions.

My slide deck on creating a SPA (Single Page Application) in SharePoint 2013 using NAPA can be found here.  Feel free to shoot me an email with any questions.

%%wppa%% %%slideonly=1%% %%size=0.75%%

 

There are many options out there for programming against the SharePoint object model. You can use all sever side code using the server side object model, everything client side using JavaScript and the CSOM (client side object model). You can even use Silverlight to access your SharePoint objects. One of the newest methods, and one that I’m excited about, is using the new SharePoint REST API. Making RESTful service calls is now available using SharePoint 2013, which makes creating pages and web parts very simple.

You can access most of your SharePoint objects via REST, but I am just going to look at lists for the moment. I will show you how to first read something from a list and then how to insert an item into that list.

The Model

For this example we are going to have a list already created named ‘Employees’ that has 5 fields.

  1. Title (I changed the display Name to Name)
  2. Address
  3. Department
  4. Salary
  5. Manager

Selecting From a List

The whole basis for RESTful queries is the URL and SharePoint makes this very easy for you. In this example let’s assume that our employees list is at the root of our site. In order to select all items from this list we would simply query the following URI:

https://mysite.com/_api/web/lists/getByTitle('employees')/items.   

The ‘_api’ tells SharePoint that this is going to be a REST query, and the rest of the string tells it where to find this list. A normal REST query would look like this:

https://mysite.com/_api/web/lists/employees/

But since this is SharePoint things are always a little bit different. Instead of referencing the list directly in the URI you must find the list by title. There is also an option to find by GUID, but using the title is a bit simpler to read in my opinion.

That query will give you every property of every item in your list. Sometimes this might by OK, but I would assume that most of the time this is going to be overkill. I queried my list with Fiddler and this is the first entry of the result set that came back.

full query set

You can see all of my custom properties in there, but the rest of the stuff I really don’t care about. Let’s trim this list a little bit by adding a query string to the end of my URI I can tell SharePoint to only give me back certain items.

 https://mysite.com/_api/web/lists/getByTitle('employees')/items?$select=Address,Department,Manager,Title,Salary

simplified query

This is the same record that I selected from above and obviously this is a lot lighter than my first query, so you would want to make sure you trim down the items you are returning to only the items you actually need. Also note that in the Model section above that I renamed the default Title field to Name, however that is just a display name. So when you are querying the list you must give the static name which is Title in this case. You can use most of the ODATA protocol in order to page through the list or do some filtering but I will leave that as an exercise for you.

Inserting a List Item

Inserting an item is just as easy as selecting an item and in fact we are going to be using the same URI and just change our HTTP verb from GET to POST.
We start with https://mysite.com/_api/web/lists/getByTitle(‘employees’)/items just like before, but this time we are going to need a payload to send along with this query so SharePoint knows to insert it. My payload data looks like the following.

 { '__metadata': { 'type': 'SP.Data.EmployeesListItem' }, 
    'Title':  'Tony Stark',
    'Department' : 'Research', 
    'Salary':  '2,000,000', 
    'Manager':  'Pepper Potts',
    'Address':  '23 Ironman Way, New York, NY'
 };

We are telling SharePoint what type of object we are inserting, in this case SP.Data.EmployeesListItem. Then we just pass along as a JSON string representation of everything that we want to fill out about the item. Just that simple.

We POST against this URL and SharePoint takes care of the rest.

Summary

  • SharePoint 2013 exposes a RESTful service to access lists and other elements
  • RESTful queries are quickly becoming the standard for web services instead of the older SOAP standard
  • Using RESTful queries in SP 2013 allows developers to access SharePoint elements without having to write any complex code

This post is also over on my company site

Tagged with:  

Doing more with LessCss

On March 7, 2013, in Uncategorized, by admin

As a developer, I am not very excited about the prospect of writing the same bit of code over and over again. We are developers. We write code once and reuse it; we have classes and functions that we use all over the place. While doing web development, however, I find myself writing the same thing over and over again in my CSS file. While I can style pages on my own, to be honest with you CSS is not my strong suit. I can create some basic styling and get the job done, but not as quickly or as efficiently as a designer. I would love to be able to speed this process up. From another standpoint, I am sure designers would love to have some more control over their styles so some rogue developer doesn’t start mucking up their hard work.

LessCSS is a dynamic stylesheet language that allows you to write functions, use variables, and reduce the amount of redundancy in the CSS that you write. It also lets a designer come in and create the base styles for your page and add some hooks for a common developer like myself. These hooks allow me to change some properties around, but keeping the main look of the site intact. The designer can limit what I can change by only allowing certain properties to be editable. Of course I can overwrite these styles, but that is what code reviews are for right?

When I first heard of less it left me scratching my head a bit. So let’s start with a very simple example. I want to create two classes in my CSS that only differ by a background color. Without using less, my CSS file would look like this.

.BlueBox
{
    float: left;
    background-color: rgb(0, 100, 200);
    padding: 10px;
    margin: 10px;
    border: solid 2px orange;
}
 
.GreenBox
{
    float: left;
    background-color: rgb(0, 160, 16);
    padding: 10px;
    margin: 10px;
    border: solid 2px orange; 
}

While this isn’t horrible, it is a bit redundant. The only thing that has changed between the two classes is the background color. So if I had to change the border color, I would have to find all of my boxes and update them. Right now there are only two, but you can see how this could become a maintenance nightmare. How do we fix this?

With Less we can use functions or in the less parlance a mixin. A mixin is what less calls a CSS class that you can use in other classes. Below is my less code that gets compiled to look exactly like the example above. In this case the box class is called a mixin.

.GreenBox
{    
    .box (rgb(0,160,16));
} 
 
.BlueBox
{
    .box (rgb(0,100,200));    
}

.box (@backgroundcolor: rgb(0,0,0))
{
    float: left;    
    padding: 10px;
    margin: 10px;    
    background-color: @backgroundcolor;
    border: solid 2px orange;
}

So I have three classes defined and starting from the bottom we have box. This has everything about my box that I would need and if I didn’t give it a parameter I could use this as a normal class, but since I have a parameter I have to use it as a mixin. This class takes one parameter to set the background color, and if I don’t set it I have a default value of white. Moving up a class I have BlueBox, and the only line in this definition uses our mixin and passes in an rgb color of blue. That’s it and the same thing for GreenBox. Pretty powerful stuff!

So my designer could have created the box style, and allowed me to set the background color, and it will be uniform across the site giving a standardized look. We also removed all of the redundant code, it is now in one spot, so if I wanted to update my border color I would just have to come to box and change it there. My update is now propagated across all of the places where I am using box as a mixin.

Nesting

Less also allows you to nest rules. There are many times when you want to change how something looks, but just in a particular section. Building off the example above, let’s say that I would like to reverse the colors of the blue and green boxes, but just in the main content section. I would also like to underline a header, and make the background color of the whole section red (quiet garish I realize, I told you I wasn’t a designer).

My HTML looks like the following.

 
<div class="GreenBox">This is some text in my green box</div> 

  <br style="clear: both" /> 

  <div class="BlueBox">This is some text in by Blue Box</div>

  <br style="clear: both" />
  <article class="MainContent">
     <h1>Main Content</h1>
     <div class="GreenBox">This is some text in my Green box</div>
 
     <br style="clear: both" />
 
     <div class="BlueBox">This is some text in my Blue Box</div>
  </article>

I have two divs using the style from the previous example, so the text should match the background color there. But inside my MainContent article I want the colors reversed.

In traditional CSS in order to do that, it would look like the following:

.GreenBox {
  float: left;
  padding: 10px;
  margin: 10px;
  background-color: #00a010;
  border: solid 2px orange;
}
.BlueBox {
  float: left;
  padding: 10px;
  margin: 10px;
  background-color: #0064c8;
  border: solid 2px orange;
}

.MainContent {
  border: solid 1px green;
  padding: 5px;
  background-color: red;
  overflow: auto;
}
.MainContent h1 {
  text-decoration: underline;
}
 
.MainContent .BlueBox {
  float: left;
  padding: 10px;
  margin: 10px;
  background-color: #00a010;
  border: solid 2px orange;
}
.MainContent .GreenBox {
  float: left;
  padding: 10px;
  margin: 10px;
  background-color: #0064c8;
  border: solid 2px orange;
}

Things are starting to get a bit more complicated now. I am playing nice here by keeping all of the styles for MainContent together but there is nothing saying that I have to do that, I can have it spread out all over the place if I wanted to. How can less help with this? It allows you to nest definitions. So the above code turns to this:

.GreenBox { .box (rgb(0,160,16));   }
.BlueBox  { .box (rgb(0,100,200));  }

.box (@backgroundcolor: rgb(0,0,0))
{
    float: left;
    padding: 10px;
    margin: 10px;
    background-color: @backgroundcolor;
    border: solid 2px orange;
}
 
.MainContent
{
    border: solid 1px green;
    padding: 5px;
    background-color: red;
    overflow: auto;
 
    h1 { text-decoration: underline;    } 
    .BlueBox   { .box(rgb(0,160,16));   }
    .GreenBox  { .box(rgb(0,100,200));  }
}

You can see that I have all of my styles for MainContent nested underneath it. This grouping of the styles makes everything very easy to read and find. I could even continue to go down and nest things further if I wanted to, and everything is nicely grouped and easy to read. And that makes me, as a developer, very happy.

Usage

So now that we have written our lessCss, how do we actually use it? The easiest way to do this is to download the less.js file from lesscss.org. Include it in your HTML after your stylesheet declarations and it will compile everything for your client side when the page is rendering. Yes, it works but maybe not the best solution since that will take time when the page is loading. In the example above since I don’t have a very many styles you cannot tell the difference in the page load. However once you start having a lot of class definitions the performance may start to degrade.
There are some extensions for Visual Studio that you can download and install that will compile the less to pure CSS for you, and then you can just reference the compiled version and push that out to your site. I use Web Essentials 2012 in Visual Studio 2012 to compile my Less. Every time you save it generates your file for you, and it gives you a nice preview window of what your code looks likes on the fly.

Summary

  • Less lets you quickly develop CSS in a highly structured manner
  • It allows your designers to focus on the base styles, and your devs to just use them less worry of breaking some style rule that the designer has put forth.
  • Nesting lets you group your related styles together so you no longer have to hunt for child style definitions
  • Because less gets compiled to standard CSS there are no cross browser issues, other than what you would normally encounter with CSS.
  • Whether you use less client side or at design time it will allow you to greatly simplify your CSS allowing your devs to get more done.
 

CoffeeScript is an abstraction of regular JavaScript. In fact under the hood it still is just JavaScript and it compiles directly into JavaScript. In fact, on the CoffeeScript homepage they say that the Golden Rule of CoffeeScript is “It’s just JavaScript”. So why would you want to use CoffeeScript if, basically, you are just using JavaScript?

JavaScript is notoriously a bit finicky. There are a lot of gotcha’s that if you have been working with JavaScript for a while you will already know and how to get around them. So would CoffeeScript be good for you? Maybe. It may help you write a little bit quicker, but you will have the initial learning curve of learning CoffeeScript and you could probably write the equivalent JavaScript in much less time. Who then would benefit from learning CoffeeScript? Anyone who’s JavaScript foo isn’t the strongest, new developers or people just breaking into the wide world of client side development.

I would argue that still learning JavaScript is very important, but using CoffeeScript is a great way to do that because you can see what the CoffeeScript compiles into and learn best practices from that. CoffeeScript is mostly just syntactic sugar but the script that you write with CoffeeScript may be faster than the script you handwrite. Now that I have gotten those disclaimers out of the way, let’s drink the kool-aid…err coffee.

Basics

CoffeeScript is a whitespace based language, so all the indentations do matter. Since there are no curly braces or semi colons please pay attention to the spaces. The CoffeeScript complies into the JavaScript below it.

CoffeeScript

sugar = true
cream = false
lumps =0
 
if sugar 
    lumps =2 
 
makeCoffee = (s, c, l) ->
    msg = "Here is your coffee with "    
 
    if s
        msg += l + " lumps" 
 
    if c
        msg += " and cream"
 
    alert msg
 
makeCoffee(sugar, cream, lumps)

JavaScript

(function() {
  var cream, lumps, makeCoffee, sugar;

  sugar = true;

  cream = false;

  lumps = 0;

  if (sugar) {
    lumps = 2;
  }

  makeCoffee = function(s, c, l) {
    var msg;
    msg = "Here is your coffee with";
    if (s) {
      msg += l + " lumps";
    }
    if (c) {
      msg += " and cream";
    }
    return alert(msg);
  };

  makeCoffee(sugar, cream, lumps);

}).call(this);

One of the first things that you will notice is that there are no semi colons, when writing in CoffeeScript everything is based off of spaces, so you don’t have to worry about those pesky semicolons. There are also no variable types you don’t have to have var in front of your declarations. Moving down the source on the left we have an if-statement. There isn’t a whole lot there, no parentheses around the test, and no curly braces around the if-block. If we keep moving down we are defining a function named makeCoffee that takes 3 arguments. The -> denotes that this is going to be a function, and everything under that is the actual function body. After the function definition we are actually calling the makeCoffee function.

Looping in CoffeeScript

CoffeeScript

range = [1..15]
 
for i in range 
    if i % 3  == 0 
        console.log 'fizz'
        
    if i % 5 == 0
        console.log 'buzz'
 
    if i % 3 != 0 and i % 5 != 0
        console.log i
    
    console.log 

JavaScript

(function() {
  var i, range, _i, _len;

  range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

  for (_i = 0, _len = range.length; _i < _len; _i++) {
    i = range[_i];
    if (i % 3 === 0) {
      console.log('fizz');
    }
    if (i % 5 === 0) {
      console.log('buzz');
    }
    if (i % 3 !== 0 && i % 5 !== 0) {
      console.log(i);
    }
    console.log;
  }

}).call(this);

The first line in the CoffeeScript is defining my range of values. The .. between my two numbers means to be inclusive, so the 15 is included in my range. If I added three dots … it wouldn’t be inclusive, so my range would stop at 14. I am just doing a quick fizzbuzz loop and writing out the results to a console window. The for-loop is very familiar, and shouldn’t be too hard to understand. But what amazes me is how that little bit of code translates into so much more.

Existential Coffee

Determining whether or not a variable exists isn’t trivial in regular JavaScript. It gets me a little verklempt. I’ll give you a topic…An undefined variable is neither variable nor invariable. Talk amongst yourselves.

Ok, we’re back…You can check if it the variable has a value, or if it is undefined, but that is somewhat lacking. So CoffeeScript gives you the existential operator (?) which allows you to check if a variable exists and act accordingly. Below, I am asking if cups is defined, and if it isn’t I am assigning the value of 10 to cupsOfcoffee and then putting that in an alert box.

CoffeeScript

cupsOfcoffee =  cups ? "10"
alert cupsOfcoffee

JavaScript

(function() {
  var cupsOfcoffee;

  cupsOfcoffee = typeof cups !== "undefined" && cups !== null ? cups : "10";

  alert(cupsOfcoffee);

}).call(this);

That little question mark turns out to be quite powerful, and translates to a very good null check for the variable cups. Very cool stuff.

Summary

There is a lot more to CoffeeScript that this simple overview, but I just wanted to show you some basics. For a full listing of what CoffeeScript can do I recommend checking out their site.

  • CoffeeScript is a lightweight framework over top of JavaScript
  • Creates fast and readable script that translates directly into JavaScript.
  • CoffeeScript may not be as useful for experienced JavaScript developers but for people just learning client side development it may significantly decrease the time it takes to create an app.



This is post can also be found at TCSC.com

Tagged with:  

SharePoint Saturday Richmond

On March 5, 2013, in Sharepoint, Speaking, by admin

I will be speaking at SharePoint Saturday in Richmond on March 23rd.  There are a lot of great speakers and topics lined up, so I would encourage you to go out and sign up today.

The name of my speech is “Giving SharePoint 2013 the SPA treatment.”    I will be covering how to use Office 365 and NAPA to create Single Page Application (SPA) in SharePoint 2013, using the JSOM (JavaScript Object Model).

Hope to see ya’ll out there

Tagged with:  

HTML5 Web Workers and AJAX

On February 25, 2013, in HTML5, JavaScript, JQuery, by admin

One of the new features in HTML5 allows asynchronous JavaScript operations to happen on the web freeing your UI thread to continue and not lock up the user providing a rich user experience. But how do you use AJAX along with the web workers to post data back to the server? This proves a little more difficult because we are limited to basic JavaScript calls. We can’t use jQuery from within the web worker, so we have to rely on our old friend the XMLHttpRequest.

First let’s start with the basics, calling a web worker. In order to call a web worker you must create a separate JavaScript file to hold all the logic. I have the following code in a JavaScript file named SavePerson.js

   self.addEventListener('message', function (e) {
 
    self.postMessage('Saved person: ' + e.data);
});

In the main body of my JS code I have the following code to call the worker.

var worker = new Worker('/scripts/SavePerson.js');
 
worker.addEventListener('message', function (e) {
    alert(e.data);
});
 
worker.postMessage('James Bond');

As you may have noticed in order to send messages back and forth both the caller and the worker are posting messages back and forth and are listening for the message event. The event contains one parameter ‘e’ which has a data property. This data property can be just simple text or JSON. The caller, in this example, is passing the text “James Bond” to the worker. The worker receives the message and simply prepends the text ‘Saved person: ’ in front of the message and posts that back to the calling thread, who then pops up that message in an alert box.

This is obviously a very simple example and will return almost immediately, with very little lag. So this isn’t something you would generally use web workers for. You would want to use them for long running processes. Something like saving or updating a record doesn’t require the user to wait before it is finished.

I am now going to update my web worker to actually make a call back to my .Net code to do my insert.

self.addEventListener('message', function (e) {
 
    var data = JSON.stringify(e.data);
    
    var req = new XMLHttpRequest();
 
    req.open('POST', '/myHandler.ashx?action=SavePerson', false);
 
    req.setRequestHeader('Content-Type', 'application/json;  charset=utf-8');
    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            self.postMessage({ 'Error': 'No', 'Message': 'Save Successful' });
        }    
    }    
    req.send(data);
});

This is a more complex example, so let’s step through one line at a time for those not used to the old school method of making AJAX calls. The first line is the same as our first example where we are listening for the message event. We are then converting the JSON data passed in into a string so can post it back to the server. We then create a new XMLHttpRequest object and open it. This is a post method since we are sending data back to the server. I am posting back to a generic handler named myHandler.ashx, and passing a query string value that is telling my handler what action I wish to take.

The last parameter of the open method is whether or not you want this synchronous or not. Since I am in a web worker which is in a separate thread already from the main UI thread I can wait around for my AJAX call to come back. The next line tells the server that I will be sending JSON back to the server. We are then ready to setup our callback event for the readyStateChange event. The state changes a few times during this process so we must look for the complete state, which is HTTP status of 200 and a ready state of 4 which equates to loaded. Once we have received those codes, we post a message back to the parent saying that there were no errors and the save was successful. The last line is where the post actually happens when we tell the XMLHttpRequest to send the data.

Whew, that was a lot of work for something so simple as calling $.post(“/myhandler.asxh?action=SavePerson”, data, function(){}) in jQuery. This is why jQuery is such a nice tool. Under the hood jQuery is doing the same thing, and since this worker is in a separate thread there is no document.ready function, so we can never initialize the jQuery object. That is why you can’t use it in your workers.

Calling the worker is exactly the same as in the first example except I am sending and receiving a JSON object.

 var person = {     'Name': 'James Bond',
                    'Age': '32',           
                    'Bio': 'Redacted',
                };  

 var worker = new Worker('/scripts/SavePerson.js');
        
        worker.addEventListener('message', function (e) {            
            if (e.data.Error == 'No') {                
                DisplayInfoMessage(e.data.Message);             
            }
            else {                
                DisplayErrorMessage(e.data.Message);
            }            
        });

worker.postMessage(person);        

Summary

  • Web workers allow async JavaScript calls to free up your UI thread
  • You should only use them for long running processes
  • You can pass strings or JSON between worker and caller
  • You can’t use jQuery in your workers
Tagged with:  

Taking Sammy to the SPA

On February 25, 2013, in JavaScript, Sammy.js, by admin

Web applications are now expected to be as responsive and immersive as desktop applications. In my opinion, Single Page Applications or SPAs are where the web is going and many sites you are already familiar, with such as Gmail, are already there. However writing an application on the web poses some unique concerns. Being on the web, users will expect the forward and back button to work and to be able to bookmark pages. Having a SPA poses some problems since everything is done on a single page. So how do you provide support for back and forward buttons and support for bookmarks? Enter Sammy.js

Benefits of using Sammy.js

  • Bookmarking a “page” in your SPA
  • Forward and back button still work as expected
  • Avoiding Postbacks/Minimal Network traffic, because this is a single page there is no need for the browser to reload the page each time you navigate, so almost all computation is done client side providing a significant speed boost.
  • Avoiding session, because we have actual URLs there is no need for your application to remember where you are, eliminating the need to store the users current state in session or something similar which can be a problem in traditional AJAX sites.

The heart of Sammy.js is allowing you to define routes in your JavaScript very similar to how you set up routes in MVC. The first step is to set up the base route. This is what will be fired when no other route is defined. In order for Sammy to work you must setup the routes right after the DOM is fully loaded before you have any other actions in you JavaScript.

(function ($) { 
    var app = $.sammy('#MainSection', function () { 
        this.get('#/', function (context) {
            DoSomethingHere();
        }); 
    });  

    $(function () { 
        app.run('#/');
    });
})(jQuery);

Above I am defining the main content area of my SPA as MainSection. You can also explicitly define the main content area (see below), but you can just use the short hand as shown above to keep things simple.

this.element_selector = '#MainSection';

After defining the main content area I am defining my default route. So whenever the users navigates to a URL matching www.myapp.com/, www.myapp.com/# or www.myapp.com/default.html/# it will call the DoSomethingHere() method. After defining the default route you must initialize the application. If you do not initialize the application by calling app.run() then the routing engine will not take over and none of your routes will work.

Now let’s try for a little more complex route. I want a URL that will show employees. So I am going to define a route that looks like www.myapp.com/default.html#/Employees. We are going to declare this route right below the default route in the example above.

this.get('#/Employees', function (context) {
   ShowEmployees();
 });

So anytime someone navigates to the URL above it will run the ShowEmployees functions. If you have any experience with the MVC framework this should look very familiar to you. Now if we wanted to continue along those lines and wanted to view a specific employee based on that employee’s ID then we can use the following pattern www.myapp.com/default.html#/Employees/5 and define a route to match.

 this.get('#/Employees/:id', function (context) {
    LoadEmployee(this.params['id']);
 });

The :id tells the routing engine to expect a variable after the ending slash. To access this variable you just call this.params[] and give the name of the variable in quotes and you are ready to use it. So now that we have the routes down how do we actually use it? You simply add an anchor tag to your site that matches a route. The below example shows how you would add a link to view employee number 5:

   <a href="#/Employees/5" >John Doe </a>

When the user clicks the link above, the page life cycle looks something this:

  1. Page navigates to the # anchor on the page (doesn’t actually exist) loads DOM
  2. Sammy.js recognizes the pattern from your defined routes
  3. Your method LoadEmployee gets fired, where you change the main content to display information about John Doe.
    1. Presumably you are making an AJAX call to pull employee data back via JSON, or if you are using an HTML5 compatible site, you can load all your employee data when the user first lands on your site and store everything in local storage. There are pros and cons to each method, but that is out of scope for this post.
  4. After LoadEmployees returns the rest of your JavaScript on the page fires. For example, if you are using JQuery this is when the document.ready function would fire.
  5. Display the rendered page to the user.

In summary, by using Sammy.js you can create and define routes in your single page applications that will allow users to navigate as they normally would on the web without the extra overhead of continuously posting back to the server.

This is cross posted at TCSC.com

Tagged with:  

Mark your calendars now for the Microsoft Visions Conference scheduled on February 20, 2013.

I will be giving a presentation on HTML5 and Azure and how you can leverage the Azure platform to quickly build your HTML5 website using Azure table storage.

There is something for everyone, whether you are a developer, business analyst, or even an executive. This event will be held at the Microsoft office in in Glen Allen, VA.

The Microsoft Visions Conference is sponsored by TCSC, go ahead and register today!

Tagged with:  

Using Templates to Generate HTML from JSON

On February 25, 2013, in JavaScript, by admin

Instead of generating HTML inside of JavaScript by concatenating strings to form your display code you can use JSRender to apply templates to your JSON objects in order to greatly simplify your code.
As an example I am going to create a simple form that takes in some person information and uses JQuery and JSRender to display it back on the page.

Step 1: Get JSRender

You can find JSRender here from github.

Step 2: Reference the jsrender.js file in your page

    <script src="Script/jsrender.js" type="text/javascript"></script>

Step 3: Create your template

 <script id="PersonTemplate" type="text/x-jsrender">
    <div class="DataRow">
       <div class="Col">{{>FirstName}}</div>
       <div class="Col">{{>LastName}}</div>
       <div class="Col">{{>Suffix}}</div>
       <div class="Col">{{>Gender}}</div>  
    </div>
 </script>

Make sure you give your template an id, set its type to text/x-jsrender, and then declare the template inside of your document.ready function as shown below:

$.templates({
  PersonTemplate: "#PersonTemplate"
});

Step 4 : Fill your JSON Object.

In the example below I am storing all of my entries in the people object.  I am pulling the values from the html form, filling out my row, and adding it to the people object.


var people= [];

$("#btnSave").button().click(function () {
   var person = {
      "FirstName": $("#txtFirstName").val(),
      "LastName": $("#txtLastName").val(),
      "Suffix": $("#txtSuffix").val(),
      "Gender": $("#ddlGender").val()
   };

people.push(person);

Step 5: Apply the template

Applying the template is very simple; you just have to pass the data that you wish to render to the template function, which then gets output as HTML. In the below example I am appending the output to the SavedPeople div.

$("#SavedPeople").text("");
$("#SavedPeople").append($.render.PersonTemplate(people));

The results should look something similar to this:

Fully working example:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>JSON Templating Example</title>
   <style>
      .DataRow{
         position: relative;
         width: inherit;
         min-width: 650px;
         clear: both;
         margin: 10px;
         height: 1%;         
         overflow: hidden;
      }

      .FormRow{
         position: relative;
         width: inherit;
         min-width: 650px;
         clear: both;
         height: 15px;
         margin: 10px;
      }

      .Col{
         float: left;
         width: 25%;
         height: 100%;
      }

      .headerRow{
         font-size: 11px;         
         font-weight: bold;
         color: Black;
         background-color: #C0E0FF;         
         vertical-align: top;
         border: solid 1px #aaaaaa;
         padding: 5px;
      }

</style>

</head>

<body>

   <form id="form1" runat="server">
      <div>
         <fieldset> <legend>Person</legend>
             <div class="FormRow">
                <div class="Col">First Name</div>
                <div class="Col"> <input id="txtFirstName" type="text" /></div>
             </div>

             <div class="FormRow">
                <div class="Col">Last Name </div>
                <div class="Col"> <input id="txtLastName" type="text" /></div>
             </div>

             <div class="FormRow">
                <div class="Col">Suffix</div>
                <div class="Col"> <input id="txtSuffix" type="text" /></div>
             </div>

             <div class="FormRow">
                <div class="Col">Gender</div>
                <div class="Col">
                   <select id="ddlGender">
                      <option value="male">Male</option>
                      <option value="female">Female</option>

                   </select>
                </div>
             </div>

             <a href="#" id="btnSave">Save</a>

         </fieldset>

         <h2>Saved People</h2>
            <div class="DataRow headerRow">
                <div class="Col">First Name</div>
                <div class="Col">Last Name</div>
                <div class="Col">Suffix</div>
                <div class="Col">Gender</div>
            </div>
            
            <div id="SavedPeople">
                (No People)
            </div>
         </div>

  </form>

  <script src="Script/jquery-1.6.2.js" type="text/javascript"></script>
  <script src="Script/jquery-ui-1.8.18.js" type="text/javascript"></script>
  <script src="Script/jsrender.js" type="text/javascript"></script>
  
  <script>
     $(document).ready(function () {
        $.templates({
           PersonTemplate: "#PersonTemplate"
        });

        var people = [];

        $("#btnSave").button().click(function () {
           var person = {
             "FirstName": $("#txtFirstName").val(),
             "LastName": $("#txtLastName").val(),
             "Suffix": $("#txtSuffix").val(),
             "Gender": $("#ddlGender").val()
           };

           people.push(person);

           $("#SavedPeople").text("");
           $("#SavedPeople").append($.render.PersonTemplate(people));

        });
     });

  </script>

  <script id="PersonTemplate" type="text/x-jsrender">
     <div class="DataRow">
        <div class="Col">{{>FirstName}}</div>
        <div class="Col">{{>LastName}}</div>
        <div class="Col">
           {{if Suffix == ""}}
               
           {{else}}
              {{>Suffix}}
           {{/if}}
        </div>
        <div class="Col">{{>Gender}}</div>  
     </div>

  </script>


</body>
</html>

This post is cross posted at TCSC.com

Tagged with:  

Sorting a SharePoint List in Report Builder

On February 25, 2013, in Sharepoint, by admin

I recently needed to display a list of items in alphabetical
order for a multi select parameter inside of a report. I was using Report Builder 3.0 and there is no option for sorting the list in the user interface. Many people recommended sorting the list before returning it to the report. This wasn’t really an option for me because I was pulling the data from a SharePoint list that I didn’t have control over.
A lot of articles out there say that this can’t be done or
that in order to do it you must embed some code inside of the report to sort
the list manually. There is an easier way to do this however. You can use CAML (Categorical Abstract Machine Language) to set the order.

My initial query looked like this:

<RSSharePointList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ListName>MyListName</ListName>
    <ViewFields>
      <FieldRef Name="ItemToSort" />
    </ViewFields>
</ RSSharePointList>

In order to change the sort order of my data set, I changed my query to the following:

<RSSharePointList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ListName>MyListName</ListName>
    <ViewFields>
      <FieldRef Name="ItemToSort"/>
  </ViewFields>

  <Query>
      <OrderBy>
           <FieldRef Name="ItemToSort" Ascending="True" />  
    </OrderBy>
  </Query>
</RSSharePointList>

I added the query node, and inside of that specified what I
want to order by; simple as that.  Be
warned, however, that CAML queries are notoriously easy to break. Everything needs to be in the correct case,
and no extra spaces. Because of that I would recommend using a CAML query
builder in order to generate your query.

This post is cross posted on TCSC’s blog.

Tagged with: