Tuesday, July 31, 2007

ViewState transition

View state is page scoped and is valid for that page only. View state should not be transferred across pages.

The Viewstate structure
The Viewstate field is not crypted. But it has a 2 level coding:

* first all HTML punctuations, like "<", "+", "=" are encoded using a %nn notation. For instance, "+" is coded as "%2B" (where $2B is the Hex value of the ASCII code of ".")
* then the text is "base 64" encoded: to fit all 256 possible byte value in 7 bits, there is a transcoding from 8 to 7 bits.

The resulting decoded string follows a "compact xml" structure, where the elements are all between "<" and ">" and the elements of the tags are triples, pairs, lists arrays and indexes.

The IEBNF (Indented Extended BNF) grammar of this coding is


viewstate= element .
element = triple | pair | list | index .
triple= 't<' element ';' element ';' element '>' .
pair= 'p<' element ';' element '>' .
list= 'l<' { element ';' } .
index= 'i<' value '>' .
value= ANY_BUT ( ';' | '>' ) .

Refernces article


What happens if i do pass it on?

Similar to "ViewState" there are other option to save temporary data like "Cache", "AppDomain"


each one has its own use.
ViewState - Is good for page level data storage, where amount of data is small.
Cache - Is good for large amount of data
AppDomain - Is good for across client commuication.like sharing a specific details across all active clients.



From Another Article

Question: I set my page's EnableViewState property False; why is there still a __VIEWSTATE hidden form field?

ANSWER: A while back I wrote an article for MSDN online titled Understanding ASP.NET View State, and blogged about the article in this past entry. I recently noticed a comment in that blog entry from Matthias Cavigelli, asking:

When I disable the ViewState property of the page, I still have the hidden field __VIEWSTATE in the html code. Could you explain why it's still there although it's not enabled?

What Matthias is referring to is the EnableViewState property, which is defined in the System.Web.UI.Control class (which means that all ASP.NET server controls have this property, including the Page class from which all ASP.NET Web pages are derived.) This property defaults to True, which means that, by default, a control should track its view state and save its view state during the SaveViewState stage of the page's lifecycle. By setting EnableViewState to false, a control is saying, "Don't bother recording my view state."

Setting EnableViewState to False on certain state-heavy controls is a good way to trim the size of a page's view state. Of course, you must take care when tweaking this property, since the state-heavy controls typically rely on the view state to maintain their functionality. Here's a good example of when you can set EnableViewState to False: when you have a DataGrid Web control on a page that simply displays data, and where the DataGrid's properties are not programmatically changed on postback. (Note: if this page does have postbacks you'll have to make sure to rebind the database data to your DataGrid on every postback.)

If your page does not perform any postbacks at all, having view state is a big waste. So, you might as well set the Page class's EnableViewState to False, so that no view state is saved for the entire page. Or so you'd think. If you set EnableViewState to False for the page, you'll still get a hidden __VIEWSTATE form field, although it will be pretty small. Why does this hidden form field exist at all?

To answer this question it is important to realize that view state really is paramount to Web Forms, not the Page class. (A Web Form is a server-side form tag, which is represented in the .NET Framework via the System.Web.UI.HtmlControls.HtmlForm class.) If a Web Form exists, there typically needs to be a hidden __VIEWSTATE form field. But the Web Form does not know the complete view state of the page. The Page class, for instance, has a ViewState property, into which a page developer can store items into the view state. The Web Form, obviously, is ignorant about this. So there's this chicken-and-egg thing going on here - the Page knows how to completely represent the view state, but it's the Web Form that cares about it, not the Page. The end result is that the Page class is responsible for generating the hidden __VIEWSTATE form field, but it's the Web Form that knows whether or not this is needed.

To overcome this hurdle, the Page class needs some way to know whether or not the __VIEWSTATE form field needs to be emitted or not. To allow for this, the Page class provides a public RegisterViewStateHandler() method; if this method is called during the page lifecycle, a __VIEWSTATE hidden form field will be emitted, even if the Page class's EnableViewState property is set to False.

From a Web Form's perspective, it always needs to save view state. Well, this is the way the Web Form class was programmed by Microsoft. You can see this by examining the HtmlForm class's OnInit() method:

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Page.SetForm(this);
this.Page.RegisterViewStateHandler();
}

Personally, it would seem to make more sense to me to have Page.RegisterViewStateHandler() called only if Page.EnableViewState is true, but there may be a reason behind this that I haven't seen. Anywho, when the Web Form is rendered, it calls an additional two of the Page class's methods:

1. OnFormRender() - this adds the __VIEWSTATE hidden form field along with any registered hidden form fields or script blocks registered via Page.RegisterClientScriptBlock().
2. OnFormPostRender() - this adds any script blocks registered via Page.RegisterStartupScript() and any client-side arrays registered via Page.RegisterArrayDeclaration().

You may still be wondering why when the Page's EnableViewState is False that the __VIEWSTATE hidden form field has anything in it. Well, if you take a look at the Page class's SavePageViewState() method, you'll see:

internal void SavePageViewState()
{
if (!this._needToPersistViewState)
{
return;
}
Triplet triplet1 = new Triplet();
int num1 = this.GetTypeHashCode();
triplet1.First = num1.ToString(NumberFormatInfo.InvariantInfo);
triplet1.Third = this._registeredControlsThatRequirePostBack;
...
triplet1.Second = base.SaveViewStateRecursive();

this.SavePageStateToPersistenceMedium(triplet1);
}

So what you see her is the following: if _needToPersistViewState is False, then nothing is saved. Well, this flag is set to True when the Web Form calls Page.RegisterViewStateHandler(). So a Triplet is built up, with the first item containing the page's hash, the third item containing an ArrayList of Web controls that require a postback. Now, the second item is where the meat of the view state comes from - this is the sum of the view state of the controls in the page. But if EnableViewState is False for the page, SaveViewStateRecursive() returns null.

So even if you set the Page's EnableViewState to False, you'll still get a __VIEWSTATE hidden form field with the Page's hash and ArrayList of controls that require postback. I still don't see why this is needed, but there is likely a good reason.

Rounding Off decimal places

what is the output of the following statements :

Console.WriteLine(decimal.Round(Convert.ToDecimal("0.05"), 1)); --0.0--
Console.WriteLine(decimal.Round(Convert.ToDecimal("0.15"), 1)); --0.2--

5 at 2nd decimal place is rounded to 1 if first decimal places is non-zero else zero
Why?



Explanation
The decimal.Round version that take 2 parameters
rounds midpoints to the even number (Banker's Rounding)
rather than rounding them away from zero

i.e
decimal.Round(0.05, 1); // 0.0
decimal.Round(0.15, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.35, 1); // 0.4
etc.

To get 'normal' rounding (midpoints are rounded away from zero)
you can use a overloaded version of the decimal.Round
method that takes a thrid parameter, which
specifies how to treat midpoints:

ie
decimal.Round(0.05, 1, MidpointRounding.ToEvent); // 0.0 Banker's Rounding

decimal.Round(0.05, 1, MidpointRounding.AwayFromZero); // 0.1

Monday, July 16, 2007

Basics

Value and Refference types
By default in C# everything is passed as value type.

Structs are value type and Classes are reference type. Value types are assigned memory in stack with an exception of In-Line value types asssigned in heap. Reference types are always assigned memory in heap.

value type means a copy of whatever is being passed either a reference type or a value type.



Interface - Abstract Class
What is an Interface?

An interface is a contract, a specification that concrete classes MUST follow. It defines method signatures but cannot have any implementations; the latter must be provided by the classes that implement the interface.
For example,
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}

what is an abstract class?

An Abstract class lets you define some behaviors and force your subclasses to provide others.
For example,
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}


Differences between Interfaces and Abstract classes ?

I. multiple inheritance

A class may implement several interfaces but can only extend one abstract class.

II. default implementation

An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.

III. adding functionality

If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.
If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

IV. is-a vs -able or can-do

Interfaces are often used to describe the abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

An abstract class defines the core identity of its descendants.


Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.


With abstract classes we can provide a default/general method implementation for all overridding classes whereas in case of interfaces, every implementing class must provide its own specific implementation.




Static (Type) or Instance Constructer
Static or Type Constructor :

used to provide a one way access to the class object. you can restrict the class intance to itself using a static constructer. it also provide ways to make singelton class or a clone function, which always returns the class object.
Only one class constructor per type is permitted.
It cannot use the vararg (variable argument) calling convention.

Instance Constructor :

is executed every time a new object is created and is specific to that object instance.
Multiple instance construtor are allowed with different parameter list (return type ie void and name are fixed).
It cannot use the vararg (variable argument) calling convention.
Instance constructors are not allowed to be a virtual type.




Ex :

using System;
class SomeClass {

private Int32 member1;
private static Int32 member2;

//Type constructor
static SomeClass(){}

//Instance constructor
public SomeClass(){} //default instance Constructor
public SomeClass(Int32 memberval){ member1 = memberval;}


}



Working Ex:

public class A

{

//Static Constructor of Class A

static A()

{

Console.WriteLine("Static Constructor of Class A");

}

//Constructor of Class A

public A()

{

Console.WriteLine("Constructor of Class A");

}

}

public class B: A

{

//Static Constructor of Class B

static B()

{

Console.WriteLine("Static Constructor of Class B");

}

//Constructor of Class B

public B()

{

Console.WriteLine("Constructor of Class B");

}

}

public class C: B

{

//Static Constructor of Class A

static C()

{

Console.WriteLine("Static Constructor of Class C");

}

//Constructor of Class C

public C()

{

Console.WriteLine("Constructor of Class C");

}

}

#endregion

class ConstructerDestructer

{

static void Main(string[] args)

{

C c = new C();

Console.ReadKey();

}

}



Output :

Static Constructor of Class C

Static Constructor of Class B

Static Constructor of Class A

Constructor of Class A

Constructor of Class B

Constructor of Class C





Interview

ref and out?
A ref parameter must be assigned a value by the CALLER before it is sent to the callee. An out parameter, on the other hand, is sent unassigned by the caller and must be assigned by the CALLEE


why cant i use static and const together?
All constants declarations are implicitly static, and the C# specification states that the (redundant) inclusion of the static modifier is prohibited.


Difference b/w const(compile time constant) and static readonly(set at run time, containing class is allowed to modify) ?


Can we const array of class/struct ?

const int constIntArray = 2; -valid-
int [] xconstIntArray = new int [] {2, 3, 4}; -valid-
const int [] xconstIntArray = new int [] {2, 3, 4}; -not valid- 'const can only be applied to a field or local whose value is known at compile time.'


What is a delegate? Comparision with function pointers?

A delegate is a data structure that refers to a static method or to an object instance and an instance method of that object.
function pointer can only reference static functions, a delegate can reference both static and instance methods.( In the latter case, the delegate stores not only a reference to the method’s entry point, but also a reference to the object instance for which to invoke the method.)


AppDomain & WebServices?

Assembly(physical) & Namespaces(logical)?

Assembly(contains verious modules) & Module(smallest executable part in a assembly)?

Can i generate and load a Assembly at runtime?
yes, use System.Reflection.Emit



Comparision b/w Equals and ReferenceEquals?

if ReferenceEquals true, then Equals true; but vice versa is always not true. ReferenceEquals compare the object pointed to whereas Equals(String) compare value. In case of object type Equals comparision, it compares the object pointed to.

ex:

public static void ReferenceValue(object a1, object a2){

if(object.ReferenceEquals(a1,a2))

Console.WriteLine("Reference Equals");

else

Console.WriteLine("Reference Not Equals");

if(object.Equals(a1,a2))

Console.WriteLine("Value Equals");

else

Console.WriteLine("Value Not Equals");}



string a = "luck"; string b = "luck"; string c = "l"; int s = 1;

Program.ReferenceValue(a, b); // 'Reference Equals' , 'Value Equals'

Program.ReferenceValue(a, c); // 'Reference Not Equals' , 'Value Not Equals'

Program.ReferenceValue(a, s); // 'Reference Not Equals' , 'Value Not Equals'

a = Console.ReadLine(); // enter 'luck'

Program.ReferenceValue(a, b); // 'Reference Not Equals' , 'Value Equals'

Console.ReadKey();

Console.Clear();

a = Console.ReadLine(); //enter 'luck'

b = Console.ReadLine(); //enter 'luck'

Program.ReferenceValue(a, b); // 'Reference Not Equals' , 'Value Equals'

Console.ReadKey();



Virtual Function?

Ex:

using System;
namespace SomeCorpProject
{
public class BaseBusinessObject
{
public BaseBusinessObject() {
}
public override string ToString() {
return "BaseBusinessObject";
}
}
}

using System;
namespace SomeCorpProject
{
public class NCapacitor : BaseBusinessObject
{
public NCapacitor()
{
}
}

public class Capacitor : BaseBusinessObject
{
public Capacitor() {
}
public override string ToString() {
return "Capacitor";
}
}
}

using System;
namespace SomeCorpProject
{
class Class1 {
[STAThread]
static void Main(string[] args) {
BaseBusinessObject bizObj = new Capacitor();
System.Console.WriteLine(bizObj.ToString());
BaseBusinessObject NbizObj = new NCapacitor();
System.Console.WriteLine(NbizObj.ToString());
}
}
} What will happen when this code is compiled and run?

(BaseBusinessObject overrides object.ToString)
---------The word "Capacitor" will be written to the console.(overrides BaseBusinessObject's object.ToString)
---------The word "BaseBusinessObject" will be written to the console.(doesnt overrides BaseBusinessObject's object.ToString)

Properties

Properties
Properties can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. For example, the get may be public to allow read-only access from outside the type, and the set may be private or protected.
A property may be declared as a static property using the static keyword. This makes the property available to callers at any time, even if no instance of the class exists.
A property may be marked as a virtual property using the virtual keyword. This allows derived classes to override the property behavior using the override keyword.
A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. Lastly, a property can be declared abstract, meaning there is no implementation in the class, and derived classes must write their own implementation.

*It is an error to use a virtual, abstract, or override modifier on an accessor of a static property

Abstract Properties
-------------------
A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.
If the abstract class contains only set accessor, we can implement only set in the derived class.
The following program shows an abstract property in action.

using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}

Static Properties
-----------------
C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also.
The following program shows a class with a static property.

using System;
class MyClass
{
private static int x;
public static int X
{
get {return x;}
set {x = value;}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}
Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.
Properties & Inheritance
------------------------
The properties of a Base class can be inherited to a Derived class.

using System;
class Base
{
public int X
{
get{Console.Write("Base GET");return 10;}
set{Console.Write("Base SET");}
}
}
class Derived : Base
{}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}
The above program is very straightforward. The inheritance of properties is just like inheritance any other member.

Properties & Polymorphism
-------------------------
A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

using System;
class Base
{
public virtual int X
{
get{Console.Write("Base GET");return 10;}
set{Console.Write("Base SET");}
}
}
class Derived : Base
{
public override int X
{
get{Console.Write("Derived GET");return 10;}
set{Console.Write("Derived SET");}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}

Variable argument methods

Variable argument methods
sometimes a general purpose requirements is to provide a variable number of parameters to a common logical unit. 'params' keyword in c# helps you perform such sometiems difficult tasks.

only care that should be take while passing variable argument is the type of variable. if you fix the type, then it might become easy but it wont fulfill the variable argument feature.
we will discuss both options :

fixed argument type :

void Ex(params string[] args)
{
foreach(string ar in args)
{
Console.WriteLine(ar);
}
}

Ex("a","d","r","t");


different argument types :

void Ex(params object[] args)
{
foreach(object ar in args)
{
Console.WriteLine(ar);
}
}
//the implementation will be similar to printf function in c

Ex(1, 'a', "text");

ps: problem comes when you need to work on the args and compute some result, which needs the actual conversion on the args to their original type. to do that we need to pass the args type in sequence with actual args sequence, as a string.

void Ex(string sequentialArgsTypeList, params object[] args)
{
//convert each arg based on its corresponding type defined in 'sequentialArgsTypeList'
}
//the implementation will be similar to printf function in c

Ex("int,string,Employee", ob1, ob2, ob3);

VS Debugging tips

Debugging made easy
Visual studio provides a very good way to debug your code whether its running in production or test




Build the report in debug mode.
Copy pdb (Symbol file) and dll and place then in the product you want to debug. The dll copied should be used by the product.
run Product

In VS - Click 'Debug' menu - Select 'Attach to process'
Select your product running services/exe form the process list (if its not visible select 'Show processes from all users' checkbox)
click 'Attach'

Click 'Tools' menu - Select 'Options'
Expand 'Debugging' option in the right panel
Select 'Symbol' option.
Add a symbol option and give the full path of the pdb file.

Apply breakpoint at appropriate places

Now whenever the product tries to access the dll (copied) it will stop at your specified breakpoints)