Wednesday, April 27, 2011

What is Overloading and Overriding

Overloading - is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.

The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined.

Overloading is a way through which polymorphism is achieved.

Overloading

Overloading is when you have multiple methods in the same scope, with the same name but different signatures.

//Overloading

public class test

{

public void getStuff(int id)

{}

public void getStuff(string name)

{}

}

Overriding

Overriding is a principle that allows you to change the functionality of a method in a child class.

//Overriding

public class test

{

public virtual getStuff(int id)

{

//Get stuff default location

}

}



public class test2 : test

{

public override getStuff(int id)

{

//base.getStuff(id);

//or - Get stuff new location

}

}

Tuesday, April 26, 2011

Optional Parameters in C#

C# does not have an implementation of optional parameters like those found in php, however you can simulate this feature using method overloading.

static int Add(int a, int b)
{
return Add(a, b, 0, 0);
}
 
static int Add(int a, int b, int c)
{
  return Add(a, b, c, 0);
}
 
static int Add(int a, int b, int c, int d)
{
  return (a + b + c + d);
}

What is the virtual keyword used for?

Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the Overridable keyword for this purpose.

When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.

public class Employee
{
public virtual void myfunction(float money) //This method may be overriden
{ Basic += money; }
}


public class Manager : Employee
{
public override void myfunction(float money) //This method is being overriden
{
float incentive = 10000;
base.SetSalary(money + incentive); //Calling base class method
}
}

Event sequence for Mastre Page-Content Page-User Control

Scenario 1:

Master page - Content page

Sequence of events

Content Page PreInit Event

Master Page Init Event

Content Page Init Event

Content Page Load Event

Master Page Load Event

If we are using master page and want to changes theme or decide which master page need to be load at runtime then we need to use Content page PreInit event.

Scenario 2:

Master page - Content page - Web user control on master page only.

Content Page PreInit Event

Master: UserControl Init Event

Master Page Init Event

Content Page Init Event

Content Page Load Event

Master Page Load Event

Master: UserControl Load Event

Scenario 3:

Master page - web user control on master page - Content page - Web user control on master page only.

Content Page PreInit Event

Content Page UserControl Init Event

Master:UserControl Init Event

Master Page Init Event

Content Page Init Event

Content Page Load Event

Master Page Load Event

Page:UserControl Load Event

Master:UserControl Load Event

PreRender - Page
PreRender - MasterPage
PreRender - UserControl

Unload - ChildUserControl
Unload - UserControl
Unload - MasterPage
Unload - Page

Conclusion :

1) PreInit for Content Page is first event

2) Init event sequence: UsercontrolàMaster PageàContent Page

3) Load event sequence: Content Page àMaster Pageà Usercontrol

4) Prerender event sequence is same as Load

5) Unload is exact reverse of load. Same as Init

UsercontrolàMaster PageàContent Page

6) Init and unload are same sequence

7) Load and prerender has same sequence

8) Webcontrol on content page has precedence over usercontrol in master page

Friday, August 13, 2010

Handle Fatal Error in SQL using DOT NET Try Catch block

Stored Procedure with fatal error

tempPK has one column with datatype = int
==============================================
CREATE PROCEDURE [dbo].[spError]
AS
BEGIN

Begin Tran
--Select 1/0

--execute('insert into tempPK select ''s''')
execute('insert into tempPK select ''fg''')
execute('insert into tempPK select 4')
Commit Tran
print 'Success'
END

======================================================
Dot Net Calling Method
try
{
SqlConnection sCon = new SqlConnection();
sCon.ConnectionString = "Database=xyz;Server=10.62;User Id=sa;Password=#12#";
sCon.Open();
SqlCommand sCom = new SqlCommand();
sCom.Connection = sCon;
sCom.CommandText = "Exec spError";
sCom.ExecuteNonQuery();
}
catch (Exception ex)
{
if(ex.Message.Substring(ex.Message.Length-7) == "Success")
MessageBox.Show("No Fatal Error");
else
MessageBox.Show("Fatal Error");
}
======================================================

Non Fatal Errors in SQL in DOT NET CATCH block

Stored Procedure having errors within
=======================
CREATE PROCEDURE spError
AS
BEGIN

Begin Tran
Select 1/0
execute('insert into te mpPK select 1')
execute('insert into tempPK select 3')
Commit Tran
END
GO
=======================
Application Code
try
{
SqlConnection sCon = new SqlConnection();
sCon.ConnectionString = "Database=xyz;Server=11.62;User Id=sa;Password=klk";
sCon.Open();
SqlCommand sCom = new SqlCommand();
sCom.Connection = sCon;
sCom.CommandText = "Exec spError";
sCom.ExecuteNonQuery();
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
=======================
Errors captured
Divide by zero error encountered.
Incorrect syntax near 'mpPK'.

Monday, August 9, 2010

Method Overloading

1) Class can not be declared as Private.

Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

namespace OOPS
{
private class A
{
}
}

By default it is Public

2) Method must have a return type
class A
{
public M()
{
}
}

3) Type 'OOPS.A' already defines a member called 'M' with the same parameter types

class A
{
public void M()
{
}
public void M()
{
}
}

4) True Method Overload
class A
{
public void M(int i)
{
}
public void M()
{
}
}

5) Type 'OOPS.A' already defines a member called 'M' with the same parameter types

class A
{
public void M()
{
}
public string M()
{
return "HI";
}
}

6) Method Overload

class A
{
public void M()
{
}
public string M(int i)
{
return "HI";
}
}





7) Method Overload
public void M(int i)
{
}
private string M()
{
return "HI";
}

8) Method Overload
class A
{
public void M(Int16 i)
{
}
public void M(Int32 i)
{
}
public void M(Int64 i)
{
}
}

9) Type 'OOPS.A' already defines a member called 'M' with the same parameter types

public void M(int i)
{
}
public void M(Int32 i)
{
}
10)Method Overload
class A
{
public void M(int i)
{
}
public void M(double i)
{
}
}

Conclusion: Access modifier and return type of function does not matter in Method Overloading. What matter is
1) Number of function parameters.
2) Datatype of parameters

If same parameters then overloading is not possible.

Sunday, July 25, 2010

Page Life Cycle

Life-Cycle Events


  • PreInit

  • Init

  • InitComplete

  • PreLoad

  • Load

  • Control events

  • LoadComplete

  • PreRender

  • PreRenderComplete

  • SaveStateComplete

  • Render



PreInit

Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
• Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
• Create or re-create dynamic controls.
• Set a master page dynamically.
• Set the Theme property dynamically.
• Read or set profile property values.
Note
If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init


Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.Use this event to read or initialize control properties.

InitComplete

Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad

Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load

The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Use the OnLoad event method to set properties in controls and to establish database connections.

Control events

Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
Note
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

LoadComplete

Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be loaded.

PreRender

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.
Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete

Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.

SaveStateComplete
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Unload
Raised for each control and then for the page.
In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
Note
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Wednesday, July 21, 2010

Generics

What is generic:

We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner. A perfect example of where we would need Generics is in dealing with collections of items (integers, strings, Orders etc.). We can create a generic collection than can handle any Type in a generic and Type-Safe manner. For example, we can have a single array class that we can use to store a list of Users or even a list of Products, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Products, and not as objects (with boxing/unboxing, casting).

Syntax:

GenericClass<T> = new GenericClass<T>()

Where T is the datatype that want to list, and GenericClass is the Generic Class which will wrap our desired datatype.

This Generic Class can be our own custom Generic Class or the ones provided by the .Net Framework.

Benefits of Generics:

1) Technically, T gets replaced by the datatype at compile type. And that's the reason why a compile time error occurs when casting is not done properly, it will be an InvalidCast Exception while using ArrayLists. Thus Generics enforce type checking at compile time only, making life less difficult
2) T is "replaced" by our datatype at comile time only so, no time and resources are wasted in boxing and unboxing the objects
3) Generics got rid of disadvantage of array list by avoiding the type casting.

With whom to use generics:

Stack (First in, Last out)
Queue (First In, First out)
List

Example:


public class Col<T> {
T t;
public T Val{get{return t;}set{t=value;}}
}

public class ColMain {
public static void Main() {
//create a string version of our generic class
Col<string> mystring = new Col<string>();
//set the value
mystring.Val = "hello";

//output that value
System.Console.WriteLine(mystring.Val);
//output the value's type
System.Console.WriteLine(mystring.Val.GetType());

//create another instance of our generic class, using a different type
Col<int> myint = new Col<int>();
//load the value
myint.Val = 5;
//output the value
System.Console.WriteLine(myint.Val);
//output the value's type
System.Console.WriteLine(myint.Val.GetType());

}
}

When we compile the two classes above and then run them, we will see the following output:

hello
System.String
5
System.Int32

Even though we used the same class to actually hold our string and int, it keeps their original type intact. That is, we are not going to and from a System.Object type just to hold them.

How to add data to an XML file using LINQ.

Load the XML file.
Specify where and what we want to add.
Save the changes to the XML file.

The method to add new data to the XML file is below.
private void addToXml()
{
XDocument xmlDoc = XDocument.Load("XYZ.xml");

xmlDoc.Element("Players").Add(new XElement("Player", new XElement("Name", txtName.Text),
new XElement("Team", txtTeam.Text), new XElement("Position",cmbPosition.SelectedItem.ToString())));
xmlDoc.Save("XYZ.xml");
}

LINQ with XML

XDocument xmlDoc = XDocument.Load(@"D:\2202_BO_1.xml");
var ACKZIP = from objACKZIP in xmlDoc.Descendants("ACKZIP").Descendants("tbl_DTFileCounter")
select new
{
ShopCode = objACKZIP.Element("ShopCode").Value.Trim(),
ReceiveZipFileCounter = objACKZIP.Element("SendZipFileCounter").Value.Trim(),
ZipFileName = objACKZIP.Element("ZipFileName").Value.Trim(),
ZipFileStatus = objACKZIP.Element("ZipFileStatus").Value.Trim(),
};
foreach (var obj in ACKZIP)
{
MessageBox.Show(obj.ShopCode);
MessageBox.Show(obj.ReceiveZipFileCounter);
MessageBox.Show(obj.ZipFileName);
MessageBox.Show(obj.ZipFileStatus);
}