Perfil de SohelSohel's spaceFotosBlogRedMás Herramientas Ayuda

Blog


28 septiembre

Google Wave: Email is too old and need to replace or re-engineered.

This is my first article on Google technology. I am always a fan of Microsoft technologies. But recently watching a video on Google Wave I can't help myself writing on it. I can't remember when I last astonished seeing something technically innovative. But I did so watching the power of Google Wave. Ok enough with my personal view. Let's dig deep into Google Wave. But before that, let's deal with the major problem with current email system.

 

Problem with current email system

The current email system was introduced few decades ago. So if you ask yourself that if the email was introduced on year 2009 then how it would be? Definitely it would be more smarter and interactive. And that's Google wave is. Email is a kind of client based (content) management system rather than sever based. Though server works to route and temporarily (sometimes permanently) store email, the email is finally downloaded by client and managed on client machine. As email is sent back and forth, different version of the same email (or thread) is stored in the different user's PC. so information (contained in the email) is disseminated in different locations of different versions. As shown in the following image, currently email server's main role is to relay the messages. Though nowadays email provider allow us to store mail on the mail server but client also may have the copy of the same mail on his desktop/laptop. So the email is not managed in a central location and multiple version of the same email exists.

image

Figure 1: General view of How current email system works.

 

How to solve?

Now the question I may ask you if email was introduced on the year of 2009 and if you were responsible to design the system what you would be your first consideration? If you would ask me the question I would reply that I would keep the email as a single entity and all users would work on a single instance. Currently recipients of the email have their own copy and work on that local copy. But if the copy would stored in the server and users would work on that single server copy then it would be easier to manage and keep track of. This would also ensured that the email doesn't have multiple copy. So the information is not disseminated. The concept is a kind of "email is a single content stored in a single location and multiple people are working on it". So here collaboration is a kind of multiple people working on a single entity. So email need to be a single instance and need to be stored in a single location and multiple people should  interact/collaborate with it. The following figure depicts the idea.

 

image

Figure 2: How email could be managed as a shared content.

 

We developers are used to work with version controlling system (like, SVN, Visual SourceSafe etc). The concept shown in figure 2 is something like that.

 

What Google Wave does?

In simple Google Wave is new collaboration system. It includes features of email, instant messaging, documenting and more in a single box. With Google Wave you'll communicate with other people online just like email but you'll not have to have local copy like email. In the wave email you can easily get instant messaging option. While you'll  send mail (FYI, mail is not the actual term in Google Wave) to someone with Google Wave, if the user is online, then you can start instant messaging and the messages will be included in the mail. The wave server will maintain all the history of the email (including the instant messaging) and you can easily navigate through the history. Though Wave also has a lot more feature my main focus here was how Wave is going to shape the world of email.

 

I'll try to write an article on this later.

24 septiembre

Microsoft Ajax CDN

Microsoft recently announced that they are going provide Content Delivery Network support for ajax and Jquery. This is great idea as developers can link the jquery to Microsoft site rather than including in the project. There are few benefits of this:

1. Don’t need to maintain duplicate jquery or ajax files in the project. Just add a reference to an URL to Microsoft provided URL.

2. Surely page loading will be faster as the script is loading from different domain. Browser as usually doesn’t allow to load multiple resources from server while loading js file. So browser can request for two or more image files from a server simultaneously. But can request for single js file to per server and while loading js file browser stop requesting any other file to the same server. Now as the js file is deployed on different server so page loading will be definitely faster.

3. Currently for multiple sites you are deploying the common JavaScript file (say jqeury file) multiple times. So for site 1 the url of the jquery file is http://www.site1.com/js/jqeury-1.2.3.js. For site 2, the same jquery file is deployed as http://www.site2.com/js/jqeury-1.2.3.js. So browser is loading the same version of query file for different site. Now if you add CDN reference then the same jquery will be used for multiple sites. And as browser caches js file so once the js file is cached for site 1, for site2 the js file will not be download.

 

We can expect such type CDN network for other common components. Details can be found here on asp.net site.

28 agosto

Stemming in Search

Stemming is a process of reducing a word by removing some pattern. For example 'Search', 'Searches' and 'Searching' has the same origin and if user search with any of the words then content with 'search' keyword should be included in the result. So when user search with keyword 'Searching' how will you ensure that any content with keyword 'search' is included in the result? You can do so by applying stemming to the user search text. So if user searches with 'Searching' then the stemming process will remove the 'ing' from 'searching' and you will get the 'search'. Then you can use this keyword 'search' to use for searching content in your system.

 

The process of applying Stemming is shown in the following diagram:

image

 

So we can use a stemming library to parse the user search text and then we can get the root of each word user provided. Then we can search with stemming keywords. This will increase the chance of getting result from user perspective. You can get the open source stemming library from the following link:

http://tartarus.org/~martin/PorterStemmer/

01 agosto

XSLT Debugging

XSLT is a great way of transforming XML document. But most of the developers who works with XSLT doesn't know that XSLT can be debugged in Visual Studio. Debugger in Visual Studio supports breakpoint, viewing XSLT executing steps, variable watching capability etc. There are two ways to debug XSLT in visual studio.

First Approcah

In this approach you don't need to write any code. You need your XSLT and XML file ready.

1. Open you XSLT file in Visual Studio.

2. On the properties of the XSLT file you will find Input property. Select the XML file you want to debug with this XSLT.

3. Start Debug

 

 

Second Approach

In this approach you need to write few lines of code to debug XSLT. For XSLT debugging from code you need to use the XslCompiledTransform Class.  The following code block use XslCompiledTransform to debug the XSLT. You can pass boolean value to XslCompiledTransform constructor to debug or not. The code section below is self explanatory and has proper comment to understand. You have need to have two files, source (XML) and styelsheet (XSLT). Then you need to specify the output file name which the XML after  applying stylesheet to XML. In the code section below I have created the full path name by appending current application directory with "Xmls/filename".

string sourceFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Xmls/XMLFile.xml");

        string stylesheet = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Xmls/XSLTFile.xslt");

        string outputFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Xmls/output.xml");

       // Enable XSLT debugging.

      XslCompiledTransform xslt = new XslCompiledTransform(true);

 

      // Compile the style sheet.

      xslt.Load(stylesheet);

 

      // Execute the XSLT transform.

      FileStream outputStream = new FileStream(outputFile, FileMode.Append);

      xslt.Transform(sourceFile, null, outputStream);

Now to debug all you need to do to put breakpoint at the line where transform takes place (xslt.Transform.....). when the breakpoint hits and if you press F11 then you will stepped into XSLT debugging.

 

Few more Information

While in debug you can get the current node by putting "self::node()" in the immediate window or watch window. You can also get the particular node value by writing any XPath  query like "./FirstName/text()". Here you will get the First Name with respect to current node. The text() is a function which returns the node's text value.

 

23 junio

JavaScript Event

How to handle the event object?

JavaScript event handling is a bit incompatible between IE and other browsers. So if you have not clear picture of what the difference then it'll be difficult to write proper event handling code in javascript that will work swimmingly in different browsers. By default when an event will be fired and you have bound some event handler code to handle that event, the event object should be passed automatically to the function. Though all browser works this way, Surprisingly the IE browser works different way. IE doesn't pass the object directly rather you need to access it through window object. So in an event handler you need to write code in any of the two ways as shown below to get the event object:

        function eventHandler(e) {

            e = e || window.event;

        }

        function eventHandler(e) {

            if (!e) {

                e = window.event;

            }

        }

In the first event handler, the OR operator (||) is used to take e if e is not null. If e is null then window.event is used (for IE). In the second handler above the shorthand OR is written in more elaborately.

 

How to prevent the default behavior of an event?

Now let think you have an anchor and when user will click on the anchor you need to do some validation on client side and if the validation is passed then you want the anchor url to be navigated. If validation is not passed then you want to prevent the user to move the url. So you need to write javascript code to prevent the anchor's default behavior (will navigate to the href defined). You can do so by calling event object's preventDefault method. But IE doesn't support preventDefault. Rather you need to use returnValue.

 

        function eventHandler(e) {

            e = e || window.event;

            // Prevent the default action of an event

            if (e.preventDefault) {

                //For Non-IE

                e.preventDefault();

            } else {

                //For IE

                e.returnValue = false;

            }

        }     

 

 

Event bubbling and how to prevent it?

When an event is fired in an element in javascript DOM and the event is not handled in the element then the event is passed to the parent of the element. If the event is not handled in the parent element the event is propagate to the upper. So this is called event bubbling. There's another model called event capture. You can read more details about event model from here. For all browsers except IE we can call the event object's stopPropagation method to prevent event bubbling. But for IE, we need to set cancelBubble to true. The code snippet below shows how we can write a cross-browser compatible javascript code.

            // Stop event from bubbling up: 

            if (e.stopPropagation) {

                // W3C compliant browsers: 

                e.stopPropagation();

            } else {

                // IE: 

                e.cancelBubble = true;

            }

 

Filter event by checking the source of the event

Sometimes we need to check the source of the event. We can do so applying event delegation technique. For example we have a table of data and whenever a row is clicked, we need to handle the event. Rather than writing event handler for each of the tr/td we can write an common handler and check the source element in that event handler and take necessary actions. The technique is called event delegation. With Event delegation we can apply event handler to an element and using this as a basis for manipulating its children element. In all browsers except IE you can access the source element of the event by accessing target property of the event. For IE you need to use srcElement.

            var targetNode = e.target || e.srcElement;

            // Test if it was a TR that was clicked: 

            if (targetNode.nodeName.toLowerCase() === 'tr') {

               

            }

 

Event delegation relies on event bubbling. The above code wouldn't work if the bubbling was halted before reaching the 'table' node.
21 junio

Lambda Expression Tree

Lambda expression is parsed as tree under the hood. The lambda expression is parsed and stored as tree-shaped structure. Each node in the expression tree is represented as expression. System.Linq.Expressions.Expression class contains static factory methods that can be used to build and manipulate expression tree. The following figure shows how a simple expression is parsed and represented.

 

image

 

As the above figure shows, the expression is represented with two parameters: Body and Parameters. We had two parameters in the image above. Each parameter is of type Expression (ParameterExpression). FYI, there are several types of expressions(BinaryExpression, ConditionalExpression, ConstantExpression etc) that is derived from base Expression class. Also, Body is of type Binary Expression. So lets take an expression and dissect it.

 

Analyzing an Expression Tree

Say we have a function representing delegate  Func<int, bool>. The expression is:

Expression<Func<int, bool>> expressionTree =(i => i> 5);  

The expression has subparts that has shown in the image below

image

Here in the above statement we see the lambda expression takes an integer value and check if the value is greater than 5 or not and return a boolean value. The above expreesionTree variable's two property we have used in the code below. One is parameters collection and another one is Body. Parameters collection is of length one as we have only one parameter i

//This is i before the lambda expression

ParameterExpression param = expressionTree.Parameters[0] as ParameterExpression;

//this is the body of the expression, right side of lambda operator (=>). i.e., i>5

BinaryExpression  body=expressionTree.Body as BinaryExpression;

//This is the the i in the body. I.e., i on the left side of greater than

ParameterExpression left = body.Left as ParameterExpression;

//This is the constant in the body. That is 5

ConstantExpression right = body.Right as ConstantExpression;

Console.WriteLine("Docomposed Expression: {0} => {1} {2} {3}", param.Name, left.Name, body.NodeType, right.Value);

Building an Expression Tree

We can build the same expression tree that we have seen in above (for expression i=>i<5). All we need to do to generate different expressions (BinaryExpression, ConditionalExpression,ConstantExpression etc) and combine these properly into a single expression. Finally we need to compile and invoke the expression. A shown in the code snippet below, we can use Expression static methods to generate various types of expressions. we can generate a full function from that expression with Expression.Lambda method.

 

//bulild the prarameter expression

ParameterExpression param=Expression.Parameter(typeof(int),"i");

//build the constant expression

ConstantExpression constant = Expression.Constant(5, typeof(int));

//build the binary expression

BinaryExpression numLessThanAndEqual = Expression.LessThanOrEqual(param, constant);

//build the whole expression. that is body

Expression<Func<int, bool>> func = Expression.Lambda<Func<int, bool>>(numLessThanAndEqual, new ParameterExpression[] {param });

//complile the expression

Func<int,bool> compiledFounction = func.Compile();

//invoke the expression

compiledFounction.Invoke(10);

 

 

 



19 junio

Lambda Expression: Basic and benefits

Generally, a Lambda Expression is anonymous function that use lambda expression (=>) which is read as "goes to". The format of the lambda expression is as follows:

parameters => body

Here if number of parameters is one the parenthesis is optional. If more than one parameters are used then parameters need to inside parenthesis. Also if the number of statements in body part is one then no second bracket is needed but if number of statement is more than one then statements need to inside second bracket. In the following code snippet I have declared two delegates. One represent integer binary operation signature and another is for unary operation signature.

 

The delegate with unary integer operation signature is as follows:

delegate int DelUnary(int i);

In the above statement the delegate name is DelUnary and it taken an integer value and return an integer value.

 

The delegate with binary operation signatue is as follows which takes two integer value and return an integer value:

delegate int delBinary(int t, int x);

 

Now lets talk about unary delegate. We need two methods for incrementing and decrementing values. So we can define these two functions and assign those two functions in a variable of type DelUnary as shown below:

            DelUnary increment = x => x++;

            DelUnary decrement = x => {x--};

In the above statement we have declared an variable (increment , decrement) of type DelUnary and then we have defined the body of the methods (increment, decrement). The body start after equal sign (=). The body part (x=x++;) or (x=>x--) has two parts. The left part of lambda operator (=>) is parameter (i.e., x) and right part of the lambda expression is the method body. The body may contains multiple statements but its recommended not to be more than 2/3 lines. In case of multiple statements you need to use curly braces({}) for enclosing statements.

Now we can call the method as

            int i=0;

            Console.WriteLine(increment(i));

            Console.WriteLine(decrement(i));

 

Similarly we can declare binary functions and call them as shown below:

            delBinary multiplication = ((x, y) => x * y);

            delBinary summation = ((x, y) => x * y);

            delBinary subtraction = ((x, y) => x * y);

 

            int m = 5;

            int n = 10;

            Console.WriteLine(multiplication(m, n));

            Console.WriteLine(subtraction(m, n));

            Console.WriteLine(summation(m, n));

 

Lambda expression allows us to write small code to do more. Lets say we have a collection of names and we need to find person whose name start with "mar". So in conventional C# we write something as shown below:

 

        string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

        IList<string> foundNames= new List<string>();

        foreach (string name in names)

        {

            if (name.StartsWith("mar"))

            {

                foundNames.Add(name);

            }

        }

 

But with lambda expression we can easily shorten the above code into small and more neat form as shown below:

string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

IList<string> foundNames = names.Where(s => s.StartsWith("mar")).ToList();

Isn't that goo huh? I like this coding style very much and I have used this style in my few new projects. Believe me I'm enjoying this coding style. When I started using lambda expression for the first time it was a kind of wired stuff to me. But as I'm exploring I'm finding this really interesting and I personally believe that it will increase programmer productivity as programmer need to write lees code.

Next time I'll explain Lambda Expression Tree which is also interesting.

17 junio

CLR and .Net Framework: Some information to share

.Net Framework 4.0 in on the way and Vance Morrison, an CLR architect has talked about the how CLR has evolved from the the very beginning to till now. With .Net Framework 2.0 CLR version 2.0 was released. But with .Net Framework 3.x the CLR version was the same, i.e., CLR version 2.0. Now with .Net Framework 4.0 CLR version 4.0 is going to be launched. So Where is CLR version 3.0? Actually this does not exists and will never exists. To keep the CLR and .Net Framework version consistent CLR is named from 2.0 to 4.0.  I have recently come to know some new information about CLR and .Net Framework that are summarized below:

 

 

We can see source code of an assembly (if it's not encrypted) with reflector. Doesn't it break intellectual property?

Reflector unveil the source code and someone raise question about intellectual property but just unveiling source code doesn't mean the everything. A successful software system is more than just source code. Successful system is composed of dev team, test team, marketing policy, support team etc

Exception Modeling in CLR need to be optimized (As  per CLR Architect Vance Morrison)

The exception modeling in .net framework need to optimized. But the problem is that this will change the way programmer works. So changing the exception modeling, exiting exception handling may not work.

String Manipulation in CLR can be optimized (As per CLR Architect Vance Morrison)

By default string in .net takes two bytes of space as this is Unicode string. But in real world most of the systems are not multilingual system and needs only ANSI characters. So this is kind of waster of resources. Also more than 25--30% of the total resources in a system is string. So reducing the string size to half we can save around 10-15% of resources. So as per Vance Morrison, he has a vision to do something to make the string types configurable so that developers can specify which string they want to use.

Interface uses may create problem from version to version

We can't add default implementation of a method in an interface. For example in a class library version 1 an interface Interface1 has two methods. But in version 2 another one method is added. The problem is that with that new version of class library the older code will break. So Microsoft is working on .net framework to provide a way to say version 2 that "hey If this new method doesn't exist then create a default method"

Why multiple inheritance is not supported in c#?

The simple question is to make the implementation easier. If a class ClassA inherited from three different base class Base1, Base 2 and Base3 and each of them has a property (i wanna say state foo) then in composite object ClassA it might be difficult to find out which foo is to be incorporated in derived class. Some programming languages like C++ has virtual concept which may solve the problem but it make the inheritance model more complex and dotnet framework did not follow the path. These problem becomes even complex with diamond problem. State(class fields) are bad in this multiple inheritance as you need to decide which state to keep in case of multiple inheritance. But multiple contracts (methods) are fine as we can call the base contract(method) from derived one with prefixing base one (say Interface1.Contract1(), Interface2.Contract1() etc). So whether to allow multiple inheritance or not was a design problem for CLR designer and they choose not to allow multiple inheritance to avoid complexity with implementation. If multiple inheritance is supported then developer had to dealt with problems like diamond problem.

13 junio

Preliminary System Requirements for SharePoint 2010

The next Office Suit Office 2010  (including Office Web applications, SharePoint Server 2010, Visio 2010 and Project 2010)  will enter a technical preview in the third quarter of 2009 and will release to manufacturing in the first half of 2010. SharePoint 2010 will be 64-bit only. So Sql server 2008/2005 64 bit is supported with SharePoint 2010. Also Supported operating system is 64-bit Windows Server 2008 or 64-bit Windows Server 2008 R2.

 

The main focus on this next office suit is like "Office everywhere". So it just like office application on web. The line between home and work has blurred, so people want more choice and flexibility in how, where and when they work. They’re also demanding the ability to access and effectively manage their information whether at home, at work or on the go. With next office suit familiar interface will be provided across pcs, browser and cell phone. Microsoft has got that people want the freedom to use office applications from more locations (home, office and everywhere) and on more devices.

 

Though Office 2007  integrated with web but Office 2010 may be the true web base office system. So is Microsoft moving from "Microsoft office" to "Microsoft Office on Web"!!!!!!!

12 mayo

Combine Ajax axd files into one to improve performance

If we use Ajax or Ajax related controls then we'll find that a lot of script related requests are made to the server. Browser can request two concurrent requests to the server. For example browser may request for an image and while the image is loading the browser may request for an CSS file. But in case of javascript, browser can't request for two files. When browser request for a script file, it stops for any other request to the same server.

 

When you use Ajax or Ajax related tools (such as AjaxControlToolkit) the browser sends aysnchronous request to the server which is of extension (.axd). The number of asynchronous requests in axd form, the more time it'll take to load the page. So if we can combine those axd requests into one then we can get noticeable improvement in page loading.

image

Figure: axd requests to the server

Here are the steps to combine axd scripts to a single on.

1. Find all the javascript reference in your page. To do so, download the script reference profile from http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=13356. Then  register the dll in ur page and add the scriptreference profile as shown below:

Register the dll in page:

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

Add Control to the page:

<microsoft:ScriptReferenceProfiler ID="profiler1" runat="server" />

After adding the script profiler if you run the page then you will find all the script reference in your page as shown below. Remember you can't combine Microsoft provided js file like MicrosotAjax.js, MicrosoftAjaxWebform.js etc.

image

Figure: Script reference found by script profiler

2. Then use the scriptmanage's combinescript tag to combine script:

<asp:ScriptManager ID="sm1" runat="server" CompositeScript-ScriptMode="Release">

    <CompositeScript>

        <Scripts>

            <asp:ScriptReference Name="AjaxControlToolkit.Compat.Timer.Timer.js" Assembly="AjaxControlToolkit, Version=3.0.20820.23813, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e" />

            .

.

.

            <asp:ScriptReference Name="AjaxControlToolkit.CollapsiblePanel.CollapsiblePanelBehavior.js"

                Assembly="AjaxControlToolkit, Version=3.0.20820.23813, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e" />

        </Scripts>

    </CompositeScript>

</asp:ScriptManager>

After combining those scripts you'll find that the page loading time improved significantly. Some useful links:

http://lancezhang.wordpress.com/2008/11/15/aspnet-ajax-performance/


03 abril

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.

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.

21 marzo

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

18 marzo

Asp.net 4.0 Key features

In asp.net Microsoft has given emphasis on Ajax. The great new feature is client site template. We are used to use repeater, datagrid controls on server side. Now in ajax 4.0 client site template is also available. Now with new client site control called dataview user will be able to define client side temple for the raw data. The raw data will be passed to the client in JSON and then the data will be parsed in dataview based on client side template defined in dataview.

 

Another new feature is Client ID mode. We are use to get the client id of a server side control by writing code like

document.getElementById('<%=div1.ClientID %>');

Now in asp.net 4.0 we can define how server side control's client ID will be.If developer wants the client id will be just the id defined rather than changing name like control1$subcontrol1$divMain. There are few others options for client id mode.

 

Now someone may ask as Microsoft emphasized on both Silverlight as well as Ajax and both technologies are client side technologies, so are these technologies are competing each other? The answer is these two technologies are designed for two different types of applications. For example if your site is for video uploading/downloading and streaming site then Silverlight is the best choice. With Ajax you'll have to work a lot to develop such site.

10 marzo

Covariance and Contravariance in C#

To get a brief discussion on what covariance and contravariance are follow the great post on Eric Lippert's Blog or Visit Wikipedia

 

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).

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:

 

clip_image001[31]

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


09 marzo

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



25 febrero

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.

 

23 febrero

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:
 
19 febrero

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.
 
 
10 febrero

IIS 7

Today I was watching a video on IIS 7.0 and I'm really excited with some new featured of IIS 7.0. There's a great new Management console for IIS which is developed with managed code. So the IIS 7.0 is developed with managed code and this has extensibility. For example, for you application if you need to put some entry in config file then you can extend IIS manager to provide UI for editing those configurations. That's great because user don't need to go to config file to change settings manually. So if your site have connection string in the config file then you can provide an UI for in IIS manager for editing that connection string.

Also we can easily trace events and analyze those for tracking problems. For example we can specify conditions for tracing like: trace those events which has taken more than N sec, trace critical errors or trace those requests whose status is 500, trace for request of aspx file etc.