Friday, January 8, 2010

How to add a new row in DataTable?

To add a new row in DataTable, we can use NewRow() method of the DataTable object.(Here assume that there are two columns Name, Address in the DataTable.

DataTable dTable = new DataTable();

DataRow row = null;



for (int i = 0; i < 5; i++)

{

row = dTable.NewRow ();

row["Name"] = i + " - Raja";

row["Address"] = "USA";

dTable.Rows.Add(row);

}

How to create a column in the DataTable

To create a column in the DataTable we can use the Columns.Add method of the DataTable object and pass DataColumn object as parameter.


DataTable dTable = new DataTable();

// create another column

DataColumn name = new DataColumn("Name", typeof(string));

dTable.Columns.Add(name);

How to add auto increment column in the DataTable?

To add auto increment column in the DataTable, we can set the AutoIncrement property of the DataColumn object as true and specify the seed value after adding that field into the DataTable object.

// create columns for the DataTable

DataTable dTable = new DataTable();

DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));

dTable.Columns.Add(auto);

// specify it as auto increment field

auto.AutoIncrement = true;

auto.AutoIncrementSeed = 1;

auto.ReadOnly = true;

What is the best way to add items from an Array into ArrayList?

Use AddRange method of the ArrayList.


string[] arr = new string[] { "ram", "shyam", "mohan" };

ArrayList arrList = new ArrayList();

arrList.AddRange(arr);

Write a single line of code to create a text file and write contents into it.

Use following code

System.IO.File.WriteAllText(@"c:\MyTextFile.txt", "MyContents");

Write a single line of code to read the entire content of the text file.

User following code

string strContent = System.IO.File.ReadAllText(Server.MapPath("~/MyTextFile.txt"));

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

How to Find Number of Days for provided date range?

Code extract :

TimeSpan DayDifference = Convert.ToDateTime("2009-1-7").Subtract(Convert.ToDateTime("2009-1-1"));


To find the difference of the days, here we have used Subtract method. The Subtract method does not take start date into consideration. Hence, to get the exact number of days for the date range we need to add one more day to the result.

Response.Write("Number of Days : " + DayDifference.Days+1);

What is the difference between a.Equals(b) and a == b?

For value types : “==” and Equals() works same way : Compare two objects by VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True

For reference types : both works differently :
“==” compares reference – returns true if and only if both references point to the SAME object while
"Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent
Example:
StringBuilder sb1 = new StringBuilder(“Mahesh”);
StringBuilder sb2 = new StringBuilder(“Mahesh”);
sb1 == sb2 > False
sb1.Equals(sb2) > True

But now look at following issue:
String s1 = “Mahesh”;
String s2 = “Mahesh”;
In above case the results will be,
s1 == s2 > True
s1.Equals(s2) > True
String is actually reference type : its a sequence of “Char” and its also immutable but as you saw above, it will behave like Value Types in this case.
Exceptions are always there ;)

Now another interesting case:
int i = 0;
byte b = 0;
i == b > True
i.Equals(b) > False
So, it means Equals method compare not only value but it compares TYPE also in Value Types.

Recommendation :
For value types: use “==”
For reference types: use Equals method.

Some interesting facts:

Why to prefer Equals method in especially VB.Net?
Consider following snippet:
Public Sub doSomething()
Dim s1 As String = “Mahesh”
Dim s2 As String = “Mahesh”
If s1 = s2 Then
MessageBox.Show(“Same!”)
End If
If s1.Equals(s1) Then
MessageBox.Show(“Not same!”)
End If
End Sub

Now if you will compile this stuff, and check generated IL code [Use ILDASM.exe ships with .Net Framework], you will find,
in doSomething section, “=” will create,
IL_0010: call int32 [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StringType::StrCmp(string,string,bool)

And, Equals method will create,
IL_0026: callvirt instance bool [mscorlib]System.String::Equals(string)

The second approach, using Equals uses mscorlib and its smaller and faster than the “=” because “=” uses VB.NET specific string comparison logic instead of core .Net implementation.
Single comparison operation may not give you performance hit but looping or at some critical part of you code, it can.
So Equals just give some efficient code.

More interesting thing that in C#, for the above code snippet, “==” and “Equals” both will result in same IL code. so no ambiguity in C#.
But if you used to code in both the language, then its obviously preferable to use Equals method.


/////////////////////////////////////////////////////////////////////////////////////

Both are used for comparison of variables, can be overloaded and return a Boolean value.

The differences are:-

Consider two variables of different types:
1) int a = 20;
string b = "20";

//Compiler error (== cannot be applied to int and string)
Console.WriteLine(a == b);

//output: False
Console.WriteLine(a.Equals(b));

2)int c = 455;
long f = 455;
//True
Console.WriteLine(c == f);
//False
Console.WriteLine(c.Equals(f));

//Equals strictly checks that 2 variables should be of the same type

// == gives True if 2 variables ' data types allow for similar values(Example: int and long)

3)List y = new List();
y.Add("one");
List z = new List();
z.Add("one");
Console.WriteLine(y == z);
Console.WriteLine(y.Equals(z));

Both will give False.

Thursday, January 7, 2010

Diff b/w custom control and user control

Custom controls are controls that are developed by the developer
or a third party vendor. Custom controls are not provided along with
.NET.

Difference between Custom Controls and User Controls.

1.User Control is a page file with extension .ascx which can only be used within
a single application. But custom controls are assemblies(dll files) that can be
used in multiple applications.

2.User Controls cannot be added to the ToolBox of VS.NET . To use a user Control with in an
aspx page u have to drag the user Control from the solution Explorer to designer page.
But Custom Controls can be added to ToolBox of VS.NET.

3.User Controls can be viewed as a sort of generic controls during the design time.
The proper GUI of user controls can be viewed only during the run time.
But Custom Controls can be viewed during the design time.

4. User controls are created from existing Webserver and html server controls .
But a developer who creates custom controls have to render every thing from the scratch.

5.Since the dll assembly of a custom control is being used,a custom control developed in C# can be used in a project developed in VB.NET or any other managed code and vice versa.
This is not possible with user controls.They are language spefic

We cannot give any examples for custom controls since they are developed either by a developer of a third party vendor.

Difference B/W Finalize() and Dispose() in .Net?

Both are ways to destroy the object. By object i mean when you have some unmanaged resources used in your class, you have to make sure that you write the logic to destroy them in the finalize() method. But this is the implicit way of destroying the unmanaged resources, as finalize is called by garbage collector when it find thats there is no reference to this object from the stack. There is an explicit way to destroy the unmanaged resources. That is by implementing IDisposable interface. By implementing this interface, ie you have to write the code to destroy the resource in Dispose() method, you can call the object to destroy itself when ever required in your code.when we write the destructor in c#,the runtime replaces the destructor with the finalize method in IL code,so we dont know at what time the destructor is called by the garbage collector.so the finalizer is non deterministic.if we want to do the garbage collection for unmanages resources,we have to implement our own destructor or finlizer method.but,the runtime will take two round trips to remove those objects from the heap.if runtime calls the own destructor,it will take onely one round trip. to remove the unmanaged resources without the performance issues,we have to inherit the System.Idisposable interface and implement the Dispose() method.here one problem is there,we have to write a code in a way that,the dsipose method must and should execute. for that reason we have to keep the dispose methos for the objcets in the finally block. problem with the dispose is that,some times because of some problmes dispose() methos may not execute. so the good practice is to use both to achieve the desied performance.

Tuesday, January 5, 2010

Show duplicate rows and delete duplicate rows

Show:
select customerid from tbl_customer group by customerid having count(customerid)>1
it will give u duplicate customerid in that particular table
Delete:
Here table name:tbl_places...columns:place
now add one identity column to this table
alter table tbl_places add I int identity
now delete
delete from tbl_places where I NOT IN(select min(i) from tbl_places group by place)

Using ROW_NUMBER() to paginate your data with SQL Server 2005 and ASP.NET

http://www.codeproject.com/KB/database/row_number.aspx

Parsing website using asp.net/C#

using System.Net;
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
string url = @"http://www.gmail.com";
HttpWebRequest reqObj = (HttpWebRequest)WebRequest.Create(url);
reqObj.Method = "GET";
HttpWebResponse resObj = (HttpWebResponse)reqObj.GetResponse();
StreamReader sr = new StreamReader(resObj.GetResponseStream());
string result = sr.ReadToEnd();
Response.Write(result);


}