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();
}
}
Explicit Member Implementation in C#
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
Interface
{
int CompareTo (object o);
{
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; }
}
{
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; }
}
}
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);
}
}
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; }
}
{
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; }
}
}
{
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; }
}
}
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();
}
}
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
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;
}
}
}
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; }
}
}
/// 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;
}
}
public void AddNewPerson(Person o)
{
oList.Add(o);
}
public void SortByAge()
{
CompareByName Comparer = new CompareByName();
oList.Sort(Comparer);
}
public void ReverseByAge()
{
oList.Reverse();
}
}
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
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"));
}