Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Friday, July 22, 2011

Posted by SAMAJ SHEKHAR

0

Introduction to HTML5 <Canvas>: Part 2 (Example)


This post is the sequel to my previous post of Introduction to HTML5 <Canvas>: Part 1 and shows a walkthrough example of using canvas for some static 2D drawing (for Introduction to animation wait for my next post). This is the second post to my “HTML5 <Canvas>” series.
In previous post we saw how <Canvas>'s context gives us an API with set of methods and properties to draw on its surface, now in this post we will use some of those methods to draw a logo of one of my favorite game PORTAL2.
Sorry, but your Browser Dosen't Support HTML5 <canvas>
Above is the actual completed art drawn on canvas, and below we will see how we draw that art piece by piece. And Let me tell you this article is just for introducing you to the use of various methods provided by canvas and may not show the best and efficient way of drawing on it. So keeping that in mind, let’s get started.

First things first

As you may know by now that before any drawing we need to have a handle on <Canvas> element to do manipulations, and that handle is the context object of the <Canvas>. The context of the <Canvas> element provides us all that API of methods to do drawing and manipulation on <Canvas>. To get the context we use "getContext()” method and pass in the string “2d” as parameter * . Also since we feel more natural using “degrees” for specifying angles but all functions of canvas context take clockwise “radians” as parameter, we’ll use following function to convert degree into anticlockwise* radians. Also note that it is recommended to use "save()” and “restore()” methods of context to save the current state of the context on the stack before any manipulation & transformation and restore it back to its previous state respectively.
*(for details check my previous post or w3c draft)
//context of the canvas
var ctx = document.getElementById("portalcanvas").getContext("2d"); 
//function to convert radians to degrees
var acDegToRad = function(deg){
		return deg* (-(Math.PI / 180.0));    
}

Drawing the “2”

We’ll start by drawing the number “2” on the <Canvas>. It consists of 3 pieces the base rectangle, a slant rectangle and an arc.
  • 2’s Base: The base rectangle is the easiest of all to draw, just set the “ fillStyle” property of the context to light gray color and use “fillRect( x, y, width, height)” method to draw the rectangle.
    ctx.save();
    ctx.fillStyle = "rgb(110,110,110)";
    ctx.fillRect(20,200,120,35);
    ctx.restore();
    
    If we want we could also draw above rectangle as a small horizontal line with line-width equal to the height of the above rectangle. But that would involve more steps like creating a path and then drawing the line along the path, which is more complicated for this primitive shape.
  • 2’s Slant: The slant rectangle is just a simple rectangle but elevated to an angle of 35 Degrees. So to create a slant rectangle first we will translate the origin of the coordinate space (i.e., the transformation matrix) to the top edge of 2’s base rectangle using “translate( newX, newY)” and then rotate the coordinate space by 35 degrees in anti-clockwise direction, taking new origin as the pivot/center, by using the “rotate(radians)” method and then simply draw the rectangle using fillRect( x, y, width, height).
    ctx.save();
    ctx.fillStyle = "rgb(110,110,110)";
    ctx.translate(20,200);
    ctx.rotate(acDegToRad(35));
    ctx.fillRect(0,0,100,35);
    ctx.restore();
    
    Also note that how we have used save() before any manipulation and then used restore() after drawing, this makes sure that the translation and rotation of coordinate space does not affect rest of drawings we are about do later on. This way context state of the canvas always remains in previous state, in this case, the Initial state. Remember save() and restore() doesn’t save/restore the contents on the canvas, it just save/restore the state of properties/attributes like “fillStyle”, “strokeStyle”, “lineWidth”, etc and coordinate space on the <Canvas>drawing context.
  • 2’s Arc: The top arc of number “2” cannot be drawn by rectangle methods but can be simply drawn like a line arc whose line-width is equal to the height of previous rectangles. For creating any line shape we first start a path by calling “beginPath()” method, then call any shape method like “rect()”, “arc()”, “lineTo()”, etc to add them to path and then optionally call “closePath()” method to complete the path and start new one. For this step we will start a new path and add an arc to the path by using “arc(x,y,radius, startAngle, endAngle)” method. So far we have only created the path, to actually draw the arc on canvas we will call “stroke()” method. But since stroke will draw with default color, so before calling “stroke()“ we will set “strokeStyle” property of context to light gray.
    ctx.save();
    ctx.lineWidth = 35;
    ctx.beginPath();
    ctx.arc(77,135,40,acDegToRad(-40),acDegToRad(180),true); 
    ctx.strokeStyle = "rgb(110,110,110)";
    ctx.stroke();
    ctx.restore();
    

Drawing the “blue guy”

The next thing to be drawn is that blue guy coming out of the wall. This art consists of a wall, blue guy’s head, his tummy and then this hand & legs.
  • Wall: The wall is the just a simple slim and tall blue rectangle.
    ctx.save();	
    ctx.fillStyle = "rgb(0,160,212)";
    ctx.fillRect(162,20,8,300);		
    ctx.restore();
    
  • Head: The blue guy’s head is also a simple circle, but since we not have a direct method like “fillCircle()”, we’ll need to use a similar trick as we did for “2’s” arc. We will start a new path, add a full 360 degree arc and fill it with color. For filling we will use “fill()” method accompanied by “fillStyle” property set to light blue color, to fill the path with blue color thereby creating a filled circle.
    ctx.save();
    ctx.fillStyle = "rgba(256,256,256,0.75)";
    ctx.fillRect(0,0,300,350);
    ctx.fillStyle = "rgb(0,160,212)";
    ctx.beginPath();
    ctx.arc(225,80,35,acDegToRad(0),acDegToRad(360));
    ctx.fill();		
    ctx.restore();
    
    A thing to note here is that when you create a path you have two options, either to call “stroke()” method to draw that path using current “strokeStyle”, as we did earlier and will do for hand and legs, or to call “fill()”method to fill the path with current “fillStyle”, as we did just now for head and will do for tummy. We also have an option of calling “clip()” method (discussed later).
  • Tummy: The tummy of the blue guy is also drawn by creating a triangle path and filling the triangle with blue color. To create the triangle path we first start a new path, move the initial drawing point from origin or any last position (lets it be O) to a point on the wall below the head using “moveTo(x, y)” method which moves the drawing point from current draw point to a new point (let it be A) without adding the line between O & A to the path, then use “lineTo( x, y)” method which moves the drawing point to a new point (let it be B) and also adds the line between A & B to the path. Similarly add the third point (let it be C) to complete the three points of the triangle. This will also add the line between B & C to the path. Now optionally you can use “lineTo( x, y)” method to go back to point A and add line between C & A to the path and thus closing the path but by default the “fill()” will automatically assume a line between opening and closing points and will fill the enclosed area.
    ctx.save();
    ctx.fillStyle = "rgb(0,160,212)";
    ctx.beginPath();
    ctx.moveTo(170,90);  //point A
    ctx.lineTo(230,140); //point B
    ctx.lineTo(170,210); //point C
    ctx.fill(); //fill area between ABC
    ctx.restore();
    
  • Hand: For hand we will simply create two lines as we did above. A to B for shoulder to elbow and B to C for forearm. But by default the line is 1px wide first we will set “lineWidth” property of context to 25px, then since line’s ends and joints (at B) are rectangular by default, we will set both “lineCap” property, for line ends and “lineJoin” property to “round”. And since we want lines to be drawn instead of filling the space between, we will call “stroke()” method of context.
    ctx.save();	
    ctx.lineWidth = 25;
    ctx.lineCap = "round";
    ctx.lineJoin = "round"; 
    ctx.strokeStyle = "rgb(0,160,212)";
    ctx.beginPath();
    ctx.moveTo(222,150);  //point A
    ctx.lineTo(230,190);  //point B
    ctx.lineTo(270,220);  //point C
    ctx.stroke();
    ctx.restore();
    
  • Leg: The leg can be drawn exactly as we drew the hand so code will be much same as above except for the coordinates.
    ctx.save();
    ctx.lineWidth = 25;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.strokeStyle = "rgb(0,160,212)";
    ctx.moveTo(160,210);  //point A
    ctx.lineTo(195,260);  //point B
    ctx.lineTo(160,290);  //point C
    ctx.stroke();		
    ctx.restore();
    
    But there is a problem with above code, the result leg doesn’t look like what we want. Part of the leg is hidden in the wall, so we need to clip the extra piece of leg from the drawing.
  • Clip Leg: With above code we didn’t got what we wanted but fret not, “clip()” method comes to rescue. Clip is similar to fill method but instead of filling the area enclosed by the path with some color, it creates an enclosed invisible boundary (outline of triangle is drawn in figure only to highlight the clip area) where any drawing on it clipped if it does not lie in the clipping region and only the drawing lying in the clipping region is shown. So to clip legs protruding through the wall, we’ll first create a clipping region by creating a triangular path with one of its side coinciding with the wall and then draw the leg same as we drew the hand.
    ctx.save();
    //code for drawing clipping region
    ctx.beginPath();
    ctx.moveTo(170,200);  //point A
    ctx.lineTo(250,260);  //point B
    ctx.lineTo(170,320);  //point C
    ctx.lineTo(170,200);  //back to point A to close the path
    ctx.clip();           //set the above path for clipping region
    //code for drawing leg
    ctx.lineWidth = 25;
    ctx.lineCap = "round";
    ctx.strokeStyle = "rgb(0,160,212)";
    ctx.lineJoin = "round";
    ctx.beginPath();
    ctx.moveTo(160,210);
    ctx.lineTo(195,260);
    ctx.lineTo(160,290);
    ctx.stroke();		
    ctx.restore();
    
And that’s all we need to do to create the that Portal 2 Logo, Below is an animated canvas showing all the pieces we used to draw it (in fact every image in this article is actually drawn on the <Canvas> elements) accompanied by complete combined code I used to draw it. So I hope that you liked this article and stay tuned for my next post where I will discuss 2D animation on <Canvas>.

(Actual Source Code)


(function(){
    var ctx = document.getElementById("portalcanvas").getContext("2d");
	//function to convert deg to radian
    var acDegToRad = function(deg){
			return deg* (-(Math.PI / 180.0));    
		}

	//save the initial state of the context
	ctx.save();		
	//set fill color to gray
	ctx.fillStyle = "rgb(110,110,110)";
	//save the current state with fillcolor
	ctx.save();

	//draw 2's base rectangle
	ctx.fillRect(20,200,120,35);
	//bring origin to 2's base
	ctx.translate(20,200);
	//rotate the canvas 35 deg anti-clockwise
	ctx.rotate(acDegToRad(35));
	//draw 2's slant rectangle
	ctx.fillRect(0,0,100,35);
	//restore the canvas to reset transforms
	ctx.restore();
	//set stroke color width and draw the 2's top semi circle
	ctx.strokeStyle = "rgb(110,110,110)";
	ctx.lineWidth = 35;
	ctx.beginPath();
	ctx.arc(77,135,40,acDegToRad(-40),acDegToRad(180),true);
	ctx.stroke();

	//reset canvas transforms
	ctx.restore();

	//change color to blue
	ctx.fillStyle = "rgb(0,160,212)";
	//save current state of canvas
	ctx.save();
	//draw long dividing rectangle 
	ctx.fillRect(162,20,8,300);
	//draw player head circle
	ctx.beginPath();
	ctx.arc(225,80,35,acDegToRad(0),acDegToRad(360));
	ctx.fill();

	//start new path for tummy :)
	ctx.beginPath();
	ctx.moveTo(170,90);
	ctx.lineTo(230,140);
	ctx.lineTo(170,210);
	ctx.fill();

	//start new path for hand
	//set lineCap and lineJoin to "round", blue color 
	//for stroke, and width of 25px
	ctx.lineWidth = 25;
	ctx.lineCap = "round";
	ctx.strokeStyle = "rgb(0,160,212)";
	ctx.lineJoin = "round";
	ctx.beginPath();
	ctx.moveTo(222,150);
	ctx.lineTo(230,190);
	ctx.lineTo(270,220);
	ctx.stroke();

	ctx.beginPath();
	ctx.moveTo(170, 200);
	ctx.lineTo(250, 260);
	ctx.lineTo(170,320);
	ctx.clip();	

	//begin new path for drawing leg
	ctx.beginPath();
	ctx.moveTo(160,210);
	ctx.lineTo(195,260);
	ctx.lineTo(160,290);
	ctx.stroke();
	
	//restore the context back to its initial state
	ctx.restore();
})()
READ MORE - Introduction to HTML5 <Canvas>: Part 2 (Example)

Sunday, March 27, 2011

Posted by SAMAJ SHEKHAR

0

How to: Create a Twitter widget in your blog


So this my next attempt, after Google Code Prettify which i explained in previous post, to add custom features to my blog. In this post I'll explain how I made that Twitter Feed box you see in widgets column.

It uses little bit of HTML, CSS3 Styling and and jQuery to do the magic. I 'll give you a walk-through of how "I made it". I actually started this small app when someone at StackOverflow asked how to embed Tweet' text's special words like @usernames, #Hashtags and Url's in an anchor (<a>) tag, i wrote some small JS code to take raw tweet string Linkify it and return HTML. Later i moved on create a tweet box for my own Blog. in this walk-through to create a Tweet Feed Box for @samajshekhar (which is me of-course), so code and HTML are hard-coded with values related to my account but you can change it very well.
(The HTML and jQuery script is downloadable from my repository at Bitbucket, you can check it out and fork it to add custom features and styling).

Before starting i assume you have a little bit of knowledge of basic HTML, CSS (actually CSS3 for curves and gradients), jQuery library and some understanding of Twitter's API (its easy to understand and simple), I am using Public timeline API to get tweet in JSON format without authentication so we have a Rate-Limit of 150 requests per hour. So keeping these things in mind lets start!

The HTML

The HTML for the Tweeter Feed Box is simple collection of div(<div>) tags which make up skeleton to contain tweets. It contain hard coded username @samajshekhar (which is my username at Twitter).

<div>
    <div id="SPTFB">
        <div id="SPTFBHeader">  
         <a href="http://www.twitter.com/samajshekhar" target="_blank" style="text-decoration:none;color:#333;">
             <img alt="@samajshekhar" src="http://a2.twimg.com/a/1299109335/phoenix/img/twitter_logo_right.png" style="border:none;"/>
             <span>@samajshekhar</span>
         </a>
        </div>
        <div id="SPTFBBody">
             <span id="SPTFBLoading" style="display:block;font-size:10px;" class="SPTFBLoading">loading tweets...</span>
        </div>
        <div id="SPTFBFooter">   
            <table cellspacing="0px" cellpadding="0px">
                <tr>
                    <td>Developed By <a style="color:Black;" rel="author" href="http://shekhar-pro.blogspot.com">Samaj Shekhar</a><br/>License: Creative Commons</td>
                    <td><a style="color:White;" id="ShekharProCCLicenseLogo" rel="license" href="http://creativecommons.org/license/by/2.5/">cc</a></td>
                </tr>
            </table>      
        </div>
    </div>
</div>

Where:
SPTFB: is the main <div> which contains all the elements of this Twitter Feed Box (actually SPTFB is the acronym for Shekhar Pro Twitter Feed Box).
SPTFBHeader: is the <div> which act as title bar and contains the Twitter @username with a twitter image.
SPTFBBody: is the <div> in which all tweets are shown.
SPTFBLoading: is a <span> element which just shows a loading... text while we dynamically insert Tweets.
SPTFBFooter: is the Footer <div> contains my attribution and a link to Creative Commons page.

The Tweet text's <div> which will be added later will have a CSS class of ".SPTFBFeed"

The CSS

The CSS is what makes this app look like it should. Match the styling with the element id and class in the above shown HTML.

<style type="text/css">
    #SPTFB /*Acronym for ShekharProTwitterFeedBox*/
    {
        width:230px;
        height:450px;            
        padding:0px;            
    }
    #SPTFBHeader
    {
        height:40px; 
        padding:3px 0px 0px 10px;
        margin:0px;
    }
    #SPTFBBody
    {
        height:360px;
        margin:2px;
    }
    #SPTFBFooter
    {
        height:30px;
    }
    #SPTFB
    { 
        -moz-border-radius:20px 1px 1px 1px;
        -webkit-border-radius:20px 1px 1px 1px;
        border-radius:20px 1px 1px 1px;
        border:2px solid #9C9C9C; 
        background-color:#9C9C9C; 
    }
    #SPTFB a
    {
        text-decoration:underline;
        color:#666;            
    }
    #SPTFBHeader
    {            
        -moz-border-radius:18px 0px 0px 0px;
        -webkit-border-radius:18x 0px 0px 0px;
        border-radius:18px 0px 0px 0px; 
        border:1px hidden azure;
        font-family:Verdana;
        font-size:16px;
        overflow:hidden;
    }
    #SPTFBHeader , #ShekharProCCLicenseLogo
    {    
        background-color:#9C9C9C;
        background-image: -webkit-gradient(
            linear,
            left bottom,
            left top,
            color-stop(0.3, rgb(156,156,156)),
            color-stop(0.88, rgb(219,219,219))
        );
        background-image: -moz-linear-gradient(
            center bottom,
            rgb(156,156,156) 30%,
            rgb(219,219,219) 88%
        );
        overflow:hidden;
    }
    #SPTFBBody
    {
        -moz-border-radius:4px 4px 4px 4px;
        -webkit-border-radius:4px 4px 4px 4px;
        border-radius:4px 4px 4px 4px; 
        border:1px solid #888888;
        background-color:#efefef;
        overflow-y:auto;
        overflow-x:hidden;            
    }
    #SPTFBFooter
    {
        font-family:arial;
        font-size:11px;
        color:White;
        text-decoration:none;
        padding:5px 0px 0px 20px;
    }
    #ShekharProCCLicenseLogo
    {
        -moz-border-radius:50%;
        -webkit-border-radius:50%;
        border-radius:50%; 
        border:1px solid #666666;
        height:26px;width:26px;
        font-family:Verdana;
        font-size:18px;
        font-weight:bold;
        text-align:center;
        color:White;
        text-decoration:none !important;
        display:block;
        margin:0px 0px 0px 20px;padding:0px;
    }
    .SPTFBFeed , .SPTFBLoading
    {
        background-color:#d0d0d0;
        background-image: -webkit-gradient(
            linear,
            left bottom,
            left top,
            color-stop(0.25, rgb(179,179,179)),
            color-stop(0.75, rgb(224,224,224))
        );
        background-image: -moz-linear-gradient(
            center bottom,
            rgb(179,179,179) 25%,
            rgb(224,224,224) 75%
        );
        border:1px solid #888888;
        -moz-border-radius:3px;
        -webkit-border-radius:3px;
        border-radius:3px; 
        margin:3px;
        padding:3px;
        font-family:arial;
        font-size:13px;
        font-weight:normal;
        color:black;            
    }
</style>

There's nothing complicated about above CSS its simply contains styles related to margins, size, etc just go through and you will know what it does. It also has default colors with gradients so that it appears with matching color where gradients are where its not supported like in IE. If you don't know how to make gradients then there is a nice CSS3 Gradient Generator which you can use.

The Code !

The last and most important one is the code which does the actual work of filling the box with tweets. Now i know some JavaScript ninjas may frown at my code but this is what "I made" and you are free to improve it, however if you see anything obvious then add a comment and I will correct it. It small JavaScript that uses jQuery, so remember to include the jQuery in your document before using following code.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

The code can be divided in two parts, one is simple one which linkifies the tweet text, i.e surrounds the url's, #hashtags and @usernames in an anchor (<a>) tag and other is the code which actually brings in the tweets from Twitter

Code for Linkifier
var userNameRegEx = /@(\w*)\b/;
var hashTagRegEx = /#(\w*)\b/;
var urlLinkRegEx = /(^|[(\s]|&lt;)((?:(?:https?|ftp):\/\/|mailto:).+?)((?:[:?]|\.+)?(?:\s|$)|&gt;|[)])/;
function myTwitterLinkify(rawText) {
    var stringArray = rawText.split(' ');
    var stringStack = [];
    $.each(stringArray, function () {
        if (userNameRegEx.test(this)) {
            var userlink = '<a href="http://twitter.com/' + userNameRegEx.exec(this)[0].toString().replace('@', '') + '">' + this.toString() + '</a>';
            stringStack.push(userlink);
        }
        if (hashTagRegEx.test(this)) {
            var userlink = '<a href="http://twitter.com/search?q=' + escape(hashTagRegEx.exec(this)[0].toString()) + '">' + this.toString() + '</a>';
            stringStack.push(userlink);
        }
        if (urlLinkRegEx.test(this)) {
            var userlink = '<a href="' + urlLinkRegEx.exec(this)[0].toString() + '">' + this.toString() + '</a>';
            stringStack.push(userlink);
        }
        if (!userNameRegEx.test(this) && !hashTagRegEx.test(this) && !urlLinkRegEx.test(this)) {
            stringStack.push(this);
        }
    });
    return stringStack.join(' ');
}

Working of above code can be explained in following simple steps:

  1. Define Regular expression strings for each of @usernames, #hashtags and url.
  2. Take the string and split it for ' ' (space)into an array of words
  3. Take each word at a time and match it with all regular expression strings
  4. If a match is found then surround the word with anchor (<a>) tag and set its href="" attribute with respective url's and push the resultent string the stack, if not then simply insert that word in the stack.
    (usually its http://twitter.com/username for @username, http://twitter.com/search?q=hashtag for #hashtag and for urls just use the url itself.)
  5. Finally join the stack values with a ' ' (space) and return the complete string.
Code to fill tweets
var username = 'samajshekhar';  /* @username of the user at twitter*/
var format = 'json';            /* format in which to recive response, can be on of json, xml, rss, atom*/
var count = '6';                /* number of tweets to load*/
var include_retweets = 't';  /* wheather to include retweeets by user in timeline, can be true, t or 1*/
    /*the API uri at which we will make the call to get tweets*/
var theapiurl = 'http://api.twitter.com/1/statuses/user_timeline.' + format + '?callback=?';
var fillReqSucceded = false; /**/
var sptfbFillTimer = 'undefined'; /**/

/*
Function to fill tweets in the tweet box
*/
function fillTweets() {
    /*show loading... span*/
    $('#SPTFBLoading').fadeIn('slow');
    $.getJSON(theapiurl,
        {
            /*query string parameters to be passed to the api url*/
            screen_name: username,          /* @username of the user at twitter*/
            count: count,                   /* number of tweets to load*/
            trim_user: 't',                 /* whether to include extra information related to user profile,can be true, t or 1*/
            include_rts: include_retweets   /* whether to include retweets by user in timeline, can be true, t or 1*/

        },
        function (data) {
            /*remove all previous tweets already in the box*/
         $('.SPTFBFeed').remove();
         /*read each tweet linkify  its text and append it to #SPTFBBody <div> */
         $.each(data, function () {
                 var elem = $('<div/>');
                 elem.addClass('SPTFBFeed').html(myTwitterLinkify(this.text));                                                        
                 $('#SPTFBBody').append(elem);
         });
         /**
          *if we reached this far then we surely succeed in getting
          * tweets and filling it in the box, so just remove the loading... span
          */
         fillReqSucceded = true;
         $('#SPTFBLoading').fadeOut('slow');
        });
    /**
     *if this is NOT the first time we are flling tweets and we didn't succeed then 
     *show error in span schedule next fill after 20 seconds and exit this function
     */    
    if (sptfbFillTimer != 'undefined' && fillReqSucceded === false) {
        $('#SPTFBLoading').html('Problem in loading Tweets :(<br/><br/>Please wait while we try again...').css({ 'color': 'red' }); 
        sptfbFillTimer = setTimeout('fillTweets()', 20000); 
        return; 
    }
    /*if we reached this far then all is well and lets schedule the next fill to occur after 30 seconds*/    
    sptfbFillTimer = setTimeout('fillTweets()', 30000);
    /*just reset the style of loading... span as previous failure may have changed it*/
    $($('#SPTFBLoading').html('loading tweets...')).css({ 'color': 'black' });
}

This 'fillTweets()' method is the one which you are going to call when you are ready to load Tweets like at '$(document).ready();'. Now the for the working of above code comments are well enough , also as you can see we have defined some variables to store configuration related to the API uri on which we will make GET request to receive the JSON for tweet (we can also request XML for tweets, but we will need to change the code for that). Also note that we have included a 'callback=?' parameter to make the JSON response a JSONP.

And that's all you need to do. Below is the snapshots f how it looked in Firefox3,4 and IE9


READ MORE - How to: Create a Twitter widget in your blog

Saturday, January 1, 2011

Posted by SAMAJ SHEKHAR

0

Serializing and Deserializing Data from Json to .Net Objects. ( Example Facebook Feeds)


A very very Happy New Year to you all. I thought why not start this year with a nice blog post, so here i am with a post on how to Deserialize data from Json to a .Net Object and back again.Many libraries exist for this Job most notabely the Json.Net and Dynamic Rest library by Nikhil Kothari

But developer community has always asked why microsoft didn't have it in the Frame work. Well now they have one. It comes in frame work now with an added dll of "System.Web.Extentions.dll". That provides us the Class JavascriptSerializer which you can use by including a using statement as follows.

using System.Web.Script.Serialization;

Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.

What is JSON?

JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.

A Simple Example

So lets understand this process with an example, since i am currently working on a project which uses facebook to query data, i think this will be helpful to the facebook developer community also. So first you need to define a class that matches the JSON object you are receiving. like a class if a Data in Json looks like below.

{
"obj1":"data",
"obj2":"10004",
"obj3":{
      "subobj1":"data",
      "subobj2":"data"
      }
"obj4":"data"
}

Then the corresponding class for that in .Net will be

public class MyObj1
{
    public string     obj1 { get; set; }
    public int        obj2 { get; set; }
    public MyObj2     obj3 { get; set; }
    public string     obj4 { get; set; }
}

public class MyObj2
{
    public string subobj1 { get; set; }
    public string subobj2 { get; set; }
}

Notice The obj3 in Json is a completely different class as it contains sub fields so a different class fo that in .Net. Also Remember JavascriptSerializer uses reflections to match field or property "names" with that in "Json" so be careful.

Now to deserialize above Json data to the .Net classes juat include the following line.

JavaScriptSerializer sr = new JavaScriptSerializer();
string jsondata = /*your json string here*/;
//Now with this line the Json string will be converted in MyObj1 object type
MyObj1 converted = sr.Deserialize<MyObj1>(jsondata);
Facebook Example (Deserializing Facebook Feeds)

Now the data returned by facebook's Graph API is also in Json and below is an sample data returned by

http://graph.facebook.com/samajshekhar/feed?limit=1

{
   "data": [
      {
         "id": "100000570310973_182862925076050",
         "from": {
            "name": "Samaj Shekhar",
            "id": "100000570310973"
         },
         "message": "#Wow A decade has passed .. #Happy New year to every one....May this new  year be the most luckiest for you and every one.",
         "icon": "http://photos-d.ak.fbcdn.net/photos-ak-snc1/v27562/23/2231777543/app_2_2231777543_9553.gif",
         "actions": [
            {
               "name": "@samajshekhar on Twitter",
               "link": "http://twitter.com/samajshekhar?utm_source=fb&utm_medium=fb&utm_campaign=samajshekhar&utm_content=20985773201301504"
            }
         ],
         "type": "status",
         "application": {
            "name": "Twitter",
            "id": "2231777543"
         },
         "created_time": "2010-12-31T23:32:54+0000",
         "updated_time": "2010-12-31T23:32:54+0000"
      }
   ],
   "paging": {
      "previous": "http://graph.facebook.com/samajshekhar/feed?limit=1&since=2010-12-31T23%3A32%3A54%2B0000",
      "next": "http://graph.facebook.com/samajshekhar/feed?limit=1&until=2010-12-31T23%3A32%3A53%2B0000"
   }
}

Don't get confused its just little more data of different types including arrays. ( To get data from facebook you can use System.Net.HttpWebRequest and System.Net.HttpWebResponse class). So Now the equivalent .Net classes will be as follows.

Note:

I have included only the classes needed for the above feed for a complete class that accommodate all fields returned in feed with and without access token can be found here at

http://thesharepage.codeplex.com/SourceControl/changeset/view/5405#100657

public class FacebookFeedsWithoutToken
{
 public FacebookFeedWithoutToken[] data { get; set; }
 public ReturnedDataPaging paging { get; set; }
}

public class FacebookFeedWithoutToken
{
 public string id { get; set; }
 public NameIdPair from { get; set; }
 public string message { get; set; }
 public Uri icon { get; set; }
 public NameLinkPair[] actions { get; set; }
 public string type { get; set; }
 public NameIdPair application { get; set; }
 public DateTime created_time { get; set; }
 public DateTime updated_time { get; set; }
}

public class NameIdPair
{
 public string name { get; set; }
 public string id { get; set; }
}

public class NameLinkPair
{
 public string name { get; set; }
 public Uri link { get; set; }
}

Now the classes are ready we just need to convert from json string to .Net object types. add the following line similar to above.

JavaScriptSerializer sr = new JavaScriptSerializer();
string jsondata = /*your json string here*/;
FacebookFeedsWithoutToken converted = sr.Deserialize<FacebookFeedsWithoutToken>(jsondata);

Thats all you have to do.

And once again Happy new year.

READ MORE - Serializing and Deserializing Data from Json to .Net Objects. ( Example Facebook Feeds)

Wednesday, December 15, 2010

Posted by SAMAJ SHEKHAR

1”

Creating a Facebook like badge


This a small walkthrough of how you can go about creating a Bage just like Facebook Badge.

Infact While developing my project i myself thought of creating a facebook like badge that can later be saved on the server and used with a link to it. Following is the complete class code to generate the badge(Its also available on codeplex, and following is basically explaination of code there).

(Note: replace the"Image.FromFile(@"C:\Users\SHEKHAR\Desktop\Test HTML\tsp1.png");" with a path to image that can be used as a title bar in the badge.)

The Badge Class

First Declare the Class and some variables to hold on required information. (made it sealed so it couldn't be inherited).

public sealed class TSPBadge
{
 /// <summary>
 /// Image for the TSP badge's title bar (Static Field)
 /// </summary>
 private static Image TSPBadgeTitleBar = Image.FromFile(@"C:\Users\SHEKHAR\Desktop\Test HTML\tsp1.png");

 /// <summary>
 /// The Default Width for TSP Badge (Constant Field)
 /// </summary>
 public const int DBadgeWidth = 300;

 /// <summary>
 /// The Default Height for TSP Badge (Constant Field)
 /// </summary>
 public const int DBadgeHeight = 500;

 /// <summary>
 /// Set this variable to true if a TSP badge has been successfully made
 /// </summary>
 public bool IsMade = false;

 /// <summary>
 /// Initializes the static members of the TSPBadge Class (Static Constructor)
 /// </summary>
}
Class Constructors

Now lets define both static and instance constructors.

/// <summary>
/// Initializes the static values of TSPBadge with default values
/// </summary>
static TSPBadge()
{
BadgeWidth = DBadgeWidth;
BadgeHeight = DBadgeHeight;
}

/// <summary>
/// Initializes a new Instance of TSPBadge with default values
/// </summary>
public TSPBadge()
{
 IsMade = false;
 UserPic = null;
 UserName = null;
 EmailID = null;
 UserStatus = null;
}

/// <summary>
/// Initializes a new Instance of TSPBadge with specified Width and Height
/// </summary>
/// <param name="Width">The Width for the TSP Badge</param>
/// <param name="Height">The Height for the TSP Badge</param>
public TSPBadge(int Width, int Height)
{
 BadgeWidth = Width;
 BadgeHeight = Height;
}

/// <summary>
/// Initializes a new Instance of TSPBadge with specified Image, Name, Status and EmailID.
/// </summary>
/// <param name="userpic">The user's picture</param>
/// <param name="username">The name of the user</param>
/// <param name="emailID">The user's EmailID</param>
/// <param name="userstatus">The user's most recent status text</param>
public TSPBadge(Image userpic, string username, string emailID, string userstatus)
{
 IsMade = false;
 UserPic = new Bitmap(userpic);
 UserName = username.ToUpper(CultureInfo.InvariantCulture);
 EmailID = emailID;
 UserStatus = userstatus;
}
Properties

Following are defination of some properties that will help you to alter the settings when required.

/// <summary>
/// Gets or Sets the Width to be used for drawing TSP badge. (Static Property)
/// </summary>
public static int BadgeWidth { get; set; }

/// <summary>
/// Gets or Sets the Height to be used for drawing TSP badge. (Static Property)
/// </summary>
public static int BadgeHeight
{
 get
 {
  return _BadgeHeight;
 }
 set
 {
  GraphicsUnit gu = GraphicsUnit.Pixel;
  //The TSP Badge's Minimum height is the height of TSP TitleBar's height
  if (value <= (int)TSPBadgeTitleBar.GetBounds(ref gu).Height)
  {
   _BadgeHeight = (int)TSPBadgeTitleBar.GetBounds(ref gu).Height;
  }
  else
  {
   _BadgeHeight = value;
  }
 }
}
private static int _BadgeHeight;

/// <summary>
/// Gets or Sets the User Picture to be used for drawing TSP Badge
/// </summary>
public Bitmap UserPic { get; set; }

/// <summary>
/// Gets or Sets the User Name to be used for drawing TSP Badge
/// </summary>
public string UserName { get; set; }

/// <summary>
/// Gets or Sets the User EmailID to be used for drawing TSP Badge
/// </summary>
public string EmailID { get; set; }

/// <summary>
/// Gets or Sets the User's Status text to be used for TSP Badge
/// </summary>
public string UserStatus { get; set; }
Methods for drawing

Lets draw the badge!

/// <summary>
/// Draws a TSP Badge on bitmap with specified Image, Name, Status and EmailID. (Static Method)
/// </summary>
/// <param name="userpic">The user's picture</param>
/// <param name="username">The name of the user</param>
/// <param name="emailID">The user's EmailID</param>
/// <param name="userstatus">The user's most recent status text</param>
/// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
public static Bitmap MakeBadge(Image userpic, string username, string emailID, string userstatus)
{
 Bitmap bmp = new Bitmap(BadgeWidth, BadgeHeight);
 Graphics gf = Graphics.FromImage(bmp);
 GraphicsUnit gu = GraphicsUnit.Pixel;
 string BatchString = String.Format("{0}\n\nEMAIL:  {1}\n\nSTATUS:  {2}", username.ToUpper(CultureInfo.InvariantCulture), emailID, userstatus);
 //We are taking 60% of the bitmap space for User picture - (int)((float)BadgeHeight * (60F / 100F))
 //Write status, name etc in rest of 40% bitmap space
 float PicPer = 60F;
 float RstPer = 100F - PicPer;
 gf.Clear(Color.White);
 gf.DrawImage(userpic, new Rectangle(2, 2, BadgeWidth - 4, (int)((float)BadgeHeight * (PicPer / 100F)))); //NOTE: The rectangle here takes a non-zero based width/height so 300
 gf.DrawImage(TSPBadgeTitleBar, new Rectangle(0, 0, BadgeWidth, (int)TSPBadgeTitleBar.GetBounds(ref gu).Height));
 //TODO: Insert code to check name dosen't go out of title bar and get trimmed
 gf.DrawString(username.ToUpper(CultureInfo.InvariantCulture), new Font(new FontFamily("Arial"), 10F), Brushes.White, new PointF(5, 6));
 gf.DrawRectangle(Pens.Black, 0, 0, BadgeWidth - 1, BadgeHeight - 1); //NOTE: DrawRectangle takes a 0 based width/height so 300-1
 gf.DrawRectangle(Pens.Black, 1, 1, BadgeWidth - 3, ((int)((float)BadgeHeight * (PicPer / 100F))) + 1);
 gf.DrawRectangle(Pens.Black, 1, ((int)((float)BadgeHeight * (PicPer / 100F))) + 3, BadgeWidth - 3, ((int)((float)BadgeHeight * (RstPer / 100F))) - 5);
 gf.DrawString(BatchString, new Font(new FontFamily("Arial"), 10F), Brushes.Black, new RectangleF(5, ((int)((float)BadgeHeight * (PicPer / 100F))) + 6, BadgeWidth - 7, ((int)((float)BadgeHeight * (RstPer / 100F))) - 5), StringFormat.GenericTypographic);
 return bmp;
}

Now lets add some more methods in the class to make the MakeBadge static method accessible to instance methods and customizable too.

/// <summary>
/// Draws a TSP Badge on bitmap.
/// <para>NOTE: This function requires that all the requiremens are set already other wise it returns a null bitmap</para>
/// </summary>
/// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
public Bitmap GetBadge()
{
 IsMade = false;
 Bitmap bmp = null;
 if (UserPic != null && UserName != null && EmailID != null && UserStatus != null)
 {
  bmp = TSPBadge.MakeBadge(UserPic, UserName, EmailID, UserStatus);
  IsMade = true;
 }
 return bmp;
}

/// <summary>
/// Draws a TSP Badge on bitmap with specified Image, Name, Status and EmailID.
/// </summary>
/// <param name="userpic">The user's picture</param>
/// <param name="username">The name of the user</param>
/// <param name="emailID">The user's EmailID</param>
/// <param name="userstatus">The user's most recent status text</param>
/// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
public Bitmap GetBadge(Image userpic, string username, string emailID, string userstatus)
{
 IsMade = false;
 UserPic = new Bitmap(userpic);
 UserName = username.ToUpper(CultureInfo.InvariantCulture);
 EmailID = emailID;
 UserStatus = userstatus;
 Bitmap bmp = TSPBadge.MakeBadge(UserPic, UserName, EmailID, UserStatus);
 IsMade = true;
 return bmp;
}

That's all Happy Coding :)

READ MORE - Creating a Facebook like badge

Monday, September 13, 2010

Posted by SAMAJ SHEKHAR

1”

Making Any Control Draggable in Silverlight & WPF


Introduction

Silverlight gives you easy access to make your User Controls come alive. For example you can make any control in Silverlight draggable. Here's how:

In your Code add a TranslateTransform inside your layout grid of your user control. The TranslateTransform will allow you to move your grid along the x and y coordinates of your application

Listing 1 - Adding the TranslateTransform to your control
<Grid x:Name="LayoutRoot" >
        <Grid.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform x:Name="LocalTranslateTransform"/>
            </TransformGroup>
        </Grid.RenderTransform>

Now we want to pick a control inside the UserControl to grab onto. In our sample we will use a Border control. Inside the Border control, we'll add mouse events to handle the various states of dragging with the mouse.

Listing 2 - Hooking up the mouse events to the Border control
<Border x:Name="myToolbar" MouseLeftButtonDown="OnToolbarClicked"
 MouseLeftButtonUp="OnToolbarReleased" MouseMove="OnToolbarMoving"  />
The Code

The XAML part was pretty simple. Now let's look at the code behind. All of the dragging functionality is handled by our 3 event handlers: OnToolbarClicked, OnToolbarReleased, and OnToolbarMoving. When we first click down on the border control, we need to record the initial offset point for our transform. We also need to set the state to mouseDownInToolbar to true to indicate we are dragging. Finally we need to set the mouse mode to capturing inside the border control.

Listing 3 - Handling the mousedown event inside the border
private void OnToolbarClicked(object sender, MouseButtonEventArgs e)
{
    mouseDownInToolbar = true;
    DragOffset = e.GetPosition(LayoutRoot);
    toolbarBorder.CaptureMouse();
}

While the mouse is in the mouseDownInToolbar state, we need to translate the position of the toolbar in reference to the position of the mouse. Listing 4 illustrates how we go about this. We get the position of the mouse relative to the main grid of the control. Then we change the TranslateTransform of the grid based on the new position of the mouse. We also need to offset the current mouse position by the original location of the mouse when we first clicked down in the control. Everytime we move the mouse, the new TranslateTransform will be computed and our control will move to the translated location. The mouse cursor will remain at the point when we first clicked the toolbar.

Listing 4 - handling the dragging of the control while the mouse is moving
private void OnToolbarMoving(object sender, MouseEventArgs e)
{
    if (mouseDownInToolbar)
    {
        // we want to move it based on the position of the mouse
        moveUserControl(e);
    }
}

private void moveUserControl (MouseEventArgs e)
{
    Point mousePos = e.GetPosition(LayoutRoot);
    Double newX = LocalTranslateTransform.X + (mousePos.X - DragOffset.X);
    Double newY = LocalTranslateTransform.Y + (mousePos.Y - DragOffset.Y);
    LocalTranslateTransform.X = newX;
    LocalTranslateTransform.Y = newY;
}

When the user unclicks the mouse, we need to stop the drag process. The MouseUp event handler will release the mouse capture and set the mouseDownInToolbar state to false. This will prevent the toolbar to continue to move as we drag the mouse around the screen.

Listing 5 - Handling Mouse Up when dragging the Toolbar
private void OnToolbarReleased(object sender, MouseButtonEventArgs e)
{
    mouseDownInToolbar = false;
    toolbarBorder.ReleaseMouseCapture();
}
Conclusion

Manipulating size and position of controls is fairly easy in Silverlight with the power of transforms. Dragging a control is accomplished using the TranslateTransform in conjunction with mouse events and functions. You can probably take this a step further and build your own docking framework. Anyway, drag yourself away from conventional controls in Windows and enjoy the power and flexibility of WPF in the browser with Silverlight.

Originally taken from Here
READ MORE - Making Any Control Draggable in Silverlight & WPF

Saturday, August 28, 2010

Posted by SAMAJ SHEKHAR

4

Introduction to using WP7 Accelerometer


This post is about introducing you Windows Phones Accelerometer (I have taken following contents from Charles Petzold's book "Programming Windows Phone 7 - Special Excerpt 2". The contents are Copyright of Microsoft and is used only for informational purpose). You can get more detailed information about using Accelerometer from above mentioned book, complete book is still to be released later this year.

Windows Phones contain an accelerometer — a small hardware device that essentially measures force, which elementary physics tells us is proportional to acceleration. When the phone is held still, the accelerometer responds to the force of gravity, so the accelerometer can tell your application the direction of the Earth relative to the phone. It is convenient to represent the accelerometer output as a vector in three-dimensional space. Vectors are commonly written in boldface, so the acceleration vector can be symbolized as (x, y, z). XNA defines a three-dimensional vector type; Silverlight does not.

While a three-dimensional point (x, y, z) indicates a particular location in space, the vector (x, y, z) encapsulates instead a direction and a magnitude. Obviously the point and the vector are related: The direction of the vector (x, y, z) is the direction from the point (0, 0, 0) to the point(x, y, z). But the vector (x, y, z) is definitely not the line from (0, 0, 0) to (x, y, z). It’s only the direction of that line. The magnitude of the vector (x, y, z) is calculable from the three-dimensional form of the Pythagorean Theorem:

Magnitude = Math.sqrt( Math.pow(x,2), Math.pow(y,2), Math.pow(z,2) )
where:
Math.sqrt() function returns the square root of a number
Math.pow() function returns a number raised to a power
For working with the accelerometer, you can imagine the phone as defining a threedimensional coordinate system. No matter how the phone is oriented, the positive Y axis points from the bottom of the phone (with the buttons) to the top, the positive X axis points from left to right.



When the phone is still, the accelerometer vector points towards the Earth. The magnitude is 1, meaning 1 g, which is the force of gravity on the earth's surface. When holding your phone in the upright position, the acceleration vector is (0, –1, 0), that is, straight down.

So lets start, To use the accelerometer, you’ll need a reference to the Microsoft.Devices.Sensors library, and a using directive for the Microsoft.Devices.Sensors namespace. In WMAppManifest.xml, you need
<Capability Name="ID_CAP_SENSORS">

You create an instance of the Accelerometer class, set an event handler for the
ReadingChanging event, and call Start. And then it gets a little tricky. Let’s take a look at a project named SilverlightAccelerometer project that simply displays the current reading in its content grid. A centered TextBlock is defined in the XAML.

<Grid x:Name="ContentGrid" Grid.Row="1">
    <TextBlock Name="txtblk"
     HorizontalAlignment="Center"
     VerticalAlignment="Center" />
</Grid>

This is a program that will display the accelerometer vector throughout its lifetime, so it creates the Accelerometer class in its constructor and calls Start:

public MainPage()
{
    InitializeComponent();
    Accelerometer acc = new Accelerometer();
    acc.ReadingChanged += OnAccelerometerReadingChanged;
    try
    {
        acc.Start();
    }
    catch (Exception exc)
    {
        txtblk.Text = exc.Message;
    }
}

The documentation warns that calling Start might raise an exception, so the program protects itself against that eventuality. These user-interface objects are not thread safe; they are not built to be accessed simultaneously from multiple threads. For this reason, Silverlight will not allow you to access a user-interface object from a non-UI thread.

This means that the OnAccelerometerReadingChanged method cannot directly access the TextBlock element to set a new value to its Text property. Fortunately, there’s a solution involving a class named Dispatcher defined in the System.Windows.Threading namespace. Through the Dispatcher class, you can post jobs from
a non-UI thread on a queue where they are later executed by the UI thread.

The Dispatcher class defines a method named CheckAccess that returns true if you can access a particular user interface object from the current thread. (The CheckAccess method is also duplicated by DependencyObject itself.) If an object can’t be accessed from the current thread, then Dispatcher provides two versions of a method named Invoke that you use to post the job to the UI thread.

The verbose version requires a delegate and a method defined in accordance with that delegate. The delegate (and method) should have no return value, but as many arguments as you need to do the job, in this case setting a string to the Text property of a TextBlock:
delegate void SetTextBlockTextDelegate(TextBlock txtblk, string text);
void SetTextBlockText(TextBlock txtblk, string text)
{
    txtblk.Text = text;
}
The OnAccelerometerReadingChanged is responsible for calling SetTextBlockText. It first makes use of CheckAccess to see if it can just call the SetTextBlockText method directly. If not, then the handler calls the BeginInvoke method. The first argument is an instantiation of the delegate with the SetTextBlockText method; this is followed by all the arguments that SetTextBlockText requires:
void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
{
    string str = String.Format("X = {0:F2}\n" +
    "Y = {1:F2}\n" +
    "Z = {2:F2}\n\n" +
    "Magnitude = {3:F2}\n\n" +
    "{4}",
    args.X, args.Y, args.Z,
    Math.Sqrt(args.X * args.X + args.Y * args.Y +
    args.Z * args.Z),
    args.Timestamp);
    if (txtblk.CheckAccess())
    {
        SetTextBlockText(txtblk, str);
    }
    else
    {
        txtblk.Dispatcher.BeginInvoke(new
        SetTextBlockTextDelegate(SetTextBlockText),
        txtblk, str);
    }
}
This is not too bad, but the need for the code to jump across threads has necessitated an additional method and a delegate. Is there a way to do the whole job right in the event handler?
Yes! The BeginInvoke method has an overload that accepts an Action delegate, which defines a method that has no return value and no arguments. You can create an anonymous method right in the BeginInvoke call. The complete code following the creation of the string object looks like this:
if (txtblk.CheckAccess())
{
    txtblk.Text = str;
}
else
{
    txtblk.Dispatcher.BeginInvoke(delegate()
        {
            txtblk.Text = str;
        });
}
The anonymous method begins with the keyword delegate and concludes with the curly
brace following the method body. The empty parentheses following the delegate keyword are not required.



The Windows Phone 7 emulator doesn’t contain any actual accelerometer, so it always reports a value of (0, 0, –1), which indicates the phone is lying on a flat surface:



READ MORE - Introduction to using WP7 Accelerometer

Tuesday, August 10, 2010

Posted by SAMAJ SHEKHAR

0

Invoking C# Compiler from your Code



Imagine you have just generated some code using a code generation technique, wouldn’t it be really cool to then programmatically call the C# language compiler and generate assemblies from the generated code?
Let’s imagine we used an Xslt transformation to generate some code:
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("Program.xslt");
transform.Transform("Program.xml", "Program.cs");
Using the CSharpCodeProvider class we can now programmatically call the C# compiler to generate the executable assembly. We’ll begin by advising the compiler of some options we’d like it to use when compiling our code using the CompilerParameters class.
CompilerParameters parameters = new CompilerParameters();
We’ll specify that the assembly to be created should be an executable and we’ll also specify such things as whether debug information should be included, the warning level, whether warnings should be treated as errors etc.
parameters.GenerateExecutable = true;
parameters.IncludeDebugInformation = true;
parameters.GenerateInMemory = false;
parameters.TreatWarningsAsErrors = true;
parameters.WarningLevel = 3;
parameters.CompilerOptions = "/optimize";
parameters.OutputAssembly = "Program.exe";
Using the compiler parameters we can now compile the C# code using the CSharpCodeProvider class and get the results of the compilation as an instance of the CompilerResults class.
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, new string[] { "Program.cs" });
While the code you generated is unlikely to have any compiler warnings or errors, other developers may be less fortunate and therefore they can access the Errors property of the CompilerResults class to determine what went wrong. Actually the Errors property contains both compiler errors and warnings although the following simple LINQ queries allow you to examine the warnings and errors in isolation.
var warnings = from e in results.Errors.Cast()
      where e.IsWarning
      select e;
var errors = from e in results.Errors.Cast()
    where !e.IsWarning
    select e;
While code generation is very cool, we generate code to ultimately create assemblies that we can either execute or reference from other code. If you’re programmatically generating code why not next time also programmatically generate the assemblies too!

Post originally taken from Here
READ MORE - Invoking C# Compiler from your Code