Labels

Sunday, April 29, 2007

Perfect Equality Choice..

 

There is always a confusion among the Equality choices…

 

Reason:  Looking at System.Object seems surprising at first sight is the fact that it defines four different methods for comparing objects for equality:

 

·         ReferenceEquals() and

·         Two version of Equals().

o   Virtual

o   Static

·         Add to this the comparison operator (==),

 

So, actually we have four ways of comparing for equality.

 

Now what to choose, depends on the mechanism of Object Equality differs depending on whether you are comparing :

·         Reference Types (instances of classes), or

·         Value Types

o   Primitive data types,

o   Instances of structs or enums

 

Before we come to the actual difference let’s have a quick description:

               

1.       ReferenceEquals() Method

a.       Static method

b.      Tests whether two references refer to the same instance of a class.

c.       As a static method, it is not possible to override to compare objects by value. [Drawback – Resolved in 2(a)]

 

2.       Virtual Equals()

a.       Method is virtual, hence can be overridden.

                                                               i.      One point you should note when overriding Equals() is that your override should never throw exceptions.

b.      Throws an exception when overridden and either of the compared object is null. [ Drawback- Resolved in (3(a, b)]

                                                               i.      Definitely the raised exception can be caught, but raising the exception could cause problems for dictionary classes and possibly certain other .NET base classes that internally call this method.[ Drawback- Resolved in (3(a, b)]

c.       Tests whether two references refer to the same instance of a class.

 

3.       Static Equals()

a.       Does the same thing as Virtual with below exceptions

                                                               i.      Takes two parameters

                                                             ii.      This method is able to cope when either of the objects is null, and therefore, provides an extra safeguard against throwing exceptions if there is a risk that an object might be null.

 

b.      Now let say if you need to enjoy the overridden functionality and also want to be sure that nothing should go wrong [i.e no exceptions] when either of the object is null, then here is the solution.

                                                               i.      Use the Static Version and forget it. Here it takes care automatically.

1.       If either of them is null, it will return false, and

2.       If both references actually refer to something, then it calls the virtual instance version of Equals().

a.       This means that when you override the instance version of Equals(), the effect is as if you were overriding the static version as well.

 

 

Now here is the verdict.

 

 

= =

RefererenceEquals(x,y)

Virtual Equals(x)

Static Equals(x,y)

Value Types

Check for Value Equality

Checks for Reference Equality.

 

Will always return false.

Reason: Boxing is required and hence boxing will result into two different objects.

Overridden for ValueTypes: Hence Checks for Value Equality.

 

But, But, But,,,, using ‘==’ for structs [Again a Value Type] willl result in compliation error as there is no overloaded version is present of ‘==’ for value types.

 

Reference Types

Check for Reference Equality & never checks objects based on their contents.

 

Will return False, if both objects are different.

 

Will return True, if both objects are same, i.e points to same location.

Check for Reference Equality & never checks objects based on their contents.

 

Will return False, if both objects are different.

 

Will return True, if both objects are same, i.e points to same location or both are null.

 

 

Problem: Cannot be overridden to compare objects by value.

 

Check for Reference Equality & never checks objects based on their contents.

 

Will return False, if both objects are different.

 

Will return True, if both objects are same or null, i.e points to same location.

 

 

Problem: Can be overridden to compare objects by value, but will throw an exception if either of them is null.

 

Check for Reference Equality & never checks objects based on their contents.

 

Will return False, if both objects are different. Or either if them is null.

 

Will return True, if both objects are same, i.e points to same location or both are null.

 

 

 

String Types

Same as Value Types

Overridden for String Types:  Hence Checks for Value Equality.

 

 

 

Here is the quick walkthrough:

 

 

þ  For comparing Value Types which should be used?

 

o   Object.ReferenceEquals will always return false, at it required boxing value types into reference types. These boxing results in creation of two different objects and hence return false.

 

bool res= Object.ReferenceEquals(1,1);  // False

 

int i=1, j=1;

bool res= Object.ReferenceEquals(i,j); // False

 

So do not use it for Value Types.

 

o   Using ‘==’ or Object.Equals(i, j) or i.Equals(j), for value types will similar results, as both version of Equals() are overloaded by C# to work for value types, and checks content equality.

 

int i=1, j=1;

 

i == j;                                                     // True

                                bool res= i.Equals(j);                        // True

bool res= Object.Equals(i, j);   // True

 

But, But, But,,,, using ‘==’ for structs [Again a Value Type] willl result in compliation error as there is no overloaded version is present of ‘==’ for value types.

 

Using both the version of Equals() for struct will perform perfect and will check the content equality, provided struct do not refer any reference types.

 

þ  For comparing Reference Types which should be used?

 

o   Using ‘==’ :  Will Check reference equality.

 

Class1 obj1=new Class1(1,"AA");

Class1 obj2=new Class1(1,"AA");

 

obj1 == obj2   // False

 

obj1=obj2;

obj1 == obj2   // True

 

 

o   Using Object.ReferenceEquals : Will Check reference equality.

 

Object.ReferenceEquals(obj1,obj2)   // False

 

Obj2=obj1;

Object.ReferenceEquals(obj1,obj2)   // True

 

Obj2=null;

Object.ReferenceEquals(obj1,obj2)   // False

 

o   Using  Someobject.Equals( some obejct): Virtual Version

                                             

obj1.Equals(obj2)   // False

 

Obj2=obj1;

obj1.Equals(obj2)   // True

 

Obj2=null;

obj1.Equals(obj2)   // False or Exception- In case of Overridden. 

 

 

o   Using Object.Equals( some obejct, some obejct): Static Version

 

Object.Equals(obj1,obj2)   // False

 

Obj2=obj1;

Object. Equals (obj1,obj2)   // Will in turn call Virtual method à True

 

Obj2=null;

Object. Equals (obj1,obj2)   // False

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Thursday, April 26, 2007

Session_End v/s 'User.Identity.IsAuthenticated'

Below are few key concepts associated with Auto/Forced Session_End event & FormsAuthentication.SignOut().

 

Facts with Auto/Forced Session_End event.

We know that changing Web.config clears the Session/Application state and in result ‘Session_End’ event will fire in Global.asax.

Or maybe the possibility that something goes wrong and Session_End event fires automatically.

 

Whenever the Session_End event fires below are do’s and don’ts:

·         Clears the Session State.

·         But Still the , it does not clear the ‘Authentication’. i.e Still the ‘User.Identity.IsAuthenticated’ will return true. Hence the flow-control will remain on the same page and will not be redirected to ‘Login’ Page.

 

Justification:

1.       Login with login page

2.       Go to ModifyConfig.aspx page.

a.       Here do some modification in Web.config which leads to ‘Session_End’ event fires.

b.      Though the Session_End event fires, the control remains on the same page i.e. ModifyConfig.aspx

c.       Now if you click some button again on this page and tries to access ‘‘User.Identity.IsAuthenticated’, it will return true.

3.       Hence if you need the functionality as: The control should be redirected to ‘Login’ Page, once you make the modification in Web.config, do fire two things:

a.       FormsAuthentication.SignOut().

b.      Redirect to the same page. This will automatically will throw you to the login page.

 

 

Facts with FormsAuthentication.SignOut():

 

Whenever we call thi smethod below are do’s and don’ts:

·         It will not fire the Session_End Event.

o   Hence in turn will not clear the Session State. i.e If you try to access the Session after calling this method, you’ll be able to access the Session Data.

o   Solution : Explicitly call Session.Abandon().

§  This will fire the Session_End Event and will clear the Session.

·         But still the lines accessing Session just below the Session.Abandon() statement will be able to do that.

o   Will clear the ‘Authentication’. i.e the ‘User.Identity.IsAuthenticated’ will return false.

o   Also won’t  redirect automatically to the login page.

§  Solution: Redirect to the same page. This will automatically will throw you to the login page.

§  Or will be redirected to the login page on next click event on the page.

 

 

 



 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Tuesday, April 24, 2007

Don't use with ASP.NET AJAX

If you automatically migrate a VS 2003 Web Project to VS 2005, you might end up facing some weird JavaScript issues(both when using ASP.NET AJAX and with some other custom JavaScript routines). The problem is that you may have the <xhtmlConformance mode="Legacy"/> switch configured within the web.config file. 

If you are writing custom client-side JavaScript in your web application and/or are going to be using AJAX, please read-on to learn how to avoid a common gotcha.

Symptom:

You see strange behavior when adding new client-side JavaScript to a project that was previously upgraded (successfully) from VS 2003 to VS 2005.  When using ASP.NET AJAX UpdatePanel controls, this strange behavior can sometimes include cases where the page does a full-page postback instead of just incrementally updating pieces of a page. 

When you open up your web.config file, you also see a <xhtmlConformance/> element within it like so:

<configuration>

    <system.web>
        <xhtmlConformance mode=&! quot;Legacy" />
    </
system.web>

</configuration>

Background:

ASP.NET 1.0 and 1.1 didn't emit XHTML compliant markup from many of its server controls.  ASP.NET 2.0 changed this and by default emits XHTML compliant markup from all controls.

For backwards compatibility purposes we added the <xhtmlConformance> switch was added that allows developers to render controls in "Legacy" mode (non-XHTML markup the same as ASP.NET 1.1) as well as Transitional mode (XHTML Transitional) as well as Strict mode (XHTML Strict). 

By default when you use the VS 2003->VS 2005 Web Project Migration wizard (for both web sites and web application projects), your web.config file will have the legacy switch added.

Solution:

Unless you know of known issues that your site has when running in XHTML mode (and which you don't have time yet to fix), remove the <xhtmlConformance> section from your web.config file (or you can explicitly set it to "Transitional" or "Strict"). 

This will make your HTML output standards compliant.  Among other things, this will cause the HTML from your server controls to be "well formed" - meaning open and close tag elements always match.  This is particularly important when you are using AJAX techniques to dynamically replace the contents of certain HTML elements on your page (otherwise the client-side JavaScript sometimes gets confused about container elements and can lead to errors).  It will also ensure that ASP.NET AJAX works fine with your site.

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Thursday, April 19, 2007

Why don’t file uploads work during AsynPostback

In AJAX-enabled pages, file uploads do not work when doing an async postback. To understand why the upload doesn't work it's important to understand how async postbacks are performed and how is that different from how the browser performs a regular postback.

When the browser performs a regular postback it has the benefit of being actual code with no security restrictions running on the client computer. When you submit a form it creates a web request with all the form fields. When it encounters an <input type="file"> it examines the file the user chose, reads it from disk, and adds it to the web request.

When the AJAX JavaScript code is running in the browser it can do the first part about creating a request with all the form fields. However, when it gets to <input type="file"> fields it doesn't have the necessary security permissions to read those files from disk. Imagine what would happen if it could read those files – a potential security threat.

So what's the workaround? Well, quite simply, the workaround is to do anything that doesn't involve a file upload during an async postback. Here are some solutions:

  1. Have a dedicated "Upload" button that does a regular postback instead of an async postback. You can achieve this using several techniques: Have the button be outside all UpdatePanels; have the button be the target of an UpdatePanel's PostBackTrigger; or call ScriptManager.RegisterPostBackControl() on it.
  2. Have a dedicated file upload page that doesn't have any UpdatePanels. Many web sites already do this anyway.

People have also come up with various workarounds and articles on how to trick UpdatePanel into allowing file uploads during async posts. Here is the link to one that uses some clever techniques that ASP .NET AJAX enables to reroute the requests - http://www.jeffzon.net/Blog/archive/2007/03/31/Let-UpdatePanel-support-file-uploading-Lets-Get-Started.aspx

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Wednesday, April 18, 2007

Auto Intellisense in Web.config

We all know that, in .Net 2.0, Auto-Intellisense in Web.config is built in.

But this intellisense no longer continues, once you access the 'Web Configuration Utility' using the last link button provided in 'Solution Explorer'.

For Reference: 'Web Configuration Utility' is the Web-Tool [New feature in 2.0], oftenly used to configure the non-rememberable attributes of Web.config.

The reason being is the addition of an extra attribute [xmlns="........."] to the root tag i.e <configuration> tag xmlns=".........", as shown below.

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

Now, If you wish to bring the auto-intellisense again, just remove this new addition.

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Quick fix to bring Web Application Offline.

Normally to bring any Live Application Offline, either we thought of making few fixes in IIS or may be in the applications code.

 

However, below are the two quick approaches to achieve the same.

 

Make Application Offline:

 

1.      Add below to your web configuration file:

 

<httpRuntime enable="false" />

 

2.     Add a file with the name app_offline.htm to the root of your application.

 

 Now if you try acccessing any page of the Web Application, you can't.

 

Note: It is not a recommended approach. It is just a quick fix...

http://msgnagpur/_layouts/images/blank.gif

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Friday, April 13, 2007

AppDomain Concept

Below is the way how Appdomain works:






A single process can run several application domains.











þ A single managed process (one which has loaded the CLR) can contain any number of AppDomains.

þ The simplest only contain one.

þ AppDomains:

o Are a finer-grained level of isolation between logical components inside the same process, for both reliability and security purposes.

o They are a good alternative to Process-Level Isolation because of the relative inexpensiveness of Creating, Managing, And Switching execution and due to the level of Resource Sharing among AppDomains in a process.

o AppDomains within a process are not entirely isolated. While they do generally load their own assemblies and have their own copies of static variables, for example, resource leaks from one AppDomain can affect another and HANDLE-thieving security holes are possible because AppDomains share a single per-process handletable. AppDomains can be shut down individually while still keeping the enclosing process alive.



Regards,
Arun....

Myth regarding View State

http://msdn2.microsoft.com/en-us/library/ms972976.aspx

http://www.codeproject.com/aspnet/ViewState.asp

 

 

Myth:

 

Most ASP.NET developers think that the ASP.NET ViewState is responsible for holding the values of controls such as TextBoxes, DropDown, CheckBox and other Web Controls, across postback, so that they are retained even after postback. But this is nothing more than a Myth.

 

The ViewState is not responsible for storing the modified values/postback data for controls such as TextBoxes, dropdowns, CheckBoxList etc.

The hidden actor is the ‘IPostBackDataHandler’ interface. i.e For those controls that inherits  ‘IPostBackDataHandler’ interface, postback data is not required to be dependent on the View State [The Myth].

 

Note: Label control does not inherit from the IPostBackDataHandler interface, so the value of the Label control does not persist if the ‘EnableViewState’ flag is set to false.

 

Lets us c with the help of events to know how it happens.

 

þ  Page_Init event occurs:

þ  Here the Page and controls fire their Init events

þ  At this point in the page life cycle, the control hierarchy has been constructed, and the Web control properties that are specified in the declarative syntax have been assigned.

 

þ  LoadViewState event occurs:

þ  This stage only happens when the page has been posted back.

þ  During this stage, the view state data that had been saved from the previous page visit is loaded and recursively populated into the control hierarchy of the Page. But if the View state is disabled then nothing happens at this stage.

 

þ  LoadPostBackData event:

þ  This stage only happens when the page has been posted back.

þ  Here the Page class loads the values of those controls which inherit from the IPostBackDataHandler interface, (e.g., TextBox, Dropdowns, Checkboxes and other), by calling the control's LoadPostData() method.

þ  It works well even when the ViewState is disabled.

 

Note: It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler.

 

 

Validate the Myth using below Test Case:

 

Create an example having below. [Note: Set EnableViewState = false for all controls declared below].

  • Textbox  [ Declarative value: ‘Textbox1’]
  • Label [ Declarative value: ‘Lable1’]
  • Button [Caption; ‘Change’] 
    • With below code behind
      • TextBox1.Text = "Change 1";
      • Label1.Text = "Change ";
  • Button [Caption; ‘Post back] :
    • This is simply used to Postback.
    • No code is attached.

 

Now below happens:

 

  • First time when page appears, controls will be containing there declarative values.
    • Textbox   :  Textbox1’
    • Label : ‘Lable1’
  • Click on ‘Change Button’: When the page renders,  Controls will be containing the programmatically assigned values
    • Textbox   :  "Change 1";
    • Label : "Change";
  • Click on ‘Postback Button’: When the page renders, Controls will be containing the below values.
    • Textbox   :  "Change 1";
    • Label : " Lable1’"; [Will be default to its declarative value.]

 

Now enable the ViewState for the Label control. Then in the third step [Above Exercise], you will find that the changed value appears.

So the conclusion is that controls which inherit from the IPostBackDataHandler interface will retain their values even if the ViewState has been disabled.

 

Regards,

Arun…..

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.