Pages

Friday, April 3, 2009

Disabling asp.net client side validator affects page.IsValid

Sometime we need to disable page validator based on user selection. For example in the following image when user click the save button the three validators are used for client side validation.

image

Now if user clicks on Reset Password then we don't need to disable the client side validators related to the three fileds (old password, password, confirm password). To enable/disable validators we need to use asp.net provided client side method:

ValidatorEnable(validator, enabled);

The first parameter is the validator object itself. The second parameter defines whether the validator will be enabled or disabled. On the click event of Reset Password checkbox we'll call the ValidatorEnable method in javascript. As shown in the following image reset password will disable the client side validator.

 

image

Pretty simple! huh!

Now on the save button event you'll check if the Page.IsValid is true to ensure that client side code is validated properly. But you have disabled the client side validation with javascript. So the Page.IsValid will return false. The solution before calling Page.IsValid ensure that the validators that you disabled on the client side also disabled on server side. so you code will be like:

if(ResetPassword Chekcbox is checked)

{

1. disable validator related to old password.

2. disable validator related to password.

3. Disable validator related to confirm password

}

call Page.IsValid

Now when you'll call the page.Isavalid, you'll get the true as the call of page.isvalid will ignore those controls' that are not enabled. So if you disable a validator from server side then page.Isavalid will ignore whether the validator we validated or not on the client side.

Browser specific CSS

Sometimes the same css class renders differently in different browser. For example you have put padding-left:5px in your css class. But in different browsers the padding is showing different. So one workaround may be to use different css class or css class attribute in different browser. Consider the following css class.

 

.rightColForCheckBox

{

      float: left;

      padding-left: 2px; /* Default*/

      *padding-left:0px; /* This is for ie7 and hopefully ie8.*/

      _padding-left:0px; /* This is for ie6*/

}

 

The css class rightColForCheckBox has three attributes for padding-left each of for different browser that is described below:

*padding-left: This is for ie7 and hopefully ie8

_padding-left: This is for ie6

padding-left: This is default for browsers for which no specific css specified.

 

If we need safari specific css class then declare the same rightColForCheckBox again in the following manner:

 

@media screen and (-webkit-min-device-pixel-ratio:0) {

.rightColForCheckBox

{

      float: left;

      padding-left: 5px;

}/* This code is only recognize by safari*/

}

 

Although writing css class in this way is not recommended, this is the last way to get rid of the css comparability issue.

Saturday, March 21, 2009

prevent Concurrent Asynchronous postback

By default, when a page makes multiple asynchronous postbacks at the same time, the postback made most recently takes precedence. For example, user clicks on a button which generates asynchronous postback. Now before the response of the asynchronous postback comes to client, user click another button which also generates asynchronous postback. In this case the response of the first button's event will be discarded by the client. So user will not find the update information as the  the first button's event.

So in this case there are two approaches to handle the situation:

1. When a asynchronous postback is in progress, user will not be able to initiate another postback.

2. if user initiates multiple asynchronous postbacks then we can queue the requests and send them one by one. But in this case timeout is a problem.

 

Approach 1: Prevent users to initiate multiple asynchronous postbacks:

    <script type="text/javascript">

        var Page;

        function pageLoad() {

            Page = Sys.WebForms.PageRequestManager.getInstance();

            Page.add_initializeRequest(OnInitializeRequest);

        }

        function OnInitializeRequest(sender, args) {

            var postBackElement = args.get_postBackElement();

            if (Page.get_isInAsyncPostBack()) {

                alert('One request is already in progress.');

                args.set_cancel(true);

            }

        }    

    </script>

In the above code block, we are hooking OnInitializeRequest event on every request's initialize event. In the initialize event handler (OnInitializeRequest) we are checking if an asynchronous request is in progress. if so then canceling the current request.

 

Approach 2: Queue asynchronous requests

Andrew Fedrick describes in his blog how to queue asynchronous requests here.

For simplicity, my recommendation is to prevent users to initiate multiple asynchronous requests.

 

Some Useful Links

http://msdn.microsoft.com/en-us/library/bb386456.aspx

http://www.dotnetcurry.com/ShowArticle.aspx?ID=176&AspxAutoDetectCookieSupport=1

http://weblogs.asp.net/andrewfrederick/archive/2008/03/27/handling-multiple-asynchronous-postbacks.aspx

http://www.codedigest.com/CodeDigest/41-Cancel-Multiple-Asynchronous-Postback-from-Same-Button-in-ASP-Net-AJAX.aspx

Tuesday, March 10, 2009

Covariance and Contravariance in C#

In C# roughly we can say that covariance means we can substitute derived type in place of base type. Contravariance means we can substitute base class in place of derived class (You are thinking it's not possible, right? We'll see how it's possible). To get a detail discussion on what covariance and contravariance are follow the great post on Eric Lippert's Blog or Visit Wikipedia

In C# covariance and contravariance are supported only for reference types. We will discuss few covariance and contravariance supports in C#. For this example just take a look at the following class hierarchy as we are going to use the class hierarchy for all the examples in this post:

 

ContraCo

Figure: Class hierarchy

 

1. From C# 1.0, arrays where the element type is reference type are covariant. For example the following statement in C# is ok.

 

Animal[] animals=new Mammal[10];

In the above code mammal can be stored in animals array as mammal is derived from Animal. But remember this is only true for reference types. Why this covariance only for reference types but not for value type? Its because for reference types the array originally keeps only pointers to the original object and base pointer can refer to derived types. In case of value type the original value is stored in array itself so the size many vary depending on the type. So covariance is not supported for array of values. For example the following statement will not compile:

long[] arr = new int[100];

2. Covariance from Method to delegates were included in C# 2.0. In the following code snippets (which is valid in C# 2.0 and later) you'll find that return type supports covariant. The original delegate has return type of Animal. But the method we have assigned (here, CopyMammal) to a variable (here, cfunc) has return type Mammal. So we can see that covariance is supported in return types.

 

//delegate which take no arguments but return animal

delegate Animal copy();

 

 

/// <summary>

/// method which delegate copy can accepts.

/// </summary>

/// <returns>Mammal</returns>

Mammal copyMammal()

{

return new Mammal();

}

 

The following statement is valid and an example of return type covariance.

 

//an assignment statement where covariant occurs by allowing Mammal return type in place of Animal return type

copy cfunc = copyMammal;

 

3. Contravariance is supported in parameters. Let's take a look at the following code snippets for understanding how contravariance works in parameters types:

 

//delegate which take one mammal argument and return nothing

delegate void CopyState(Mammal a);

 

void copyMammalState(Mammal mammal)

{

}

 

void copyAnimalState(Animal mammal)

{

}

 

void CopyGiraffeSate(Giraffe giraffe)

{

}

 

 

Now the following code will compile as Contravariance is supported here. This is contravariance since we are using Animal parameter of CopyAnimalState in place of Mammal defined in CopyState delegate.

CopyState cs1 = copyAnimalState;

 

But the following code will not supported as covariance is not supported in parameters.

CopyState cs2 = CopyGiraffeSate;

The above is not valid in C#. But why is not valid? Let's explain a bit. For shake of argument think that the above statement is valid. Then anybody can call the cs2 with an Tiger element as show below:

 

CopyState cs2 = CopyGiraffeSate;

Tiger tiger = new Tiger();

cs2(tiger);

 

If covariance would support here then the above statement would generate an exception as cs2 can handle Giraffe but not Tiger.

 

C# 4.0 has extended the co and contravariance further for generic types and interfaces. Hope I'll post on it later. Some useful links on covariance and contravariance are as follows:

http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

http://andersnoras.com/blogs/anoras/archive/2008/10/28/c-4-0-covariance-and-contra-variance.aspx

Monday, March 9, 2009

Tuple in C# 4.0

C# 4.0 include a new feature called Tuple. In mathematics tuple is a ordered list of specific number of values called the components of the tuple. For example a 3-tuple name may be used as: (First-Name, Middle-Name, Last-Name).

Let's take a look in the following example:

        public Tuple<int, int> GetDivAndRemainder(int i, int j)

        {

            Tuple.Create(i/j, i%j);

        }

        public void CallMethod()

        {

            var tuple = GetDivAndRemainder(10,3);

            Console.WriteLine("{0} and {1}", tuple.item1, tuple.item2);

        }

 

In the above example the method can return a tuple which has two integer values. So using tuple we can return multiple values. So this will help lazy programmers to write less code but do more. One great use of tuple might be returning multiple values from a method.


To get more info on Tuple visit the following links:

http://en.wikipedia.org/wiki/Tuple

http://peisker.net/dotnet/tuples.htm

http://spellcoder.com/blogs/dodyg/archive/2008/10/30/16319.aspx

Wednesday, February 25, 2009

AppOffline.htm mystery

if you create a file named AppOffline.htm in the root directory of the web site user will be redirected to the page. This is useful when we upload something in PROD. We can create a file named AppOffline.htm specifying “site is upgrading………. Please wait for few mins….”, copy it in the root directory of web site and then we can modify PROD files.

So when we need to update the live site content for few moments then we can put the file in the root directory and the site will be offline. Any user trying to access any url of the site will get the appoffline.htm file.. Then when update will be done then the file can be deleted to bring the site online.

Monday, February 23, 2009

Destructor, Finalizer, Dispose

The three terms Destructor, Finalizar and Dispose are a bit confusing in dot net. May be you have heard of Finalizer and Dispose but not of Destructor. If your code uses resources that need to released then you can implement IDisposable interface. Then in Dispose method you can clear the resources. But the dispose method is not called automatically rather the user will have to call it explicitly. But if user forgets to call dispose method then how you'll release the resource? Here the Finalizer comes into play. If you implement Finalizer interface then the GC will call the finalize method when the GC will try to reclaim the memory occupied by your object. So Finalize your ensure that you cleaning code will run as GC will call it automatically. But then what about destructor? Actually destructor is just finalizer. In C++ destructor will be called when the object will go out of scope but in C# the desctructor will be called by GC (just like finalizer). So desctructor and finalizer is the same in a sense. In VB.NET there's no destructor but only Finalizer.

Finalizer is costly process and increase the object's generation by 1. When GC runs and try to collect the object and find the object has finalize method, then GC run the finalize method. And after that the GC will not collect the memory rather upgrade the object's generation by 1. So if the object in GEN 0 has finalize method called then the object will be not be reclaimed in this GC call rather the object's generation will be upgraded to GEN 1. So this will keep the object long time in memory. The object memory may be collected next time when the GC will run.

The best design is to include both dispose and finalize in the object which need to clear resources. But if user calls dispose method then we don't need to run the finalize method as the resources are already cleared in dispose method. In that case we can suppress the finalize method by calling GC.SuppressFinalize method. When this method will be called in dispose method the finalizer will not be called thus reclaiming the memory on one single GC run. But if user does not call dispose method then finalizer will be called by GC. For details follow the link:

http://msdn.microsoft.com/en-us/library/b1yfkh5e(vs.71).aspx

Thursday, February 19, 2009

CLR Profile

Few days ago I was looking to find if I can spy may dot net application to get what's doing CLR under the hood. Then I had found an amazing tool, CLR profiler. I think most people doesn't know about it or are not used to with it. I have found the tool amazing for identifying some issues like memory leak. There are two versions of CLR profiler: for .net version 1.1 and version 2.0.

With this tool we can easily find the following three issues:

1. Is our application allocating too much memory?

2. Which objects are staying in memory too much time?

3. If we are holding memory but not relasing properly.

Tuesday, February 3, 2009

Page Method (Web Service methods in aspx page)

Page method is web service method added to aspx page rather than in asmx page. Sometimes we just want a web service functionality for a single page and we don't want to use any separate web service for the shake of complexity. We need such web service like functionality when use ajax. For example when we use dynamic populate control from ajax control toolkit we need to populate data dynamically. In that case the populate control needs data from web service but if we don't want to introduce web service for keeping our system simple we can implement the code for web service in the aspx page. To declare a page method web service use the following script in the aspx page.

<head runat="server">

<script runat="server">

    [System.Web.Services.WebMethod()]

    [System.Web.Script.Services.ScriptMethod()]

    public static string Test()

    {

        return "sohel rana";

    }

</script>

    <title>Page Title</title>

</head>

You can also declare the web service method in code behind file. In that case the method will be public and static and should be marked with WebMethod attribute as shown below

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    [System.Web.Services.WebMethod()]

    [System.Web.Script.Services.ScriptMethod()]

    public static string Test()

    {

        return "your data";

    }

Now we need to know how we'll call this page methods using javascript. There are two ways to call the page mehtod Test. One is call via PageMethods and another is to use ajax control toolkit's built-in feature. To use PageMethods you need to set the ScriptManager's EnablePageMethods to true as shown below.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

This will generate a PageMethods javascript object with which we can call the Test method as shown below:

    <script type="text/javascript">

        function CallWebServiceMethod() {

            PageMethods.Test(complete);

        }

        function complete(val) {

            alert(val);

        }

    </script>

<input type="button" value="Click" onclick="CallWebServiceMethod()" />

 

The second option will be to use Ajax Control Toolkit's built-in feature. Obviously this option will be available if you are using Ajax Control Toolkit. For example in the following code snippet the Dynamic Populate extender control will call the service method Test and on completion of invocation of Test method the control will update the panel with id p1.

 

            <cc1:DynamicPopulateExtender ID="dpe" runat="server" ServiceMethod="Test" TargetControlID="p1">

            </cc1:DynamicPopulateExtender>

        <asp:Panel ID="p1" runat="server"></asp:Panel>

But my personal opinion is that may be the Page method should not use as I'm skeptical about the performance. May be I need to dig more on performance.

Saturday, January 31, 2009

Trigger Based service control system in Windows 7

Today I was watching a video from Channel9 and there I have found that the way windows service works has been changed in windows 7. The common scenario is to run common windows services on startup. Normally this takes long booting time and shutdown time. Also the services startup automatically do not need all the time. For example "Tablet PC Input Service", this service starts automatically when computer starts but this is not needed if you don't use tablet PC. So this type of services do nothing but take up computer processing power and memory and causes slow start up and shut down.

To get rid of this problem Microsoft Kernel team is devised a new way of starting and stopping services. This is trigger based. So now in Windows 7 all the services will not start automatically rather starts by kernel when some kinds of trigger fires. For example the "Table PC Input Service" will not start on startup. But some kind of tablet PC will be attached then the kernel will identify that for this the "Tablet PC Input Service" needs to be started, and start the service. And the tablet PC will be unplugged the service will be stopped by the service.

So this is great idea! Microsoft was started Vista a brand new way and now in their next OS windows 7, they are looking how to improve performance for Vista-next OS.