Blog

Categorised by 'ASP.NET'.

  • In nearly all my previous projects I've worked on required some kind of manipulation with reading some form of JSON data.

    To allow better integration into my application, I always create strongly-typed classes that mirror the structure of the incoming data feed. This in turn allows me to serialize the JSON and select specific properties I require. But sometimes, its quite difficult and confusing to the exact class structure right, especially when the JSON contains lots of fields of data.

    When I find this is the case, I use json2csharp.com. By simply pasting the contents of your JSON, the site does all the hard work and creates all the strongly-typed classes for you.

  • Ever since Twitter ditched version 1 of their API to version 1.1, an additional hurdle created when attempting to get any data from Twitter. Authentication (using OAuth) is now required on all API request endpoints. I can see why Twitter decided to go down this route but it does add a little headache when carrying out the most simplest requests.

    In all the sites I have worked on, I've always relied on third party libraries to help me interact with Twitter, such as Twitterizer (no v1.1 support) and TweetSharp. But due to the increased complexity on some of the sites I've been working on, third party libraries don't seem to cut the mustard any more. A more scalable solution is required...

    I came across a really simple and expandable class library called OAuthTwitterWrapper that stemmed from a StackOverflow question I found. Out-of-the-box, this library contains calls required to retrieve a user's timeline and return searches which is great to get you up and running quickly.

    The OAuthTwitterWrapper provided me a really good basis to add further Twitter features, for example a list of users favourite tweets.

    If you don't plan on doing anything too complex when interacting with the Twitter API, third party libraries such as TweetSharp will meet your everyday needs. However, if you want more control over how you make requests, the OAuthTwitterWrapper provides a good foundation.

  • Postbacks can be annoying. Especially when you have a long page of content with a form at the bottom and on button click causes the page to skip back to the top of the page.

    For a user who is not used to a site, this can be incredibly annoying and disorientating simply due to the fact the page has moved to a different position. This isn't so much of an issue if you happen to have a webpage that is low on content and a form will always be in clear view.

    But there is quite a nice easy way to get back to a specific area of a page by using the following line of JavaScript will be added in the page after a postback has occurred.

    if (Page.IsPostBack)
    {
        ScriptManager.RegisterStartupScript(this, typeof(string), "PostbackFocus", "window.location.hash = 'feedback-form'", true);
    }
    

    By placing this code in your Page_Load method, the user will be taken to an anchor point placed within the page. In this case, a <div> with an ID attribute of "feedback-form".

  • I've been a .NET Developer for around 6 years and it still amazes me how I can overlook something that I never really questioned. For example, when a user control is hidden, I always assumed that all the code it contained would never run since until it was made visible.

    However, after being told by one of my work colleagues that in fact a hidden user control will always run, it will just simply is hidden by the client. After searching the web for a definitive answer, I found a StackOverflow post that fully backed up his theory: http://stackoverflow.com/questions/12143693/hiding-user-controls-using-code-behind-does-internal-code-still-run-ie-am-i.

    As the StackOverflow post suggests, the most performance efficient way to show/hide a user control is by dynamically loading it in when required.

    if (jobs.Count > 0)
    {
         MyPlaceholder.Controls.Add(Page.LoadControl("/Controls/Listings/JobsList.ascx"));
    }
    

    As you can see in my example above, I'm loading my user control to a place holder in the page.

  • Sometimes optimising images to have an adequate image to file size ratio can be difficult when dynamically generating images using “System.Drawing”.

    Over the years, I have worked on quite a few different projects around the use of “System.Drawing” and recently I found a flexible way of being able to have control over the image quality and file size.

    Here’s a snippet of of code from my Generic Handler (.ashx) file:

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
    
        //Create a new Bitmap
        Bitmap oBitmap = new Bitmap(800, 800, PixelFormat.Format24bppRgb);
    
        //Load Background Graphic from Image
        Graphics oGraphics = Graphics.FromImage(oBitmap);
    
        #region Your Image Code
         
        //Insert your code here.
    
        #endregion
    
        #region Stage 1: Image Quality Options
        
        oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        oGraphics.SmoothingMode = SmoothingMode.HighQuality;
        oGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
        oGraphics.CompositingQuality = CompositingQuality.HighQuality;
        
        #endregion
    
        //Clear graphic resources
        oGraphics.Dispose();
    
        #region Stage 2: Image Quality Options
    
        //Output image
        ImageCodecInfo[] Info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
        EncoderParameters Params = new System.Drawing.Imaging.EncoderParameters(1);
        Params.Param[0] = new EncoderParameter(Encoder.Quality, 100L); //Set image quality
        context.Response.ContentType = Info[1].MimeType;
        oBitmap.Save(context.Response.OutputStream, Info[1], Params);
    
        #endregion
    }
    

    System.Drawing.Graphics Optimisations

    In all my “System.Drawing” development projects, I’ve always set the graphic object quality options (lines 19-22) and found that it never really worked for me. The reason for this is because I always placed these settings after creating my System.Drawing.Graphics object prior to my custom code. So the image was getting optimised before any of my functionality had taken place. Rubbish!

    The key is to set all your System.Drawing.Graphics object settings just before you dispose of it. Makes sense doesn’t it? Don’t know how I made such a noob mistake.

    By default, .NET uses the web safe options when converting Bitmap to an image and setting those four properties will have a big affect on how your image looks.

    Compression Level

    This is the good bit!

    .NET gives you the ability to carry out further tweaks on how your image will be rendered by allowing us to set the compression level. The compression level can be tweaked by modifying the value passed to the “EncoderParameter” constructor (line: 34).

    For another example of how this can be used, take a look at the following MSDN article: http://msdn.microsoft.com/en-us/library/bb882583.aspx

  • Safari iOS6It wasn’t until today I found that the Safari browser used on iPad and iPhone caches page functionality to such an extent that it stops the intended functionality. So much so, it affects the user experience. I think Apple has gone a step too far in making their browser uber efficient to minimise page loading times.

    We can accept browsers will cache style-sheets and client side scripts. But I never expected Safari to go as far as caching responses from web services. This is a big issue. So something as simple as the following will have issues in Safari:

    // JavaScript function calling web service
    function GetCustomerName(id)
    {
        var name = "";
    
        $.ajax({
            type: "POST",
            url: "/Internal/ShopService.asmx/GetCustomerName",
            data: "{ 'id' : '" + id + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (result) {
                var data = result.d;
                name = data;
            },
            error: function () {
            },
            complete: function () {
            }
        });
        
        return name;
    }
    
    //ASP.NET Web Service method
    [WebMethod]
    public string GetCustomerName(int id)
    {
       return CustomerHelper.GetFullName(id);
    }
    

    In the past to ensure my jQuery AJAX requests were not cached, the “cache: false” option within the AJAX call normally sufficed. Not if you’re making POST web service requests. It’s only until recently I found using “cache:false” option will not have an affect on POST requests, as stated on jQuery API:

    Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

    In addition to trying to fix the problem by using the jQuery AJAX cache option, I implemented practical techniques covered by the tutorial: How to stop caching with jQuery and JavaScript.

    Luckily, I found an informative StackOverflow post by someone who experienced the exact same issue a few days ago. It looks like the exact same caching bug is still prevalent in Apple’s newest operating system, iOS6*. Well you didn’t expect Apple to fix important problems like these now would you (referring to Map’s fiasco!). The StackOverflow poster found a suitable workaround by passing a timestamp to the web service method being called, as so (modifying code above):

    // JavaScript function calling web service with time stamp addition
    function GetCustomerName(id)
    {
        var timestamp = new Date();
    
        var name = "";
    
        $.ajax({
            type: "POST",
            url: "/Internal/ShopService.asmx/GetCustomerName",
            data: "{ 'id' : '" + id + "', 'timestamp' : '" + timestamp.getTime() + "' }", //Timestamp parameter added.
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (result) {
                var data = result.d;
                name = data;
            },
            error: function () {
            },
            complete: function () {
            }
        });
        
        return name;
    }
    
    //ASP.NET Web Service method with time stamp parameter
    [WebMethod]
    public string GetCustomerName(int id, string timestamp)
    {
        string iOSTime = timestamp;
        return CustomerHelper.GetFullName(id);
    }
    

    The timestamp parameter doesn’t need to do anything once passed to web service. This will ensure every call to the web service will never be cached.

    *UPDATE: After further testing it looks like only iOS6 contains the AJAX caching bug.

  • I’ve been working on a .NET library to retrieve all images from a users Twitpic account. I thought it would be quite a useful .NET library to have since there have been some users requesting one (including me) on some websites and forums.

    I will note that this is NOT a completely functioning Twitpic library that makes use of all API requests that have been listed on Twitpic’s developer site. Currently, the library only contains core integration on returning information of a specified user (users/show), enough to create a nice picture gallery.

    My Twitpic .NET library will return the following information:

    • ID
    • Twitter ID
    • Location
    • Website
    • Biography
    • Avatar URL
    • Image Timestamp
    • Photo Count
    • Images

    Code Example:

    private void PopulateGallery()
    {
        var hasMoreRecords = false;
    
        //Twitpic.Get(<username>, <page-number>)
        TwitpicUser tu = Twitpic.Get("sbhomra", 1);
    
        if (tu != null)
        {
            if (tu.PhotoCount > 20)
                hasMoreRecords = true;
    
            if (tu.Images != null && tu.Images.Count > 0)
            {
                //Bind Images to Repeater
                TwitPicImages.DataSource = tu.Images;
                TwitPicImages.DataBind();
            }
            else
            {
                TwitPicImages.Visible = false;
            }
        }
        else
        {
            TwitPicImages.Visible = false;
        }
    }
    

    From using the code above as a basis, I managed to create a simple Photo Gallery of my own: /Photos.aspx

    If you experience any errors or issues, please leave a comment.

    Download: iSurinder.TwitPic.zip (5.15 kb)

  • Facebook ConnectIf I need to login and authenticate a Facebook user in my ASP.NET website, I either use the Facebook Connect's JavaScript library or SocialAuth.NET. Even though these two methods are sufficient for the purpose, I don't think it's the most ideal or efficient way.

    The Facebook Connect JavaScript library is quite basic and doesn't have the flexibility required for full .NET integration through FormsAuthentication. Whereas SocialAuth.NET provides full .NET integration and all authentication is done server-side with minimal development.

    I'd say if you are looking for a straight-forward way to integrate social site authentication, SocialAuth.NET is the way to go. It's API can communicate with other social sites such as Twitter, LinkedIn and Gmail.

    Recently, I found a better and more efficient way to authenticate Facebook users on my site using Graph API and Hammock.

    Hammock is a C# a REST library for .NET that greatly simplifies consuming and wrapping RESTful services. This allows us to embrace the social site’s core technology instead of using varied SDK's or API's. There are many community driven frameworks and API's readily available on the Internet, but they can really cause problems if they evolve too quickly or haven’t been thoroughly tested.

    Suddenelfilio, has written a useful blog post on connecting Facebook using Hammock. You will see by his example that you can interact with Facebook anyway you want.

    The same principle could also be applied to other website API's that use REST based services, such as Twitter.

  • I always found writing code to read an RSS feed within my .NET application very time-consuming and long-winded. My RSS code was always a combination of using WebRequest, WebResponse, Stream, XmlDocument, XmlNodeList and XmlNode. That’s a lot of classes just to read an RSS feed.

    Yesterday, I stumbled on an interesting piece of code on my favourite programming site StackOverflow.com, where someone asked how to parse an RSS feed in ASP.NET. The answer was surprisingly simple. RSS feeds can now be consumed using the System.ServiceModel.Syndication namespace in .NET 3.5 SP1. All you need is two lines of code:

    var reader = XmlReader.Create("http://mysite.com/feeds/serializedFeed.xml");
    var feed = SyndicationFeed.Load(reader);
    

    Here’s a full example on how we can iterate through through the SyndicationFeed class:

    public static List<BlogPost> Get(string rssFeedUrl)
    {
        var reader = XmlReader.Create(rssFeedUrl);
        var feed = SyndicationFeed.Load(reader);
    
        List<BlogPost> postList = new List<BlogPost>();
    
        //Loop through all items in the SyndicationFeed
        foreach (var i in feed.Items)
        {
            BlogPost bp = new BlogPost();
            bp.Title = i.Title.Text;
            bp.Body = i.Summary.Text;
            bp.Url = i.Links[0].Uri.OriginalString;
            postList.Add(bp);
        }
    
        return postList;
    }
    

    That’s too simple, especially when compared to the 70 lines of code I normally use to do the exact same thing.

  • The thing that annoys me when using ASP.NET controls is the amount of cluttered HTML that gets generated. It sometimes reminds of my early web development days when Dreamweaver was the development tool of choice. That was a long time ago!

    CheckBoxList

    By default when using a Checkbox or Radio button list, the following markup is generated:

    <table id="MainContent_TestCheckList">
        <tbody>
                <tr>
                    <td>
                        <input type="checkbox" value="1" name="ctl00$MainContent$TestCheckList$0" id="MainContent_TestCheckList_0"><label for="MainContent_TestCheckList_0">Item 1</label>
                    </td>
                    <td>
                        <input type="checkbox" value="2" name="ctl00$MainContent$TestCheckList$1" id="MainContent_TestCheckList_1"><label for="MainContent_TestCheckList_1">Item 2</label>
                    </td>
                    <td>
                        <input type="checkbox" value="3" name="ctl00$MainContent$TestCheckList$2" id="MainContent_TestCheckList_2"><label for="MainContent_TestCheckList_2">Item 3</label>
                    </td>
                    <td>
                        <input type="checkbox" value="4" name="ctl00$MainContent$TestCheckList$3" id="MainContent_TestCheckList_3"><label for="MainContent_TestCheckList_3">Item 4</label>
                    </td>
                </tr>
        </tbody>
    </table>
    

    Yuck!

    Thankfully, this control contains a property called “RepeatLayout” that gives us the option to render our list of checkboxes or radio buttons in a much nicer way.

    Flow

    Rendered within a <span> container.

    <span id="MainContent_TestCheckList">
        <input type="checkbox" value="1" name="ctl00$MainContent$TestCheckList$0" id="MainContent_TestCheckList_0"><label for="MainContent_TestCheckList_0">Item 1</label>
        <input type="checkbox" value="2" name="ctl00$MainContent$TestCheckList$1" id="MainContent_TestCheckList_1"><label for="MainContent_TestCheckList_1">Item 2</label>
        <input type="checkbox" value="3" name="ctl00$MainContent$TestCheckList$2" id="MainContent_TestCheckList_2"><label for="MainContent_TestCheckList_2">Item 3</label>
        <input type="checkbox" value="4" name="ctl00$MainContent$TestCheckList$3" id="MainContent_TestCheckList_3"><label for="MainContent_TestCheckList_3">Item 4</label>
    </span>
    

    OrderedList or UnorderedList

    Rendered within a <ul> (unordered list) or <ol> (ordered list). Note: Multi-column layouts (RepeatColumns attribute) are not supported when using this option.

    <ul id="MainContent_TestCheckList">
        <li><input type="checkbox" value="1" name="ctl00$MainContent$TestCheckList$0" id="MainContent_TestCheckList_0"><label for="MainContent_TestCheckList_0">Item 1</label></li>
        <li><input type="checkbox" value="2" name="ctl00$MainContent$TestCheckList$1" id="MainContent_TestCheckList_1"><label for="MainContent_TestCheckList_1">Item 2</label></li>
        <li><input type="checkbox" value="3" name="ctl00$MainContent$TestCheckList$2" id="MainContent_TestCheckList_2"><label for="MainContent_TestCheckList_2">Item 3</label></li>
        <li><input type="checkbox" value="4" name="ctl00$MainContent$TestCheckList$3" id="MainContent_TestCheckList_3"><label for="MainContent_TestCheckList_3">Item 4</label></li>
    </ul>
    

    Table

    We won’t be using this option.