Search This Blog

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, May 30, 2011

Debugging made easy - Part1

We will briefly discuss 3 things here -
1) Run to Cursor
2) Set Next Statement
3) Insert Tracepoint

1) Run to Cursor - While debugging, if you right click on any statement you can see many options. One of them is Run To Cursor.  It can be used as a one time breakpoint. Like when u want to execute a few rows in a go. You can right click on line where u want ur execution to come and select Run to cursor.

2) Set Next Statement - While debugging when you right click you see another option - Set Next Statement. This command jumps the program counter directly to the line under cursor. You can give a line above or below the current execution step. A major difference between Run to Cursor and Set Next statement is that the former executes all the statements till the point while the latter skips all the lines and directly executes next statement. Because of this behavior, we can take the control inside if-else or loop etc. I usually use it when I get a UE (Unexpected Error) and want to inspect where exactly it came from by setting the first statement of method as Next statement. You can see details at http://msdn.microsoft.com/en-us/library/09yze4a9(v=vs.85).aspx

3)  Insert Tracepoint - You can insert tracepoint as you insert breakpoints. The difference between both of them is that while a breakpoint breaks the execution flow, a trace point does a specified action and/or breaks the execution flow. Tracepoints can be used for the same purpose as Trace is used, without modifying the code, but they work only in "Debug" mode. For more details http://msdn.microsoft.com/en-us/library/232dxah7.aspx

Monday, September 13, 2010

Generics

Drawbacks of using non-generic

If you use an arraylist to create say an array of int and another array list to create an array of strings. What happens internally is that the array elements are converted into object. If they are value type they are converted using boxing, and they are retrieved using unboxing. This boxing, unboxing creates an overhead and degrades performance. The other limitation is lack of compile-time type checking; since an ArrayList casts everything to Object, there is no way at compile-time to check data types.

Using Generics
By using generics you can specify the type of the collection while creating its object itself. This allows the compiler to check whether the type of elements are correct at compile time only. Creating and using generics

They are in the namespace System.Collections.Generic;
Stack<int> myStk = new Stack<int>();
myStk.Push(1);
myStk.Push(2);
myStk.Push(3);
myStk.Push(4);

Push and Pop operations are available. Here is you try to push a string, like, myStk.Push("abc");, compiler will throw an error as myStk is an integer stack.

You can use stack.Pop method to pop the elements as given below:
while (myStk.Count>0)
{
    TextBox1.Text += myStk.Pop().ToString() + " ";
}

Apart from this Generics have Enumerator to iterate through the stack elements. The enumerator objects just iterates through the stack, without deleting the stack objects. Note:  After creating Enumerator object do not change the collection.
Stack<int>.Enumerator myEnum = myStk.GetEnumerator();
while (myEnum.MoveNext())
{
     TextBox1.Text += myEnum.Current.ToString() + "-";
}

Friday, September 10, 2010

Creating User Control

To create a user control. Right click on Project->Add New Item-> User Control. Name it, say, myUserControl

A page with .ascx extension is control. Use it to place your controls.

To add it to ur page. Go to your webpage and open it in design mode. Drag and drop the usercontrol on it. When you got to Source view you will see that a new <%Register ... %>  attribute is added to your code. And a new control is added like
<uc1:myUserControl ID="myUserControl1" runat="server" />

You can access it in code using its ID like other server controls.

To send data to user control from your page
TextBox txtuc1 = (TextBox)myUserControl1.FindControl("TextBox1");
txtuc1.Text = "I am user control";
 
To send data from user control to page
use Response.Redirect and pass data in querystring, just like you do redirect normally.

Creating a custom control

Go to Projects and click on Add new project = Select ASP.NET server Control and give it a name, say, myCustomControl

A class is created which inherits WebControl. Here u can write methods and set properties. Properties are set in ViewState as their value might get lost between postbacks otherwise.

public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
 
You can access the public properties and methods in ur project (will see later).
Now build this application, so a dll is available to u
 
To add custom control to Project
The dll of myCustomControl must be present in bin folder. (use addExistingItem)
Then u need to register the Custom Control like this
<%@ Register Assembly="myCustomControl" namespace="myCustomControl" TagPrefix="myCC"/>
 
To use the customcontrol in aspx
<myCC:ServerControl1 ID="CC1" runat="server" /> (you can specify height width etc
 
To use it in codebehind, just use like any other server control
CC1.Text or any other property or method.

Tuesday, August 3, 2010

How to use dispose.. using statement

After a lot of googling and referring books i got to learn a few things about dispose
1) only unmanaged resources need to be disposed.
2) SqlConnection, sqlCommand are unmanaged resources, however data adapter and dataset are managed resources.
3) when u dispose sqlconnection object, it also closes the connection. no need to write .close explicitly.
4) No need to open and close the connection if u r using dataadpter and datsets. it does it itself.
5) u need to implement the Idisposable interface in your class (where u need to use dispose). then u need to override the dispose method (see the code snippet below)... on class level define a variable disposed, as
private bool disposed = false;

there are two dispose methods. one accepts no parameter and one accepts a bool parameter. to dispose an object u need to call the dispose method which doesnot have any parameter.
this.dispose()
generally this statement is written in finally block to ensure it is always executed.
 u can use dispose method in follwing way :-
public void Dispose()
{
 this.Dispose(true);
GC.SuppressFinalize(this);
}
///<summary>
/// Free managed and/or unmanaged resources used in this Class.
/// </summary>
/// <param name="disposing">true signifies that the user called the dispose, false
/// signifies the GC triggered the dispose.</param>
///
private void Dispose(bool disposing)
{
 // Check we haven't already disposed.
 if (!this.disposed)
{
 // User triggered the cleanup so Dispose managed resources here.
 if (disposing)
{
this.Dispose();
 }
 // Dispose unmanaged resources here.
SqlConnection.dispose();
 }
this.disposed = true;
}
~Classdestructor()
{
 this.Dispose(false);
}
 
However, it creates a lot of mess in the code. If u just need to dispose the sqlconnection object you can easily use the using clause. I guess its only available in C#, please check if u r using VB.NET.
Example:-
 
public DataTable getData()
{
using (SqlConnection SqlCon = new SqlConnection(connectionString))
{
SqlCommand command= new SqlCommand("StoredProcedureName", SqlCon);
command.CommandType = CommandType.StoredProcedure;
///your code code

return dataTable
}
}
 
the using block ensures that the sqlconnection object is disposed properly once it goes out of it. And it makes he code easy to understand also :)

Monday, May 31, 2010

Some important regular expression validators

1) for only characters
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" ErrorMessage="Only characters are allowed"  ControlToValidate="txt" ValidationExpression="[A-Za-z]*$"/>

2) for only numbers
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only numbers are allowed" ControlToValidate="txt" ValidationExpression="^\d{0,}$"/>

3) for email ID
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Enter a valid EmailID" ControlToValidate="txtUserID"
ValidationExpression="^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$" />

4) for password
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtPassword" ValidationExpression="^([a-zA-Z0-9@*#]{6,15})$"
ErrorMessage="Your Password must be between 5 and 15 characters" />
 
5) for date
<asp:RegularExpressionValidator ID="RegularExpressionValidator18" runat="server" SetFocusOnError="true" Font-Size="XX-Small"
ErrorMessage="Enter a valid date" Display="Dynamic" ControlToValidate="txtDOB" ValidationExpression="([012][0-9]
3[01])/(0?[1-9]
1[012])/((19
20)\\d\\d)" />

6) for currency - it allows negative sign, and two digits past decimal
^[-]?([1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|\.[0-9]{1,2})$