Me Myself & C#

Manoj Garg’s Tech Bytes – What I learned Today

My experiences with TFS: Upgrade from TFS 2010 Beta 1 to TFS 2010 RC

Posted by Manoj Garg on March 11, 2010

Since last few days I have been playing with TFS. So, I expect my next few posts on my experiences with it. Let’s starts with installing TFS 2010.

To get a feel of it, “What this is all about”, we decided to install a trial version of TFS 2010.

MS has release 3 versions of TFS 2010 so far, from Beta1 è Beta 2 è RC. I don’t know why we downloaded Beta1 despite latest being available there. For the first time, it took my good 5-6 hrs to have a running TFS instance. This included installing SQL Server 2008, Team explorer, Power tools 2008 etc etc. There are many posts available over net to guide you through the installation process like this, this, this and this.

While trying to learn it, I came to know that a lot has been changed between Beta 1 and RC, specially the TFS SDK APIs. As my main motive behind learning TFS was to write a 3rd party application which uses APIs exposed by TFS SDK to pull information from TFS instance and use it, I decided to upgrade my TFS instance to RC version.

Before upgrading the installation, I searched over web to see if there are some links available which explain this procedure but couldn’t find anything. All the post, forums were talking about upgrade from Beta 2 to RC. This article from Shai, has explained the upgrade process from Beta 2 to RC quite well. I thought of following the same step for Beta 1 instance.

I started with uninstalling TFS 2010 beta 1 and some other products which were installed along with it like VS 2010 Shell, Power tools 2008, Team Explorer 2010 Beta1. Then I started installer for RC, which showed a list of new programs that it was about to install as shown in figure below.

Once installation of above mentioned component was complete, I started “TFS foundation Server Configuration Manger” from program menu and opted for upgrade of my existing TFS 2010 beta1 instance.


After providing all the details as shown in figure above, installer asked for verifying the configuration setting. After clicking the “Verify” button it gave an error saying that “TFS 2010 beta1 can’t be upgraded to RC”. I was like “What”. Error message is shown in figure below.

Since I had already uninstalled Beta 1 and didn’t have setup for Beta 2. So I had no option other than installing RC from scratch. So started TFS Configuration manger and selected for “Standard Configuration on Single server” option for installation. System presented me with the following welcome screen.

For here on I again provided configuration details for new TFS system as shown in figure below. After verification of all these details, TFS setup was complete.

Once installation of TFS RC was complete, also installed Team Explorer and TFS Power Tools 2010 RC.

This way my TFS setup was complete.

Posted in Uncategorized | Tagged: , , , | 3 Comments »

Design patterns: Strategy v/s Visitor

Posted by Manoj Garg on February 4, 2010

Design patterns are recommended solution for some well-defined problems with a predefined context. As Wikipedia says:

“A ‘Design Pattern’ is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.”

Context is important while deciding which pattern to use in a given situation. There may be more than one qualifying pattern for a problem but all of them may or may not be suitable in that particular situation.

Some time back, I had implemented Visitor pattern for a problem. When a colleague of mine was reviewing it, we got into a discussion that this was best fit for a Strategy rather than Visitor pattern. That got me searching around for the right context and difference between these two so similar but yet so different pattern.

In visitor pattern the object structure accepts a visitor and performs visit on it. In strategy the only difference I could notice was that the composite or object structure composes a strategy object and calls Algorithm. Aren’t these two patterns essentially the same? Or rather can I put it like strategy is a cut down version of visitor or a visitor on a single type of element?

In the StrategyPattern, the context points to a strategy and delegates to it. There is no context in the VisitorPattern and the visitor is often created each time it is used. The VisitorPattern is based on DoubleDispatching, and there is none in the StrategyPattern. As far as I can see, these patterns have little to do with each other. —RalphJohnson


The intent of the visitor pattern is to add operations to a class which has rich data structure. If we are not able to identify all the operations in for the class but we expect in future we may need to add method for the class, but it is not advisable to alter the class, so to be on safer side we can put a visitor and share the data to the visitor class


The intent of strategy pattern is to define a family of algorithm, encapsulate each one, and make them interchangeable. Let the algorithm vary independently from the clients that use it. This pattern is used to add different algorithm nothing to do with the data in the class.

Here is an article by LEEDRICK discussing difference and similarities in these two patterns.

Please feel free to reply with your suggestions.

Posted in Design Patterns | Tagged: , | 1 Comment »

Encrypting entries in ASP.NET Web.Config

Posted by Manoj Garg on December 9, 2009

One of the best practices suggested while working with ASP.NET application is keeping values you want to make plug and play (changing them without changing the implementation) in web.config file. These configurable values can be anything ranging from some string constants to connection strings. Almost all the developers(at least those I know) follow this suggestion religiously. We keep these values in a readable format in web.config. Sometimes these values can have sensitive information like if we are storing connection string to our production database and if SQL server credentials are used to login to database server, then connection string will have username and password for the production database. Keeping credentials for database server unguarded can be a huge risk. Though IIS does a good job by blocking access to any resource with .config extension by default. But certainly there are many ways (leaving FTP open :)) by which someone with not so good intensions gets access to this config file containing credentials to database server. So, if one has this kind of sensitive data in config file then that data should be stored in encrypted way to mitigate risk of credentials falling under wrong hands.

This topic popped up while having a discussion with a colleague. He mentioned that .NET has some way of encrypting the values in config files. Which prompted me to search about this feature and Yes, .NET provides a very simple but effective way to encrypt values in config files. As you might already know, configuration settings in .NET work in provider model i.e. these settings can be replaced with another values without impacting the implementation.

.NET framework provides 2 encryption providers for encrypting the config file values.

  1. DataProtectionConfigurationProvider : It uses Windows DPAPIs(Data Protection API) to encrypt the data in config file and the key used to decrypt the encrypted values in stored in windows Local Security Authority (LSA).
  2. RSAProtectedConfigurationProvider : This provider uses public key encryption approach provided by RSACryptoProvider in .NET. This public key is stored in the config file itself.

To encrypt a configuration section use ConfigurationSection.SectionInformation.ProtectSection(providername) method and to decrypt the values use ConfigurationSection. SectionInformation.UnProtectSection() method.

Once you have encrypted the configuration sections, config file will no longer show the actual values instead it will be showing some cipher text. But at the time of accessing these values in code (C# or inline in aspx page) you don’t have to do anything like decrypting the config file or something, .NET will do it for you. But just take precaution while encrypting the config file values as this auto decryption done by .NET has some performance implications as well. So one should take a wise decision about which data to encrypt and which data can be written in plain text.

There are plethora of resources on this topic on web and my this post will also add to crowd, but following few link I found very informative and to the point.

  1. Encrypting Configuration Information in ASP.NET 2.0 Applications
  2. Encrypting Connection Strings in Web.config

Posted in .Net 2.0, ASP.Net, C# | Tagged: , , , , | Leave a Comment »

DOM property comparison for different browsers: What Works Where?

Posted by Manoj Garg on November 25, 2009

Today, I was working on a UI enhancement task where I had to do some DOM manipulation. Basically task was changing color of some SPAN elements in DOM depending on their value like if it’s value is XXX then show in RED color and so on. As always I was using IE to test my Java script code written to do the job. In JS code, I used “innerText” property of SPAN element to get the text of that element and then did the comparison to change the color and It worked fine. When I ran same JS code on Mozilla, it didn’t run (I mean it got executed but didn’t changed color of SPAN elements to RED L) . On debugging the script, I was surprised to see value of innerText property being returned null. When googled around it and found that only Mozilla doesn’t support this property L. Mozilla has another property “textContent” which has same value as innerText in other browsers.

Solution was simple, use an ORing of both the values instead of putting if-else block in code to use textContent if the user is running Mozilla or innerText for any other browser.

var txtName = clientNameElement.innerText || clientNameElement.textContent;

I picked up this solution from here. This link provides a good comparison of various DOM properties on different browsers that is what works and what not J.

Hope it helps some of you while writing code to cater to multiple browsers J

Posted in JavaScript | Tagged: , , , , , | 1 Comment »

Blogging right from Word 2007

Posted by Manoj Garg on September 22, 2009

I have been using Microsoft Office 2007 since last one and half years and frankly speaking “I’m lovin’ it”. Be it quick style feature of Word 2007 or ShapeStyle, WordArt Style of Powerpoint 2007, I have been using them extensively in this period. The new interface is so usable at the same time providing me lots of, out of the box available formatting features like table style, document templates n so on.

Ok so enough of praises for Office 2007, after all this post is not about why I like it. There are plethora of resources, posts, videos available over net describing the above mention benefits (features) of office 2007. This post is about creating and publishing a blog entry right from Word 2007 document. Since last few days I have been trying to be little active with my blog and write something to do justice with the its tagline “What I learned today“. Last week I was reading Gaurav’s blog and there he had a post about blogging from Word itself. So far I have been using Windows Live Writer to do most of my blogging related stuff(which is minimal BTW J), which is a great tool for blogging but it didn’t allowed me to format my post the way I wanted them to for ex putting quotes, creating colored tables for comparison related stuff etc. After reading gaurav’s post, I myself thought to give a spin to this feature of publishing content from word.

So here is the post for my tryst with blogging in Word 2007.

Enable publishing form word


Go to Office Button in word and then select Blog option for Publish menu item.

This would ask you to register a blog account with MS Word. Register your blog by providing the details about your blog as shown in below screenshots.





After registering the blog a new word document will open and you are good to go. I tried various formatting setting, picture formatting. So far so good. I am going to use word now instead of Livewriter.

Posted in Microsoft Word 2007, Non Technical | Tagged: , , | 4 Comments »

ViewState Compression in ASP.NET 2.0

Posted by Manoj Garg on September 16, 2009

STATE as a noun can be described as “the condition of a person or thing, as with respect to circumstances or attributes“.  In ASP.NET world, State of a control or a page is what it looks like, what its value is and what its value was before the page was posted back.

Since HTTP is stateless, to maintain state across postbacks in ASP.NET, some state management techniques are used. In ASP.NET state management can be categorized in two types depending on the location where state is being kept:

  1. Client Side: Client side state management involves keeping the state data on the client end, either on client machine or the browser. There are various mechanisms to maintain state on client side like Cookies, ViewState, Hidden Fields, Control State, Query strings etc.
  2. Server Side: Server side management is keeping state on a different machine be it database or file system on a different computer. Server side state management can be done using Application State, Session state etc. this data can be  stored in the server process or in a database or server file system.

For detailed information about different option available for state management in ASP.NET, please refer this link for MSDN. This link also gives a good comparison of various state management techniques with  their pros n cons.

ViewState is the first thing that come to mind when dealing with postbacks in ASP.NET.


In simple terms, ViewState is keeping information about page in a non-readable i.e. serialized way with the page itself. In ASP.NET, view state is kept in a hidden field name _VIEWSTATE on the page. So every time the page loads after the postback this serialized data is read and appropriate state is loaded into the controls.

To understand how viewstate is saved and loaded, one should know the page life cycle i.e. the steps a request, for loading a page, goes through before a page is fully rendered into the browser. This link on MSDN explains Page life cycle along with a good overview of what view state is. This post by Dave Reed gets under the hood of view state and explains the nuances of view state very well. I would recommend reading the above mention post to every one. That post has been the best link I have come across on view state.

As mentioned above, View state is kept in a hidden field _VIEWSTATE on the page. So every time the page is posted back to the server or retrieved from server, the content of View state also travel along with page content. In turn contributing to usage of network resources. Generally, developers have tendency to keep view state enabled for controls on their page. which unknowingly keeps growing the page size. This means as page size grows, it would take longer for the page to completely render itself.

Problem comes when the page size grows inordinately and waiting time for the end user to see the completely rendered page is too high. There are recommendation that one should use viewstate as minimally as possible to ensure the page size is with in limits. But sometime scenario enforces the developer to use viewstate in his/her page. In such cases following are some of the guideline/approaches to keep view state size in check.

  1. Enable view state for a control only when absolutely necessary: Set the EnableViewState attribute for the control to false explicitly, when you are sure that you do not require to keep state for that control.
  2. Don’t save large datasets into view state: Whenever possible keep the datasets and big data tables in cache or say session so that view state is small.
  3. Use IIS Compression: Internet Information Services(IIS) has the feature to provide compression for the pages it serves as response to the requests received. You can configure the IIS on your server to compress the appropriate websites or pages in the website. For detailed information about how to configure the IIS configuration on your server, please read this post by Scott Forsyth.  There is one another post by Shivprasad koirala, which is an extension of the post by Scott Forsyth, it also explains IIS compression in great details along with it also provides some comparison statistics data about what level of compression is good and for what type of pages one should avail this
  4. Using old ASP.NET 1.1 approach for storing the view state on server: In Page life cycle there are two steps available which do the job of fetching the view state from the hidden field and putting the view state content back into the hidden field it was stored. These methods are LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium. These methods are virtual methods from the Page class. A simplest approach would be to store the viewstate in session itself. Following code snippet shows how this could be done by overriding the two above mentioned methods and storing the viewstate in session after serializing and loading the viewstate from session again after desterilizing it. Serialization and deserialization is done using LosFormatter class. One can use any of the available formatters, BinaryFormatter, SOAPFormatter etc., for serializing the viewstate content. Content is stored in session with SessionID being the key.
protected override object LoadPageStateFromPersistenceMedium ()
    return (new LosFormatter().Deserialize ((string)Session[Session.SessionID]));
protected override void SavePageStateToPersistenceMedium (object state)
    LosFormatter los = new LosFormatter();
    los.Serialize (sw, state);
    string vs = sw.ToString ();
    Session[Session.SessionID] = vs;

An improvement in above mentioned approach could be to apply the compression on the viewstate content before storing them in session and decompressing the session content before restoring the viewstate. Following code does exactly this. This code introduces one more step, between storing and retrieving the view state from session, by compressing and decompressing the content. This approach again leads to save some more bandwidth.

Following class contains method for compression and decompression. Source code from


using System.IO;
using System.IO.Compression;

public static class Compressor
/// <summary>
/// Method for compressing the ViewState data
/// </summary>
/// <param name="data">ViewState data to compress</param>
/// <returns></returns>
public static byte[] Compress(byte[] data)
    //create a new MemoryStream for holding and
    //returning the compressed ViewState
    MemoryStream output = new MemoryStream();
    //create a new GZipStream object for compressing
    //the ViewState
    GZipStream gzip = new GZipStream(output,CompressionMode.Compress, true);
    //write the compressed bytes to the underlying stream
    gzip.Write(data, 0, data.Length);
    //close the object
    //convert the MemoryStream to an array and return
    //it to the calling method
    return output.ToArray();

/// <summary>
/// Method for decompressing the ViewState data
/// </summary>
/// <param name="data">Compressed ViewState to decompress</param>
/// <returns></returns>
public static byte[] Decompress(byte[] data)
    //create a MemoryStream for holding the incoming data
    MemoryStream input = new MemoryStream();
    //write the incoming bytes to the MemoryStream
    input.Write(data, 0, data.Length);
    //set our position to the start of the Stream
    input.Position = 0;
    //create an instance of the GZipStream to decompress
    //the incoming byte array (the compressed ViewState)
    GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);
    //create a new MemoryStream for holding
    //the output
    MemoryStream output = new MemoryStream();
    //create a byte array
    byte[] buff = new byte[64];
    int read = -1;
    //read the decompressed ViewState into
    //our byte array, set that value to our
    //read variable (int data type)
    read = gzip.Read(buff, 0, buff.Length);
    //make sure we have something to read
    while (read > 0)
        //write the decompressed bytes to our
        //out going MemoryStream
        output.Write(buff, 0, read);
        //get the rest of the buffer
        read = gzip.Read(buff, 0, buff.Length);
    //return our out going MemoryStream
    //in an array
    return output.ToArray();

protected override object LoadPageStateFromPersistenceMedium()






string viewState = (string)Session[Session.SessionID];



byte[] bytes = Convert.FromBase64String(viewState);



bytes = Compressor.Decompress(bytes);



LosFormatter formatter = new LosFormatter();



return formatter.Deserialize(Convert.ToBase64String(bytes));





protected override void SavePageStateToPersistenceMedium(object state)






LosFormatter formatter = new LosFormatter();



StringWriter writer = new StringWriter();



formatter.Serialize(writer, state);



string viewStateString = writer.ToString();



byte[] bytes = Convert.FromBase64String(viewStateString);



bytes = Compressor.Compress(bytes);



Session[Session.SessionID] = Convert.ToBase64String(bytes);


5. ASP.NET 2.0 approach for saving viewstate on server:

In ASP.NET 2.0, ViewState is saved by a descendant of PageStatePersister class. This class is an abstract class for saving and loading ViewsState and there are two implemented descendants of this class in .Net Framework, named HiddenFieldPageStatePersister and SessionPageStatePersister. By default HiddenFieldPageStatePersister is used to save/load ViewState information, but we can easily get the SessionPageStatePersister to work and save ViewState in Session object. The only thing to do this is to override PageStatePersister property of Page class and ask it to return an instance of SessionPageStatePersister class:

protected override PageStatePersister PageStatePersister









return new SessionPageStatePersister(Page);






The PageStatePersister class can be inherited to also created custom storage mediums for session state. The PageStatePersister class has two methods Load() and Save() which can be used to provide custom loading and saving media for ViewState.

public class StreamPageStatePersister : PageStatePersister






public StreamPageStatePersister(Page page)


: base(page)






public override void Load()




Stream stateStream = GetSecureStream();


// Read the state string, using the StateFormatter.



StreamReader reader = new StreamReader(stateStream);


IStateFormatter formatter = this.StateFormatter;


string fileContents = reader.ReadToEnd();


// Deserilize returns the Pair object that is serialized in



// the Save method.



Pair statePair = (Pair)formatter.Deserialize(fileContents);


ViewState = statePair.First;


ControlState = statePair.Second;










public override void Save()





if (ViewState != null || ControlState != null)




if (Page.Session != null)




Stream stateStream = GetSecureStream();



StreamWriter writer = new StreamWriter(stateStream);



IStateFormatter formatter = this.StateFormatter;


Pair statePair = new Pair(ViewState, ControlState);



// Serialize the statePair object to a string.



string serializedState = formatter.Serialize(statePair);














throw new InvalidOperationException(“Session needed for StreamPageStatePersister.”);








Then a PageAdapter can be used to use this persister

public class MyPageAdapter : System.Web.UI.Adapters.PageAdapter




public override PageStatePersister GetStatePersister() {


return new Samples.AspNet.CS.StreamPageStatePersister(Page);







This adapter can be configured via a .browser file placed in App_Browsers folder locally with the web site directory.

    <browser refid="Default" >
                adapterType="MyPageAdapter" />


This all above content was related to removing/reducing the Viewstate getting transferred over network. But there is still one more type of state “ControlState”. In layman’s terms, Its the minimal information that a control needs to render and function itself properly after a postback. A more apt definition from MSDN is:

Control state, introduced in ASP.NET version 2.0, is similar to view state but functionally independent of view state. A page developer can disable view state for the page or for an individual control for performance. However, control state cannot be disabled. Control state is designed for storing a control’s essential data (such as a pager control’s page number) that must be available on postback to enable the control to function even when view state has been disabled. By default, the ASP.NET page framework stores control state in the page in the same hidden element in which it stores view state. Even if view state is disabled, or when state is managed using Session, control state travels to the client and back to the server in the page. On postback, ASP.NET deserializes the contents of the hidden element and loads control state into each control that is registered for control state.

As it is mentioned in the above description, that ControlState will be traveling with the page all the time. There may come a requirement where we want to have it stored somewhere else other then the page hidden fields. While searching for methods to reduce the viewstate size, i stumbled across this post by SZOKELIZER, which describes a way to store the ControlState in session as well. ASP.NET provides a switch “RequiresControlStateInSession ” which allows to store the control state in session rather then the page itself. So for the sake of completeness I am putting the code that needs to be put to enable storing the control state in session from the above mentioned post.





In this post I have written about different mechanisms to reduce size of viewstate that travels along with an asp/aspx page every time. I have tried to covered few of the approaches that can be used but I am sure there can be many more. One such approach suggested by a friend of mine is using HttpHandlers to cut the viewstate from the request and restore it back. I am working on a poc for this. I will post it once it is complete. Please do post a comment, if you have come across any other way to tackle this or if there is some correction in approaches I have described above.

Posted in .Net 2.0, ASP.Net, C#, ViewState | Tagged: , , , , , , , , , , | 3 Comments »

Request.ValidateInput() : A common misconception

Posted by Manoj Garg on September 7, 2009

Attackers try to exploit smallest possible hole into the security of a website. A common and widely used method is script injection attack or cross site scripting where attacker tries to put some script as input to the website and tries to damage the system. A simplest example could be passing a java script function that redirects every request to a page to some other site next time onwards or passing a SQL DML statement which deletes/updates record into the database.

ASP.Net provide some measure to mitigate this risk of script injection. One of such technique is validating each and every input entered by the user before passing it on the server automatically. In this approach IIS parses the input before it is sent to the worker process and checks it for potential dangerous characters lie <, > etc. If any of such character is found in the input request, an exception is thrown, thus saving the site from a possible attack.

The exception thrown is

“A potentially dangerous Request.Form value was detected from the client”

In ASP.NET this feature can be applied per page basis or for the entire site depending on the requirement. To enable input request validation for the entire site, set validateRequest attribute of page section in web.config to true.

        <pages validateRequest="false" />

Similarly, to override the request validation or enable/disable request validation on a page ValidateRequest attribute of Page directive can be set to true/false respectively. Setting this attribute to true instructs the IIS to check the sanity of the incoming request before passing it on.

So this approach won’t let any script to pass through. But there are situations where you need to take a script or the prohibited characters like <,> as input from user, at the same time preventing a misuse of this opportunity of script injection.

A commonly used approach in ASP.NET for this scenario is:

  1. Set ValidateRequest to false for that page.
  2. Encode the input entered by the end user using Server.HtmlEncode(): Encoding ensures that all the stop words(potentially harmful characters) are converted to an equivalent HTML character encoding e.g. “<” is converted to “&lt;” etc.

I had a similar requirement, few days back, when in our application on “contact us” page, We wanted to allow user to enter html scripts into a text box. So we disabled the ValidateRequest attribute to false and used Server.HtmlEncode() method to encode the entered input. But at the same time we didn’t wanted the user to pass something malicious through the query string or the cookies. ASP.NET also provides a method on the Request object named ValidateInput(), which validates the request input passed by the client to the server. And if something fishy is found in the request an HttpRequestValidationException exception is thrown. And this is where the confusion gets in.

As per MSDN, Request.ValidateInput() method ….

The HttpRequest class uses input validation flags to track whether to perform validation on the request collections accessed through the Cookies, Form, and QueryString properties. The ValidateInput method sets these flags so that when the get accessors for the Cookies, Form, or QueryString property are invoked, input validation is performed. Validation works by checking all input data against a hard-coded list of potentially dangerous data.

If the validation feature is enabled by page directive or configuration, this method is called during the page’s ProcessRequest processing phase. The ValidateInput method can be called by your code if the validation feature is not enabled.

As this definition says that ValidateInput method does nothing but sets some flags indicating that all access to user input must be validated before using it. But normally developer tend to call Request.ValidateInput() method and then expect it to throw the HttpRequestValidationException exception, which will not happen since this method doesn’t throw any exception, rather any access now onwards to input will throw the above mentioned exception.

Lets disassemble the Request.ValidateInput method.

public void ValidateInput()

As shown in the above code snippet, this method has just some set methods calls. Actually these method set a flag for one of the input approach that can be used by the client. Like querystring, form input , cookie etc.

So what does this setter method do?? This method is merely an indicator for the getters methods of each of the request fields to check the sanitation of the value before returning the value to the requestor and if there is some invalid input then throw the HttpRequestValidationException.

So to check for invalid input in Form values, we need to access form values collection of the request as Request.Form after the call to Request.ValidateInput(). Following is a sample code for validating Form values,

String firstName = string.Empty;
    //Access the Form value collection. So if there is any non complient input entered by user.. It will throw an exception
    System.Collections.Specialized.NameValueCollection nvc = Request.Form;

    firstName = txtName.Text.Trim();
    firstName = HttpUtility.HtmlEncode(txtName.Text.Trim());

here line in yellow color will throw an exception if at all there is some bad data in the input. Then in catch we can use HtmlEncode() to encode the user input.

Similar approach can be used while accessing cookies or QueryString.

Posted in .Net 2.0, ASP.Net, C# | Tagged: , , , | 3 Comments »

Fixing “This page contains secure and nonsecure items” warning in IE

Posted by Manoj Garg on July 17, 2009

Ever encountered “This page contains both secure and nonsecure items. Do you want to display the nonsecure items? ” in IE. Well I do and this pesky popup keeps bugging me now n then. Till today, I never bothered about it. I used to click “Yes” no matter what😀. I know it’s not always safe to do it but who cares😀


Today I was assigned a bug, in the application I am working on, which says that users are seeing this popup so many times and they are not happy about it. That got me thinking people do care about these pop ups as well😛.

Ne way, I had to find a solution to get rid of this warning. So after little Binging and Googling I found the solution. So thought about writing my findings though they are available in top 10 search results🙂

The reason for this warning is that you are visiting a secure site (HTTPS site) and somewhere behind the scenes that site or page is trying to access a non secure resource be it a complete page or some image. That makes the browser assume that since you are inside a secure site, you should not be getting anything that’s not secure. Like many a times https pages have some images whose source is http for example http://mmyserver/myimages .

There are two ways you can get rid of this warning

  1. Change all reference of http to https in the page.
  2. Lower your guard in IE: IE has a setting which decide what the browser behavior in case of a non secure content coming while browsing a secure page. This setting is in “IE ==> Tools ==> Internet Options ==> Security Tab ==> Click Custom Level button” this will open up a list of options for various security settings for IE. Scroll this list to search for “Display Mixed Content” option. The “Prompt” radio option is selected by default. Change it to “Enable” option and click OK. and you are done. The change will take effect immediately.

Following are some of the links which helped me to solved me the issue:







Posted in IE | Tagged: , | 6 Comments »

Pagination with JavaScript

Posted by Manoj Garg on July 17, 2009

Pagination is a must have feature when it comes to display a list of item. List could be collection of search results, a tabular display of names etc etc. When the list is small, pagination is not something we should be worried about, But imagine having a list with 100’s of items to show then displaying all of them at once on a page is not a good idea.

  • Viewer of that page have to scroll down a lot if the list if too long
  • Page becomes slower since there are lots of DOM elements on the page

So developers tend to display a small number of items at once to the viewer and then proving him/her the option of navigating to different pages. There are two ways once can implement paging

  1. Server side paging: Developer can get only a fixed number of records from the server and display then to the viewer and whenever viewer wants to navigate to a different page, a new request demanding the items from that particular page can be send to the server. In turn server can return records from that page only.
  2. Client side paging: Depending on the scenario developer can also do the job of showing pages on the client side as well i.e. he/she may request all the items at once and then showing only a set of them to the viewer and providing user with the links to other pages using any scripting language.

I had a situation where it was not possible to have server side pagination due to restriction of the framework I was coding against. So I had no choice but to go with client side paging. I was implementing a search functionality where I would be searching against the lucene index to get the results and then showing those results to the viewer. search results will be displayed a html table. each row in the result table will be used to display one search result. Each search result will have some predefined fields and a summary for that results. Viewer will have an option to show and hide the summary of the result. So one requirement was to have different number of items per page depending on whether summary is visible to the viewer or not.

I took the following approach:

After getting results from server, I used JavaScript to create DOM elements for each of the search results returned. After all the results are created on the page, pagination code was called to show the first page and the pager.

To start I created a JS class named “Pager” which will have all the methods related to the navigation among pages. Pager class had following members:

  • tableName : Name of the table on which pagination has to be applied.
  • itemsPerPage : Number of items to show when summary field is visible.
  • itemsWithoutSmry : Number of items to show when summary field is not visible to the viewer.
  • currentItemPerPage : Number of items currently visible. This value will be equal to either itemsPerPage or itemsWithoutSmry.
  • currentPage : current page in the table.
  • pages : Total number of pages in the table.

All the above field will be initialized to some default values when the Object of Pager call will be created.

Initialization of the pager

This method will initialize the pager object field pages by using the total records and items to shown on page. Following code snippet is the init() method.

//initialize the pager
  this.init = function() {
        //check if table exists in the dom
        if(document.getElementById(tableName) != null)
                // get the total number of rows in the table
            var rows = document.getElementById(tableName).rows;
            var records = (rows.length - 1);
                // Calculate the number of pages
            this.pages = Math.ceil(records / this.itemsPerPage);
                // set the flag to indicate initialization is complete
            this.inited = true;

Showing records of a particular page

To do this I will iterate through the rows of the table to show/hide the visibility of these rows depending on the page viewer has requested. Following code snippet shows the methods that do this.

//Show record from a start index to an end index
this.showRecords = function(from, to) {
        // check if table exists in the DOM
        if(document.getElementById(tableName) != null)
        //Get rows in the table and then set the visibility of the rows between 'from' and 'to'
            var rows = document.getElementById(tableName).rows;
            // i starts from 1 to skip table header row and hide rows other then the current page
            for (var i = 1; i < rows.length; i++) {
                if (i < from || i > to)
                    rows[i].style.display = 'none';
                    rows[i].style.display = '';
// Method to show a particular pager
 this.showPage = function(pageNumber) {
    // check if initialization is done
        if (! this.inited) {
            alert("not inited");
        //change the CSS style of the old page
    //each page number indicator in the pager has a naming convention like tablename+pg+pageindex
        var oldPageAnchor = document.getElementById(this.tableName+'pg'+this.currentPage);
        oldPageAnchor.className = 'pg-normal';
        //change the style of the current page
        this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById(this.tableName+'pg'+this.currentPage);
        newPageAnchor.className = 'pg-selected';
       //calculate current page records index
        var from = (pageNumber - 1) * this.currentItemPerPage + 1;
        var to = from + this.currentItemPerPage - 1;
    //show the records
        this.showRecords(from, to);


Navigating to Next and Previous pages
//show previous page
    this.prev = function() {
        if (this.currentPage > 1)
            this.showPage(this.currentPage - 1);
    //show next page = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);

Showing the pager bar

Following code snippet contains javascript method which will create a div at the end of table containing number from 1 to the total number of pages in the table along with prev and next page links. each link will have a onclick javascript function call to the above mentioned functions.

//show the pager bar
// param : @pagerName: name of the pager object
//  param : @positionId: Id of the div in which the page has to be shown 
    this.showPageNav = function(pagerName, positionId) {
      // Check if the pager object has been initialized
      if (! this.inited) {
        alert("not inited");
      // check if the div exisits in DOM 
      if(document.getElementById(positionId) != null)
        var element = document.getElementById(positionId);
        // create prev page link with call to prev() method
        var pagerHtml = '<b><span onclick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> | ';
        // create numeric page number links
        for (var page = 1; page <= this.pages; page++)
              pagerHtml += '<span id="'+this.tableName+'pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
        // Create next page link with call to next() method
        pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span> </b>';
        // chnage the inner html of the pager Div 
        element.innerHTML = pagerHtml;

Adjusting the record count per page with the Summary visibility

I added a method to the pager class which takes a Boolean parameter denoting the visibility status of the summary content as input and based on this parameter it changes the current page size. Following code snippet shows the same:

//adjust page according to summay div visibility
// param : @isSummaryShown = Visibility status of the summary content for the item
    this.adjustPager = function(isSummaryShown)
      //change the pagesize
        this.currentItemPerPage = this.itemsPerPage;
        this.currentItemPerPage = this.itemsWithoutSmry;
      //rebuild pager
      if(document.getElementById(tableName) != null)
          var rows = document.getElementById(tableName).rows;
          var records = (rows.length - 1);
          this.pages = Math.ceil(records / this.currentItemPerPage);
    this.showPageNav("pagerObj", 'pageNavPosition_Results');

Creating and using Instance of the Pager Class

following line shows the signature for the pager class

function Pager(tableName, itemsPerPage, pageSizeWithoutSummary)

after the page object is created it must be first initialized, then the pager bar should be created followed by showing the page.

Following code snippet shows this

// create a pager obejct by passing tablename, page size
var pagerObj = new Pager('table_AllResults', 10, 15);
// init the pager object
//show the pager bar for itens without summary
//show first page

I will be uploading a demo soon.

If you have some better way to implement the pagination then please drop a comment. 🙂

Posted in CSS, JavaScript | Tagged: | 4 Comments »

Null-coalescing operator in C#

Posted by Manoj Garg on May 12, 2009

While surfing around I can across a term called “null-coalescing operator”. After searching about it, I came to know that C# has an operator ?? . well I didn’t new about it before so thought of writing about it.

MSDN says

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.


int? x = null;
string str = "Hello World !!"; 

int y = x ?? -99; // Here Y will be -99 since X is null
string newStr = str ?? "Default Hello World !!"; // here newStr will be "Hello World !!"

PS: This operator reminded me of similar functions available in SQL Server like ISNULL, COALESCE

Posted in C# | Tagged: , | Leave a Comment »


Get every new post delivered to your Inbox.

Join 409 other followers