For Answers, see/post comments

Explicit Member Implementation in C#

If a class implements two interfaces which contain a method with the same signature and the class itself is having a method with the same signature, then implementing that method to the class leads to error. Explicit implementation is used to resolve this case. It’s nothing but calling the interface method name in a fully qualified manner. Call the method along with the interface name.

using System;

interface IMyinterface1
{
void display();
}

interface IMyinterface2
{
void display();
}

class trial:IMyinterface1,IMyinterface2
//interface implemented
{
public void display()
//Method belongs to class trial
{
Console.WriteLine("Method from class trial");
}

void IMyinterface1.display()
//explicit member implementation
{
Console.WriteLine("Method from Interface - IMyinterface1");
}

void IMyinterface2.display()
//explicit member implementation
{
Console.WriteLine("Method from Interface - IMyinterface2");
}
}

class sample
{
public static void Main()
{
IMyinterface1 i1 = new trial();

//creating reference to interface
i1.display();

//calling interface method

IMyinterface2 i2 = new trial();
//creating reference to interface

i2.display();
//calling interface method

trial t = new trial();
t.display();
}
}

To to find date difference in C#

This code sample shows how to find the difference between two dates in C#

DateTime dt = Convert.ToDateTime("01/01/2008");
DateTime dt1 = Convert.ToDateTime("05/03/2008");
TimeSpan ts = dt.Subtract(dt1);int day = ts.Days;
textBox1.Text = day.ToString();

Binding Data to DropdownList

The Following sample shows the method of binding dropdownlist dynamically. Hee "Name" is the Text Field of the dropdownlist and "id" is the value Field.

Dim str As String = "data source=(local);" _
& "initial catalog=av;uid=sa;pwd=sa;"

Dim con As SqlConnection = New SqlConnection(str)
con.Open()
Dim ds As New DataSet
Dim da As SqlDataAdapter
Dim strSql As String = "Select * from tabTest"

da = New SqlDataAdapter(strSql, con)
da.Fill(ds)

// ddl is the name of the dropdown list.
ddl.Datasoucre = ds.Tables(0)
ddl.DataTextField = "Name"
ddl.DataValueField = "id"
ddl.DataBind()

Data Relation between Two Different Datasets

Create Two Datacolumn variable for relating Two Tables in two different Datasets. Suppose you are having two tables Emp and Salary. EmpID is common for both the tables . Then Write the following coding to relate those tables

DataColumn dcEEmpID, dcSEmpID;
dcEEmpID= ds1.Tables["Emp"].Columns["EmpID "];
dcSEmpID= ds2.Tables["Salary"].Columns["EmpID "];

// Create the relationship between the two columnsDataRelation relEmpSal;
relEmpSal= new DataRelation("CustomerOrders", dcEEmpID, dcSEmpID);

How to filter the datatable

We Often use to come across the situation where we use to filter the data with some condition, here i have taken a products table from northwind database and now i want to show all the products name which come under cateogory 1(Beverages)

SqlConnection myConn = new SqlConnection(strConString);

string strSql = "select * from Products";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strSql, myConn);
da.Fill(ds);
DataTable dt = ds.Tables[0];

// The following line filters the data by "CategoryId = 1" and returns an array of DataRowDataRow[] dRow = dt.Select("CategoryId=1");

for (int i = 0; i <>
{
Response.Write("Row " + dRow[i]["ProductName"].ToString());
}

Remove duplicate records from a table

This code sample shows how to identify and remove duplicate records from a dataset/datatable.Following Code will take inputs datatable and column name wherein we need to find duplicates items and remove

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{

Hashtable hTable = new Hashtable();

ArrayList duplicateList = new ArrayList();
//Add list of all the unique item value to hashtable, which stores combination of key, value pair.
//And add duplicate item value in arraylist.

foreach (DataRow drow in dTable.Rows)
{

if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
}

//Removing a list of duplicate items from datatable.

foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);
//Datatable which contains unique records will be return as output.
return dTable;
}

Example showing how to use above method:

protected void Button1_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); SqlConnection conn = new SqlConnection(strConn);

SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();

da.Fill(ds, "Emp");

// Filling a employee table
DataTable dt = ds.Tables["Emp"];
dt = RemoveDuplicateRows(dt, "empname");
GridView1.DataSource = ds.Tables["Emp"].DefaultView;
GridView1.DataBind();
}

Serialize a Remotable Dataset

The following code defines the format for the dataset when required for remoting purposes. On serializing the remotable dataset to a binary file, you could see the difference.

FileStream fs = new FileStream(@"c:\authordata.txt", FileMode.Create);
pubsDataSet.RemotingFormat = SerializationFormat.Binary;
// Remove the above line, and serialize the dataset; Check the file content.
BinaryFormatter bfo = new BinaryFormatter();
bfo.Serialize(fs, pubsDataSet);
fs.Close();

Create a Generic Colletion to store objects in VB.Net

The code will represent a user defined collections for storing objects and retriving objects from the Collection and to manipulate it.For example you can have the collection of class objects in this collection.This collection can be iterated using For Each.

Public Class GenericCollection
Implements IEnumerable, IEnumerator
Dim arr As New ArrayList

Public Function GetEnumerator()
As System.Collections.IEnumerator
Implements System.Collections.IEnumerable.GetEnumerator
Return arr.GetEnumerator()
End Function


Public ReadOnly Property Current() As Object
Implements System.Collections.IEnumerator.Current
Get
Return arr.GetEnumerator.Current()
End Get
End Property

Public Function MoveNext() As Boolean
Implements System.Collections.IEnumerator.MoveNext
GetEnumerator.MoveNext()
End Function

Public Sub Reset() Implements System.Collections.IEnumerator.Reset
arr.Clear()
End Sub

Public Sub Add(ByVal obj As object)
arr.Add(obj)
End Sub

Public Function Count() As Integer
Return arr.Count
End Function

Public Function RemoveAt(ByVal Index As Integer)
arr.RemoveAt(index)
End Function

Public Function Remove(ByVal obj As object)
arr.Remove(obj)
End Function

Public Function Item(ByVal Index As Integer) As object
Return arr.Item(Index)
End Function
End Class

How to get the available RAM and the CPU usage?

These methods are very usefull in order to monitor the system and particulary the amount of the available RAM in MB (MegaBytes) and the cpu usage in percents.

protected PerformanceCounter cpuCounter;
protected PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
/* Call this method every time you need to know the current cpu usage. */

public string getCurrentCpuUsage()
{
cpuCounter.NextValue()+"%";
}

/* Call this method every time you need to get the amount of the available RAM in Mb */

public string getAvailableRAM()
{
ramCounter.NextValue()+"Mb";
}

How to find out the nth highest number in a database column

You can use this stored procedure to find the nth highest number in a database column. For example, if you want to find the second largest number, pass 2 as the value for the parameter 'nth'.


CREATE PROC nth (
@table_name sysname,
@column_name sysname,
@nth int
)
AS
BEGIN
--Purpose: To find out the nth highest number in a column. Eg: Second highest salary from the salaries table

--Input parameters: Table name, Column name, and the nth position
SET @table_name = RTRIM(@table_name)
SET @column_name = RTRIM(@column_name)
DECLARE @exec_str CHAR(400)
IF (SELECT OBJECT_ID(@table_name,'U')) IS NULL
BEGIN
RAISERROR('Invalid table name',18,1)
RETURN -1
END
IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name AND COLUMN_NAME = @column_name)
BEGIN
RAISERROR('Invalid column name',18,1)
RETURN -1
END
IF @nth <= 0
BEGIN
RAISERROR('nth highest number should be greater than Zero',18,1)
RETURN -1
END
SET @exec_str = 'SELECT MAX(' + @column_name + ') from ' + @table_name + ' WHERE ' + @column_name + ' NOT IN ( SELECT TOP ' + LTRIM(STR(@nth - 1)) + ' ' + @column_name + ' FROM ' + @table_name + ' ORDER BY ' + @column_name + ' DESC )'
EXEC (@exec_str)
END

Delete a record from the database

This function will delete the record based on your delete condition and table from which the data has to be deleted. It will return 0 or 1 based on the output.


Public Function DeleteRecords(ByVal TableName As String, ByVal DeleteAndSelectCondition As String) As Integer
Dim oCon As New OleDbConnection(mConnectionString)
Dim sSQL As String, i As Integer
sSQL = "delete from " & TableName & " where " & DeleteAndSelectCondition
Try
oCon.Open()
Dim oCmd As New OleDbCommand(sSQL, oCon)
i = oCmd.ExecuteNonQuery()
If ContextUtil.IsInTransaction = True Then ContextUtil.SetComplete()
oCon.Close()
Return i
Catch e As Exception
If ContextUtil.IsInTransaction = True Then ContextUtil.SetAbort()
Throw New Exception(e.Message & vbNewLine & e.Source & ":-DeleteRecords")
End Try
End Function

How to select second max from Database Table in SQL Server

SELECT * FROM Student_infowhere S_id=(select max(S_id)from Student_info where S_id<(select max(S_id)from Student_info))

How to call a stored procedure from C#

private void button1_Click(object sender, System.EventArgs e) {
SqlConnection conn = new SqlConnection("Data Source=localhost;Database=Test;Integrated Security=SSPI");
//string jn="SELECT Student_info.FName,Login.User1 FROM Student_info INNER JOIN Login ON Student_info.FName=Login.User1";
SqlCommand command = new SqlCommand("t", conn);
// t: Stored procedure. command.CommandType=CommandType.StoredProcedure;
// command.Parameters.Add("@User1", SqlDbType.VarChar).Value =textBox1.Text;
command.CommandText="t";
conn.Open();
DataSet ds=new DataSet();
DataTable myTable=ds.Tables.Add("Login");
SqlDataAdapter dt=new SqlDataAdapter(command.CommandText,conn); dt.Fill(ds,"login");
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
string s=reader[0].ToString().Trim()+""+reader[1].ToString().Trim();
MessageBox.Show(s);
}
conn.Close();
}
}

Error Handling

Hi All,
I am running in to a problem with a text box on my page. I have ValidateRequest="true" on my page, which obviously means the page craps out when they enter invalid characters. This is good, but I'd like to trap this error and present a message to the user saying they have entered invalid characters, otherwise I follow my usual error flow and go to the custom error page. Is there a simple way to do this? I am using a method on my code behind which I grabbed somewhere else and the method is being hit. Apologies as I can't remember what site I grabbed this from, but it is only for test purposes:

Protected Overrides Sub OnError(ByVal e As EventArgs)
' At this point we have information about the error
Dim ctx As HttpContext = HttpContext.Current
Dim exception As Exception = ctx.Server.GetLastError
Dim errorInfo As String = ("
Offending URL: "
_
+ (ctx.Request.Url.ToString + ("
Source: "
_
+ (exception.Source + ("
Message: "
_
+ (exception.Message + ("
Stack trace: "
+ exception.StackTrace)))))))
exception.
ctx.Response.Write(errorInfo)
' --------------------------------------------------
' To let the page finish running we clear the error
' --------------------------------------------------

ctx.Server.ClearError()
MyBase.OnError(e)
End Sub

This method gets hit when the error arises and I'm just spitting it out to the page right now. My question is whether or not there is a way to trap the specific error I am looking for and otherwise throw it up to be handled as a regular error. Is there a specific error number I can access? Or maybe I'm way off track and there is a simpler way of handling this. Please let me know any feedback you have.

Thanks

Object not set

Hi,
Error: Object reference not set to an instance of an object.
referring to:
command.Parameters.AddWithValue("@A", Z.Text);
what causes this?
Thanks,

variable losing value on postback

I'm sure this is an easy question, but I need some help...

I have a variable, level, that starts out with a value of 1. After clicking a button, I need it to increase by one. Here's a code snippet:

private int _level;
public int Level
{
get
{
return _level;
}
set
{
_level = value;
}
}

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
Level = 1; //SET INITIAL VALUE OF LEVEL TO 1
}
}

protected void btnSubmit_Click(object sender, System.EventArgs e)
{
Level += 1; //THE VALUE HERE IS RESET BACK TO 0
}

Any help you can provide is greatly appreciated.

Thank you,

Using IComparable and IComparer to compare objects

Introduction
The .Net framework and especially the System.Collection namespace provides us two built in interfaces witch are IComparable and IComparer interfaces. The first one, namely, the IComparable specifies a behavior that allows an object to be compared to another one from the same type according to a specified member value such as a hash table value or so. At the other hand, IComparer interface enables us to compare two objects at once at the opposite of the first one witch enables us to compare two objects one by one. The IComparable and the IComparer could also be found as a part of the System.Collection. Generic built in interfaces, thing that renders the deal more comfortable when using them since the conversion exceptions headache will be neutralized and avoided with generic types.
In this article I will try to provide some techniques according to the effective use of the IComparable and the IComparer interfaces in a development context and I will expose some real use cases to know how, and under witch condition may one use each of both interfaces.
IComparable interface
Interface
{
int CompareTo (object o);
}
The IComparable interface has CompareTo (object o) as a member. This last one is used to compare two objects one by one profiting of the extreme polymorphism nature of the interface. Say, that we have a type person and you want to compare two objects from this type according to their ages for example. It will be more practical to implement the IComparable interface within the person class core.
public class Person : IComparable
{
public Person() { }
// private fields
private string _FirstName;
private string _LastName;
private int _Age;
public Person(string FirstName, string LastName, int Age)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
//Properties
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
//This was the interface member
public int CompareTo(object obj)
{
Person Temp = (Person)obj;
if (this.Age <> Temp.Age)
{ return -1; }
else
{ return 0; }
}
}
The method int CompareTo (object obj) returns an integer. You can specify your result according to the returned value as follow:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
Person me = new Person("Bejaoui", "Bechir", 29);
Person myFather = new Person("Bejaoui", "Massinissa", 65);
Person myGrandFather = new Person("Krayem", "Shishaq", 95);
int state = me.CompareTo(myFather);
if (state == 1) Console.WriteLine("My father is older than me");
if (state == -1) Console.WriteLine("I'm older than my father!!!");
if (state == 0) Console.WriteLine("My Father and I have the same age!");
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
When the generics come into the world as a part of the .Net 2.0 innovations, the code structure becomes more robust as the problem that may raise a casting exception is avoided in this case. So the person class code structure will be as following:
public class Person : IComparable
{
public Person() { }
// private fields
private string _FirstName;
private string _LastName;
private int _Age;
public Person(string FirstName, string LastName, int Age)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
//Properties
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
//This was the interface member
public int CompareTo(Person obj)
{
Person Temp = obj;
if (this.Age <> Temp.Age)
return -1; }
else
{ return 0; }
}
}
You can observe that the argument that overloads the CompareTo is a type of person rather than object now. With this manner the casting operation is avoided and the risk of receiving a compile or a run time errors are minimized. But let us be more practical as this example is demystifying the fact of profiting of the real IComparable interface services. I explain by giving a real example. The array type implements the IComparable interface in order to sort its objects collection and even the array list do the same thing to sort its objects collection internally. Say that I want to build my own objects container type. For this, I build a new type called Room witch plays the role of person objects container.
The class person will be presented as follow:
public class Person
{
public Person() { }
// private fields
private string _FirstName;
private string _LastName;
private int _Age;
public Person(string FirstName, string LastName, int Age)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
//Properties
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
}
The class Room witch plays the container role is designed as bellow:
public class Room
{
protected ArrayList oList;
public Room()
{
oList = new ArrayList();
}
//Indexer
public Person this[int index]
{
get { return (Person)oList[index]; }
set { oList[index] = value; }
}
//Properties
public int Count
{
get { return oList.Count; }
}
//Methods
public void AddNewPerson(Person o)
{
oList.Add(o);
}
public void SortByAge()
{
oList.Sort();
}
public void ReverseByAge()
{
oList.Reverse();
}
}
When I try to run this program:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
Person me = new Person("Bejaoui","Bechir",29);
Person myFather = new Person("Bejaoui","Massinissa",65);
Person myGrandFather = new Person("Bejaoui","Shishaq",95);
//Add some persons to the room
Room LivingRoom = new Room();
LivingRoom.AddNewPerson(me);
LivingRoom.AddNewPerson(myFather);
LivingRoom.AddNewPerson(myGrandFather);
LivingRoom.SortByAge();
for(int i = 0; i
I receive a real time error that indicates that the sorting operation is failed and the cause here is that the person type doesn't implement the IComparable interface. In order to render the sorting operation realizable, the IComparable interface has to be implemented first. Try now to implement the person type as follow:
public class Person : IComparable
{
public Person() { }
// private fields
private string _FirstName;
private string _LastName;
private int _Age;
public Person(string FirstName, string LastName, int Age)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
//Properties
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
//Interface method
public int CompareTo(object o)
{
Person Temp = (Person)o;
if (this.Age <> Temp.Age)
{
return -1;
}
else
{
return 0;
}
}
}
Now, try to run the program and you will not receive this run time error again. Well, the fact is that this interface method enables the object to be compared to other instances of its own type.IComparer interfaceAt the other hand, the IComparer interface is used to compare two objects issued from the same type and at the same time, consequently, it doesn't be implemented within the type going to be compared. It is implemented within a separate type that has as a mission to compare a couple of objects. Let us turn back to our previous example and try to use the IComparer instead of the IComparable interface to sort objects within the room container.Given this design of person type:
public class Person
{
public Person() { }
// private fields
private string _FirstName;
private string _LastName;
private int _Age;
public Person(string FirstName, string LastName, int Age)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
//Properties
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
}
Say that we want to sort objects person by name now. First we ought to define a kind for comparer object that implements the IComparer interface:
///
/// CompareByName is an object that enables us compare
/// two person objects, it implements the IComprer interface.
///

public class CompareByName : IComparer
{
public CompareByName() { }
//Implementing the Compare method
public int Compare(object object1, object object2)
{
Person Temp1 = (Person)object1;
Person Temp2 = (Person)object2;
return string.Compare(Temp1.FirstName, Temp2.FirstName);
}
}Then we implement the Room container as follow:
public class Room
{
protected ArrayList oList;
public Room()
{
oList = new ArrayList();
}
//Indexer
public Person this[int index]
{
get
{
return (Person)oList[index];
}
set
{
oList[index] = value;
}
}
//Properties
public int Count
{
get
{
return oList.Count;
}
}
//Methods
public void AddNewPerson(Person o)
{
oList.Add(o);
}
public void SortByAge()
{
CompareByName Comparer = new CompareByName();
oList.Sort(Comparer);
}
public void ReverseByAge()
{
oList.Reverse();
}
}
As you observe, I instantiate an CompareByName object witch serves as an argument to overload the oList.Sort method and that enables the Room container to compare the person objects collection twice by twice internally.

Treeview

Hi,
Can anyone suggest me, how to work with treeview in C#.net, it must hold 3 table values.
Parent Node,Child Node, GrandChild Node.
Tables like
>ParentTable
>ChildTable
>GrandChildTable.

Get user control from existing .net application

Ok, I thought this was crazy at first, but I have found stuff on the internet and I can take a user control compiled in a dll and have it show up on a webpage. That was great but what I really need to do is take a control from my exisiting application (complied as exe) and have it show up on a webpage. I was thinking about trying to put some public GetControl method but then I wasn't sure how I could actually call it from another dll or from my webpage directly.
So if I am going the wrong way all together the please let me know. I am up for anything. My story is, I have a control which is in my main application (but not compilied on its own dll) which I would like to "shadow" onto a webpage. This control re-paints every few times a second to appear like a moving graph; which I would need to look the same over the webpage. The other thing I notice with just putting an object node in my htm page is it instainates a new user control on load. I would need the usercontrol to be the same one of my applications because there is a lot of data getting happening which I wouldn't want to re-implement.
My application also uses spring to build the application. I started to do some research and I think spring might be able to help me with this problem too but I am not knowledgable in spring.
Please help or give any suggestions.

Enable CLR Debugging

1) Open Server Explorer.
2) In Server Explorer, right-click on the connection you want to debug and choose Allow SQL CLR Debugging. This setting enables SQL CLR debugging for all connections on the server.
3) A message box appears with the warning: "SQL CLR debugging will cause all managed threads on the server to stop. Do you want to continue?". When you are debugging SQL CLR database objects, breaking execution will break all threads on the server, affecting other users. For this reason, you should not debug SQL CLR applications on a production server.
4) Click Yes to enable debugging.

Convert Database data to XML

The data existing in the relational database can be easily converted into an xml documant in the program. The following code illustrates this.

I have used SQLServer database table employee ( with columns empid, first_name,last_name,deptcd,salary and resig_status) The connection is established using appropriate connection string. The data from the RDBMS table is stored in the dataset dsEmp. The xml class XmlDataDocument is used to convert the data into an xml data file. It takes the

dataset as input and converts to xml data.
{
DataSet dsEmp = new DataSet();
string strCon;
string strSelect;
strCon = "data source=SQLEXPRESS;initial catalog=dbemp;persist security info" +"=False;user id=sa;password=jadoogar;workstation id=HCL;packet size =4096";strSelect = "Select empid,first_name,deptcd from employee";

try{
SqlConnection sqlCon = new SqlConnection(strCon);
SqlDataAdapter empAdapter = new SqlDataAdapter(strSelect,sqlCon);
empAdapter.Fill(dsEmp,"employee");
}
catch
{
}

XmlDataDocument empDoc = new XmlDataDocument(dsEmp);
empDoc.Save(MapPath("xmldata/newemp.xml"));
}