Saturday, April 10, 2010

Delegates in .net

http://authors.aspalliance.com/quickstart/howto/

http://oakleafblog.blogspot.com/2008/01/linq-to-xml-grouping-and-aggregation.html

Calling functions through Delegates

class A
{
//Declared the Multicast Delegate(Void Return type)
public delegate void MyDelegate(int a,int b);
public static void Main(string[] args)
{
B b = new B();
MyDelegate Handler;
Handler = new MyDelegate(b.Add); //Added address of first function.
Handler += new MyDelegate(b.Subtract); //Added address of first function.

Handler(3, 4); //Calling functions.
Console.ReadLine();
}

}
class B
{
public void Add(int a, int b)
{
Console.WriteLine("Sum is:{0}",a + b);
}
public void Subtract(int a, int b)
{
Console.WriteLine("Difference is:{0}", Math.Abs(a - b));
}
}

This article will demonstrate how to handle them at runtime with an example.

using System;

using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace DelegateEventDemo
{

public delegate void AddEvent(object sender,EventArgs e);

class DelegateHandler
{

public event AddEvent OnAdditionToList;

public ArrayList al = new ArrayList();

public DelegateHandler()
{
// Registering the Changed method to event
OnAdditionToList += new AddEvent(Changed);
}

public void OnListChanged(EventArgs e)
{
// Publish the event : Listening
if (OnAdditionToList != null)
OnAdditionToList(this, e);
}

private void Changed(object sender,EventArgs e)
{
// Notify the user
Console.WriteLine("New element has been inserted into the list.");
}


public ArrayList Add(int num)
{
al.Add(num);
// Fier the event it on occure
OnListChanged(EventArgs.Empty);
return al;
}

public ArrayList Get()
{
return al;
}

}



class Program
{
static void Main(string[] args)
{
DelegateHandler dh = new DelegateHandler();

// Client side handling of event
dh.OnAdditionToList += new AddEvent(ClientFunction);

for (int i = 1; i <= 10; i++) dh.Add(i * 10);

ArrayList al = dh.Get();

for (int i = 0; i < style="mso-spacerun:yes">
Console.WriteLine(al[i].ToString());

Console.ReadLine();
}


public static void ClientFunction(object sender, EventArgs e)
{
Console.WriteLine("Client handler is called.");


}


}
}
 
 
 

Sometimes it is required that to access a click event of a master page button in content pages.Button present in master page is visible in every inherited child pages.But each child page needed to process some unique logic.

This is the code that defines the property in the Master Page for the Button ButtonMaster.

Code for C#:


In page Example.Master

In it's cs page set property
public Button ButtonClick
{
get{
return Button1;
}
}

In child pages
child.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//masterPage button click event defined in child pasge
Example mp = (Example)Page.Master;
mp.ButtonClick.Click += new EventHandler(ButtonTest_Click);


}

void ButtonTest_Click(object sender, EventArgs e)
{
//throw new System.Exception("The method or operation is not implemented.");
// put the logic here
}

 

This function will return the diffrence between two dates.



private double DateDiff(System.DateTime startDate, System.DateTime endDate)
{
double diff = 0;
System.TimeSpan TS = new System.TimeSpan(endDate.Ticks - startDate.Ticks);
diff = Convert.ToDouble(TS.TotalSeconds);

return diff;
}

 
 

How to return values from JavaScript function to the C# page load

Add the JavaScript function just below the HTML &LTtitle> tag.
This function should have __doPostBack to return value.

&LTscript language="javascript">

function RetVal()
{
var testVar = 'abc'
__doPostBack('Test',testVar);
}
Add a label to display the values from JavaScript function.



Add a text box to page and set the AutoPostBack property to true. One control with AutoPostBack property set to true is required in the page to get the value from JavaScript function using __doPostBack.

In Page_Load write the following code.
 
protected void Page_Load(object sender, EventArgs e)

{
if (IsPostBack)
{
string arg = Request.Form["__EVENTTARGET"];
string val = Request.Form["__EVENTARGUMENT"];
if (arg == "Test")
{
Label1.Text = val;
}
}
else
{
string script;
script = @"&LTSCRIPT language='javascript'> RetVal();" + "";
Page.RegisterStartupScript("Test", script);
}
}
"The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control."



The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server
 

Transaction in C#

using System;

using System.Data;
using System.Data.SqlClient;

class ExecuteTransaction
{
public static void Main()
{

SqlConnection mySqlConnection =new SqlConnection("Connection String");
mySqlConnection.Open();
SqlTransaction mySqlTransaction = mySqlConnection.BeginTransaction();
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.Transaction = mySqlTransaction;

mySqlCommand.CommandText =
"INSERT INTO City (" +
" ID, Name" +
") VALUES (" +
" 10, 'Bangalore'" +
")";

Console.WriteLine("Inserting First record is in process");
mySqlCommand.ExecuteNonQuery();

mySqlCommand.CommandText =
"INSERT INTO Country (" +
" ID, Name" +
") VALUES (" +
" 11, 'India'" +
")";

Console.WriteLine("Inserting Second record is in process");
mySqlCommand.ExecuteNonQuery();
Console.WriteLine("Committing transaction is in process");
try
{
mySqlTransaction.Commit();

}
catch (System.Data.SqlClient.SqlException ex)
{
mySqlTransaction.Rollback();
Console.WriteLine("TRANSACTION ROLLED BACK");
}
catch (System.Exception ex)
{
Console.WriteLine("System Error\n" + ex.Message);
}
finally
{
mySqlConnection.Close();
}

}
}
In the above code two records are inserted

one is city another one is country.
If all the two insert sucessfully, Transaction will commit
If any one of the two failed to insert, Transaction will rollback the remaing inserted record
It is very uesfull to add relation ship datas

No comments:

Post a Comment