Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, March 5, 2011

Posted by SAMAJ SHEKHAR

2

Google Code Prettify


For a long while code snippets on my blog were inconsistently formatted as i always kept experimenting with CSS for code and every post came out with its own formatting, sometimes i used tools on web to format my code and give me the HTML, so it looked very awful. Recently i found out "Google Code Prettify", its a java-script code which contains those lexers to recognize the code and format it appropriately accompanied by a CSS which you can of-course customize it to suit your needs. Its easy to use and supports almost all languages, from java to Haskel and all C family languages. Though there is a readme at Google code website here are the steps to add it to your blog or website.

Setup

  • Download a distribution
  • Include the script and style-sheets in your document (you will need to make sure the css and js file are on your server, and adjust the paths in the script and link tag)
  • <link href="prettify.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="prettify.js"></script>
  • Add onload="prettyPrint()" to your document's body tag.
  • Modify the stylesheet to get the coloring you prefer
  • Usage

    Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code> and it will automatically be pretty printed. The original
    class Voila {
    public:
      // Voila
      static const string VOILA = "Voila";
    
      // will not interfere with embedded tags.
    }
    Prettier (I have applied custom CSS on my blog so it will be different then what you'll get)
    class Voila {
    public:
      // Voila
      static const string VOILA = "Voila";
    
      // will not interfere with embedded tags.
    }
    So as it says you will need to download it on your own server and then link it in your script tag, but for your (and my own) convenience i have hosted it at Bitbucket DVCS Source Code hosting site. On the download page you will find the minified versions of the prettify.js(19kb) and prettify.css(1kb)

    So your tags become:

    <link href="http://cdn.bitbucket.org/shekharpro/google_code_prettify/downloads/prettify.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="http://cdn.bitbucket.org/shekharpro/google_code_prettify/downloads/prettify.js"></script>
    READ MORE - Google Code Prettify

    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

    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