Friday, November 20, 2009

Asp.net Page Life Cycle

MSDN REFFERENCE:

Page Event

Typical Use

PreInit

Use this event for the following:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed.

  • Create or re-create dynamic controls.

  • Set a master page dynamically.

  • Set the Theme property dynamically.

  • Read or set profile property values.

    NoteNote:
    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. Use this event to read or initialize control properties.

InitComplete

Raised by the Page object. Use this event for processing tasks that require all initialization be complete.

PreLoad

Use this event if you need to perform processing on your page or control before the Load event.

Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Requestinstance.

Load

The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.

Use the OnLoad event method to set properties in controls and establish database connections.

Control events/Post back events

Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

NoteNote:
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

Use this event for tasks that require that all other controls on the page be loaded.

PreRender

Before this event occurs:

The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

SaveStateComplete

Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.

Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

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 Rendermethod that writes out the control's markup that is sent 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

This event occurs 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.

NoteNote:
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.

Although both Init and Load recursively occur on each control, they happen in reverse order.

The Init event (and also the Unload event) for each child control occur before the corresponding event is raised for its container (bottom-up: first child, then parent).

However the Load event for a container occurs before the Load events for its child controls (top-down).


Wednesday, November 18, 2009

Post and Pre Increment in C#

private static void PostAndPreIncrement() {
int i=1;
i=i++;
//(internal) In my words.
//1. var  original = i;
//2. var modified = i + 1;
//3. i = modified;
//4. return  original ;
//Result:::: i = 1
var k=i++;
//(internal) In my words.
//1. var  original = i;
//2. var modified = i + 1;
//3. i = modified;
//4. return  original ;
//Result::: k=1, i=2
var l=++i;
//(internal) In my words.
//1. var original = i;
//2. var modified = i + 1;
//3. i = modified;
//4. return modified;
//Result:::: l=3, i=3
}

Monday, November 9, 2009

Ado.net - CommainBuilder and DataAdaptor.

When creating a CommandBuilder a DataAdapter is passed as a parameter to the constructor. This links the CommandBuilder to a DataAdapter allowing it to read the SELECT command that has been associated with the DataAdapter. It will use the SELECT command to extract the schema information from the Table in the Database. Using this schema information it can automatically build INSERT, UPDATE and DELETE Command objects and the required SQL statements.

So, in terms of a program...

var adaptor=new OleDbDataAdapter("Select * from users", connection);
var dataSet=new DataSet();
adaptor.Fill(dataSet);
var cmdBuilder=new OleDbCommandBuilder(adaptor);
adaptor.UpdateCommand=cmdBuilder.GetUpdateCommand();

//ToDo: update dataset.
adaptor.Update(dataSet, "users");

Saturday, November 7, 2009

Encapsulation Vs Abstraction.

I have been confused about it plenty of times.

My words:
Abstraction is the concept of exposing only the required handles to the user, and hiding the undesired details. Eg: handle of gearbox, user only cares about the movement of the handle, and the number to which it points rest all is abstracted from the driver.

Encapsulation: it is binding the code and the data it manipulates into one reusable, real-life entity.
Eg: gearbox, it knows the intricacies needed to change the spears, chain etc on movement of the lever.

//Read it somewhere, but still not sure about it.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs. Abstraction solves the problem in the design side while encapsulation is the implementation.

Thursday, November 5, 2009

Comparing Reference Types in C#

This confuses me all the time, == Equals IEquatable ??
Found an interesting piece of code to help me remember that.

public class Point : IEquatable {
#region Implementation of equality
public bool Equals(Point other) {
if(ReferenceEquals(other, null))
return false;
// TODO Implement comparison logic here. E.g.:
// return X.Equals(other.X) && Y.Equals(other.Y);
throw new Exception("The method or operation is not implemented.");
}
public override bool Equals(object obj) {
return Equals(obj as Point);
}
public static bool operator ==(Point lhs, Point rhs) {
return ReferenceEquals(lhs, rhs)
!ReferenceEquals(lhs, null) && lhs.Equals(rhs);
}
public static bool operator !=(Point lhs, Point rhs) {
return !(lhs==rhs);
}
public override int GetHashCode() {
// TODO Implement comparison logic here. E.g.:
// return X.GetHashCode() ^ Y.GetHashCode();
throw new Exception("The method or operation is not implemented.");
}
#endregion
}


** Refer Effective C# Programming for better understanding.

Saturday, October 31, 2009

.net 3.5 Extension Methods, Its a syntactiv sugar.

Using extension methods and object oriented techniques, this is the best example i have come across.

public static void DoIt()
{
var someMeeting = Meeting.Between("jack").And("jill").At(8.OClock().Tommorrow());
}

Other than some basic Oops inheritance, what is used here is Extension methods which i would put here. So, in a way extension methods help in writing a more compact code (syntactic sugar) , which is not always possible using inheritance, polymorphism.


public static class Extensions
{
public static TimeSpan OClock(this int hour)
{
return new TimeSpan(hour, 0, 0);
}

public static DateTime Tommorrow(this TimeSpan time)
{
return new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, time.Hours, time.Minutes, time.Seconds);
}
}

Wednesday, October 28, 2009

Sending mails from C# with embedded images.

//Sample Code from MCTS 70-536 Kit

// Create the HTML message body
// Reference embedded images using the content ID

string htmlBody =
"[html][body][h1]Picture[/h1]img src=\"cid:Pic1\"][/body][/html]";

AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
// Create a LinkedResource object for each embedded image
LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg);
pic1.ContentId = "Pic1";
avHtml.LinkedResources.Add(pic1);
// Create an alternate view for unsupported client
sstring textBody ="You must use an e-mail client that supports HTML messages";
AlternateView avText = AlternateView.CreateAlternateViewFromString(textBody, null, MediaTypeNames.Text.Plain);
// Add the alternate views instead of using MailMessage.Body
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);
m.AlternateViews.Add(avText);
// Address and send the message
m.From = new MailAddress("lance@contoso.com", "Lance Tucker");
m.To.Add(new MailAddress("james@contoso.com", "James van Eaton"));
m.Subject = "A picture using alternate views";
SmtpClient client = new SmtpClient("smtp.contoso.com");
client.Send(m);

Monday, October 26, 2009

Difference between Trace and Debug - C#

The Trace class functions almost identically to the Debug class. However, calls to Trace are executed in both Debug and Release builds. Therefore, use the Debug class to writemessages only in the Debug build, and use the Trace class to write messages regardlessof the build type.

Passing arguments as 'ref' in C#.

What confuses me about passing a variable as reference (ref) is the concept of value types and reference types in C#.
Since, reference types are always passed by reference, why would we need to pass a reference type as 'ref' argument?

The difference is that passing an argument as 'ref' allows the method to change the reference also (memory address stored in the variable), which can not be done otherwise. A reference type allows the calling method to change the state of the instance (some fields), while passing an argument as 'ref' allows the calling method to assign a new instance to the variable.

Sample Code:

public class PlayWithRef {
public class Employee {
public string Name { get; set; }
public override string ToString() {
return Name;
}
}
public static void DoIt() {
var emp=new Employee{Name="Rina"};
ModifyMe(emp);
Console.WriteLine(emp);
ModifyMeAlso(ref emp);
Console.WriteLine(emp);
}
public static void ModifyMe(Employee str) {
str=new Employee { Name="NonRef Rina" };
}
public static void ModifyMeAlso(ref Employee str) {
str=new Employee{Name="Ref Rina"};
}
}

Essentially what happens is, passing an argument sends the heap memory address and the argument can access the instance lying in that address and can modify its instance/fields but can not make the original variable point to a new memory address, which is possible when the variable is send as 'ref'.

Tuesday, September 29, 2009

Git - Beginner

* Reverting a previous commit (not pushed on server).
1. git log
-- shows last 5/6commits with the commit id (which is needed to revert a given commit).
or - gitk, select your commit and look at "SHA1 ID".
2. git revert -n sha1 id

* To see history of a given file.
gitk filePath


Monday, September 28, 2009

Equality Comparisons in C#

Equality comparisons in C#:

  • == for simple value types or where use of operator overloads are desired
  • object.Equals(a,b) for most scenarios where the type is unknown or comparison has potentially been overridden
  • string.Equals(a,b,StringComparison) for comparing strings
  • object.ReferenceEquals(a,b) for identity comparisons, which are usually the fastest

Monday, January 12, 2009

MS Sql Server

//Modify Table column type
ALTER TABLE dbo.Investor4_head
alter column investorId varchar(32) not null;

//Drop index of table.
drop index tableName.IndexName

//Update Column values
UPDATE tableName
SET columnName = ''
WHERE columnName='-1'