Playing with List Controls using jQuery

You all must be knowing, I am fan of jQuery. The kind of neat and clean code and the power provided by jQuery at Client side scripting is unmatchable.

List Controls are one of the most used form controls. And we all know that manipulating these controls from JavaScript always have been a tough task.

In this post I’ll be discussing about accessing List controls and manipulating it with the help of jQuery. Hope you all like it and also will able to apply with other controls as well.

Continue reading

Advertisement

Single Sign On between sub domains : Forms Authentication

Today, I am going to discuss one of the feature, that I was working last few days and spent sleepless nights at office and Home as well. Here I am going to discuss Single Sign On (SSO) feature and every other developer implements SSO on some or other day.

So Actually I was having two applications. The requirement was like, user logins from one application and on clicking a link it is navigated to another application. So when user clicks on the link it redirected to application2, it checks, whether the user is authenticated or not. If authenticated it can access the application2 else get redirected to first application for Authentication, And once authenticated again directly reaches the second application.

Continue reading

IsCrossPagePostBack : Cross page PostBack

Download sample from here

Last few days, I was working on one of my module in my web application. During writing code, I came accorss one property IsCrassPagePostBack of Page Class. I have seen this earlier but never tried to dig. So I thought of exploring it and here I am sharing my findings with you all.

First, Let’s start from beginning. We know when we submit a page, entire form data with hidden fields, including view state is posted to the server. One must be using IsPostBack property a lot. It is false when page loaded first time but returns true if any postback takes place. Whenever we click any server side control like button, linkbuttons etc or any other control with autopostback true. All the data including hidden field, View State etc.. is posted to the server and available for processing at codebehind. Continue reading…

Generics and Constraints over Generics

In this post,  I am going to discuss about Generic Classes and bit more on this.  Just for a smooth start,

“Generics were introduced in .NET 2.0, which provides us a way to create Classes/Methods/Types and many more without specifing the specific type of parameters. Parameters must be provided at the time of creating the instances. So we can say Generics are only a blueprint/templated version and actual type is defined at Runtime.”

So lets first create a simple Class say Point Continue reading…

Call HTTPhandler from jQuery, Pass data and retrieve in JSON format

Download sample for here

Last few days ago, I was woking with HTTP handler. Here I was required to call handler from Client script. Later I found, that I need to pass some data to handler and also recieve some from it.

So I was looking for if there is some way we can pass some data to handler in some format and can recieve.

So Here I am going to share, How we can call a HTTPHandler from jQuery and can pass some data to handler and receive as well.

So Let’s go step by step Continue reading…

A way to improve performance of your Web Application significantly

Last few days,  I was working on performance improvement of one of my Web Applications. I analysed my application in various ways. Also used different profiler and did profiling for my application using several profilers like Ants, .NET profiler etc. During analysis, I found few problems, that we rectified but got no visible improvement.

Later I thought, my server side code is good enough, but still its taking time to download the page.  Although we are already using IIS compression to reduce the page size, but still Page was taking good amount of time to download.

I posted a blog to enable IIS compression, Click the following link to have a look

How to enable HTTPCompression at IIS6

Actually,  My application is RIA application and we are using myriad  ajaxtoolkit controls in our application. I analysed my application using firebug and there are a lot of scriptresource.axd and webresource.axd files are gettng downloaded.

So I thought if we can combine these files into single that will a great performance application boost for our application.

First, I tried doing it from myself, Later I found ASP.NET itself provides a way to combine these axd files. Just you need to have .NET 3.5 SP1.

So if you are using framework version 3.5 upgrade it to SP1 and enjoy this feature.

I have created a small sample and will show you with the help of it.

So In my sample application, I have a Calender extender.  Lets see how many requests are there using firebug.

Requests of a Web Page

We can see currently there are 14 requests on every PageLoad. We can reduce the number of request.

So to  use this, first you need to download a ScriptReferenceProfiler. You can download it from here.

Now add the reference in your project and add the profile in the your page.

First register it as


<%@ Register Assembly="ScriptReferenceProfiler" Namespace="ScriptReferenceProfiler"
    TagPrefix="cc2" %>

and add it as a control like


<cc2:ScriptReferenceProfiler ID="ScriptReferenceProfiler1" runat="server" >
</cc2:ScriptReferenceProfiler>

Now when you run you application you will see the page as

Now copy all the link and put it in the CompositSctript tag as


<asp:ScriptManager ID="ScriptManager1" runat="server">
            <CompositeScript>
                <Scripts>
                    <asp:ScriptReference name="MicrosoftAjax.js"/>
	                <asp:ScriptReference name="MicrosoftAjaxWebForms.js"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Common.DateTime.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Compat.Timer.Timer.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Animation.Animations.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Animation.AnimationBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.PopupExtender.PopupBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Common.Threading.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Calendar.CalendarBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
                </Scripts>
            </CompositeScript>
        </asp:ScriptManager>

Now lets run the Application. Lets check the firebug.

Combined requests

Here we can see the number of significantly reduced It’s just 4.

But this is sample and its working fine. But when you try to your actual application you might face several issues.
One issue that I faced while using with my Live application and That is

Issue: The resource URL cannot be longer than 1024 characters. If using a CompositeScriptReference, reduce the number of ScriptReferences it contains, or combine them into a single static file and set the Path property to the location of it.

So first I could not understand it and try to find to something on google. But somewhere found it’s a issue and it will be taken care or handle by own for the time being. But during analysis I found one solution.
The problem is the URL length is getting higher than 1024. So for this one has to reduce the number of files getting combined. So you can have more than one group of file and put it in different composit scripts tag.

I have added one script manager proxy and added a compositscript tag it in it and pasted almost half of the scripts in it. And it resoved the issue. As


 <asp:ScriptManager ID="ScriptManager1" runat="server">
            <CompositeScript>
                <Scripts>
                    <asp:ScriptReference name="MicrosoftAjax.js"/>
	                <asp:ScriptReference name="MicrosoftAjaxWebForms.js"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Common.DateTime.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Compat.Timer.Timer.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
                </Scripts>
            </CompositeScript>
        </asp:ScriptManager>
        <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
            <CompositeScript>
                <Scripts>
                <asp:ScriptReference name="AjaxControlToolkit.Animation.Animations.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Animation.AnimationBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.PopupExtender.PopupBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Common.Threading.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
	                <asp:ScriptReference name="AjaxControlToolkit.Calendar.CalendarBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
                </Scripts>
            </CompositeScript>
        </asp:ScriptManagerProxy>

Now it will combine the resource files in two files. You can add more CompositScript tags if required.

Hope all you have enjoyed this and get benefited from it.

Cheers,

Brij

How to store custom objects in web.config

In this Post, I am going to discuss about web.config. Normally in our daily life, we used to have some data in appSettings section of web.config and read it when required. That is in string form. But there are lot more than this. We can update the data in web.config  programmatically as well .

Now another main point is, we can store some object of custom type in web.config as well, which we normally don’t do it. But this can be very useful in several scenarios.

Have anyone tried to update some value or add some value in web.config?  W’ll have brief discussion on this.

First, This is very common to have some constant data at appSettings section of web.config and read it whenever required. So how to read this ( for beginners).

//The data is stored in web.config as
<appSettings>
		<add key="WelcomeMessage" value="Hello All, Welcome to my Website." />
</appSettings>

// To read it
string message = ConfigurationManager.AppSettings["WelcomeMessage"];

Now if we want to update some data of appSettings programatically. One can do like this.

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings["WelcomeMessage"].Value = "Hello All, Welcome to my updated site.";
        config.Save();

Now what do you do,  if you want to add some data in appSettings . You can add some app.config data as below.

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings.Add("ErrorMessage", "An error has been occured during processing this request.");
        config.Save();

The above code is adding one new key value pair in web.config file.  Now this can be read anywhere in the application.

Now, the question is, Can we store some custom data at config?

Yes…

We can store some object. Let’s see how

I have created a sample example. In this example, I have saved an  object of my custom class NewError in web.config file. And also updating it whenever required.

To do this, Follow the below steps.

a) Create a Class that inherit From ConfigurationSection (It is available under namespace System.Configuration ).  Every property must have an attribute ConfigurationProperty, having attribute name and some more parameters. This name is directly mapped to web.config. Let’s see the NewError class

public class NewError:ConfigurationSection
{
    [ConfigurationProperty ("Id",IsRequired = true)]
    public string ErrorId {
        get { return (string)this["Id"]; }
        set { this["Id"] = value; }
    }
    [ConfigurationProperty("Message", IsRequired = false)]
    public string Message {
        get { return (string)this["Message"]; }
        set { this["Message"] = value; }
    }
    [ConfigurationProperty("RedirectURL", IsRequired = false)]
    public string RedirectionPage
    {
        get { return (string)this["RedirectURL"]; }
        set { this["RedirectURL"] = value; }
    }
    [ConfigurationProperty("MailId", IsRequired = false)]
    public string EmailId
    {
        get { return (string)this["MailId"]; }
        set { this["MailId"] = value; }
    }
    [ConfigurationProperty("DateAdded", IsRequired = false)]
    public DateTime DateAdded
    {
        get { return (DateTime)this["DateAdded"]; }
        set { this["DateAdded"] = value; }
    }
}

as you can see every property has attribute ConfigurationProperty with some value. As you can see the property ErrorId has attribute

 [ConfigurationProperty ("Id",IsRequired = true)]

it means ErrorId will be saved as Id in web.config file and it is required value. There are more elements in this attribute that you can set based on your requirement.
Now if you’ll see the property closely, it is bit different.

public string ErrorId {
get { return (string)this["Id"]; }
set { this["Id"] = value; }
}

Here the value is saved as the key “id”, that is mapped with web.config file.

b) Now you are required to add/register a section in the section group to tell the web.config that you are going  to have this kind of data. This must be in <configSections/>  and will be as

<section name="errorList"  type="NewError" allowLocation="true"
     allowDefinition="Everywhere"/>

c) Now one can add that object in your config file directly as

<errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="xyz@hotmail.com" ></errorList>

d) And to read it at your page. Read it as follows.

NewError objNewError = (NewError)ConfigurationManager.GetSection("errorList");

And also a new object can be saved programmatically as

 NewError objNewError = new NewError()
        {
          RedirectionPage="www.rediff.com",
          Message = "New Message",
          ErrorId="0",
          DateAdded= DateTime.Now.Date
        };
        Configuration config =
            WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        config.Sections.Add("errorList", objNewError);
        config.Save();

Even one can add a custom group and have some custom elements in in this section.

ASP.NET provides very powerfull APIs to read/edit the web.config file easily.

Hope you all must have enjoyed this, and I will appreciate your feedback.

Thanks

Validating partial page with ASP.NET Validators using JavaScript

Validation plays a key role whenever we take a inputs from the user. For this, ASP.NET provides us few validator controls that are used a lot in web applications.
Now a days, in our application, we used to have several section in our web pages.
And also, we populate some data based on the user’s input.
So several times, it requires  to validate the page partially not the entire page,
while earlier we used to have single submit button and their we need to validate the page.

AJAX also played a key role, for partial post back, initiate a call to server etc, which requires to validate a part of the page.

So in these scenarios our earlier approach of validation would not work.
In this kind of scenario, I will discuss few things that will be very helpful.

First, I would suggest, to divide your page in some logical section, those you might need to validate at certain points. And assign a different group name to the validators on those section.

1) If you are initiating an ajax call or initiating a callback from java-script, and you want to validate certain section/part of the page.

So before initiating the ajax call, you need to validate the user inputs. This can be easily with the following method.

You need to call Page_ClientValidate() method, this method has two flavors,
– Page_ClientValidate() it fires all the validators on the page and returns false, if it fails
– Page_ClientValidate(‘groupname’), this method fires all the validators having the passed groupname and returns false if any validator fails.
This is quite useful, while validating partial section/part of the page. So your java script code may look like this

function SaveAddress()
{
	if(Page_ClientValidate('groupname') == false)
		return false;
	else
	{
		//Save Address
	}
}

2) Several time, it happens, that based on some requirement, we used to hide some section of input form or hide some input control, but whenever page/section is going to be submitted, the hidden validators also gets fired. So to overcome this problem, you may need to disable the validators. So to disable any validator from javascript as

document.getElementById('ValidatorClientId').enabled=false;

So these validator wont be fired till you gain enable it. You can enable it as

document.getElementById('ValidatorClientId').enabled=true;

Hope you all will like this post and will found it to be useful.

Task List window of Visual Studio

Recently, when microsoft launched Visual Studio 2010, they launched it with the very nice Campaign “Life runs on code”.Who all have seen the any advertisement of VS 2010, must have seen this also. It’s very true, we, developer’s life runs on code, and our code runs on Visual Studio IDE ( Obviously only on development phase 🙂  ).

As most of the time in our offices and home (only for workaholics 🙂 we spent most of the time with visual studio IDE, we always try to find some way to code faster/better, to increase the productivity.
Visual studio IDE is full of myriad features, that helps us for faster and smoother coding. We most of the time are not aware of this and don’t use these.I always try to find some good feature at Visual studio, which we can use in our daily life and share with you all.

In this post, I am going to discuss a window, that is called as Task List window, some of you might aware this so this for rest developers 🙂

So what is the Task window, how it can help us. Let’s go in bit detail

As we have other window, Error/Warning window, we also have Task list window.To see this window, Go To View->Task List or directly using the keys Ctrl+W, T. This task list window show us the TODO list that we track and other annotations. Task list window has two views : User Task Window and Comments Window. We’ll discuss first comments Window.

Generally, we write some TODO or UNDONE comments, while development phase of our application. These comments are a sign, that we need to update/Change the code before releasing to QA/Staging environment.

As in my sample project, I have added few comments multiple files. These are listed in the Task List window (Comment View). One can all the these type of of comments in this window from the entire project. And one can click one by one and make changes whenever required. Let’s see the comments…

Task List: Comment View

We can click on any of it and it will take us to directly that line of code.

HACK, TODO, UNDONE, UnresolvedMergeConflict are default comment Tokens in VS IDE. But one can add custom tag based on their requirements.Go to Tools-> Options then under Environment click task list as below ( If Task list is not visible make sure “Show all settings” checkbox is checked at bottom of Options window).

Options Wnidow

Options Wnidow

To add a Custom Token, write the Token at Name input box, set the priority and then click on add button.We can also remove/change the existing token with the given buttons.

Now lets move to User Task View, this view list down all the user created tasks. One can create user tasks by clicking Create User Task icon, just beside view dropdown. Let’s see it

Task List: User Tasks view

Task List: User Tasks view

This gives you option to write the description of the task and set the priority. Once the task get completed, then one can mark it as completed by checking the checkbox.

Note: I have VS2008 for this post.

That’s all for now!!!

Cheers!!

Brij

 

Why MaxLength property of a textbox with multiline mode doesn’t work? A Solution

Many developers set the MaxLength property of a Textbox and it works fine until the Textbox is not in multiline mode, which is by default behavior of a Textbox.

So what is the basic diffference between a textbox in single line and multiline mode!!!

Let’s see, how it gets rendered as html. Lets have a look

Textbox with SingleLine mode

Textbox with SingleLine mode

Now Textbox with MultiLine mode

Textbox with MultiLine mode

Textbox with MultiLine mode

As you can see, When a Textbox is in SingleLine mode, it gets rendered as a input type text  and when it is in MultiLine mode, it gets rendered as a textarea. As we know MaxLength property works only for input type.

So what is the solution. We need to have a custom solution for this.

Let’s try some solution,

One thing we can do, we can attach a function on onkeypress event to the textbox, which first check the length of input string and if exceed with limit it just returns else allow to enter any input. In the below example I have used the maximum length as 10.

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" onkeypress="return CheckLength();"></asp:TextBox>

//And the javascript code is
function CheckLength() {
            var textbox = document.getElementById("<%=tb.ClientID%>").value;
            if (textbox.trim().length >= 10) {
                return false;
            }
            else {
                return true;
            }
        }

This works fine until, a user doesn’t paste a text  which is greater than the max length that is given( here 10).  So there is no simple way to stop this. To overcome this problem, one should use one of the asp.net validators.

One can go for the custom validator, and provide a javascript function, which checks the length of the text and if exceeds the maxlength then show an error. Let’s see the code below

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>
//Validator
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter maximum 10 charachters." ControlToValidate="tb"
         SetFocusOnError="true" ClientValidationFunction="CheckMaxLength" ></asp:CustomValidator>

//Client Validator function
function CheckMaxLength(sender, args) {
            if (args.Value.trim().length >= 10) {
                args.IsValid = false;
            }
        }

But there is another smart way is there, to acheive this. We can also use Regular expression validator for this, which will check the count of the entered character and will throw an error if it exceeds. Here we would not require to write a javascript function. We need to have a regular expression that will work. Let’s see the code

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>

//Regular Expression validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="tb" ErrorMessage="Please enter maximum 10 charachters."
 SetFocusOnError="true" ValidationExpression="^[a-zA-Z.]{0,10}$"></asp:RegularExpressionValidator>

Here we don’t require to write a javascript function. I have used a regular expression ^[a-zA-Z.]{0,10}$, which allows all the characters with length 0 to 10.

Hope you all must have enjoyed.

Thanks,

Brij