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

Wednesday, February 6, 2008

Using Keyword advantage in framework 2.0

The below code getting the employee details, but connection and command object declared in through using Keyword.one of the advantage of using keyword you no need to close the connection


using (SqlConnection myconn = new SqlConnection(connstring))
{
using (SqlCommand mycomm = new SqlCommand("select * from employee", myconn))
{
mycomm.CommandType = CommandType.StoredProcedure;
myconn.Open(); /////Here u opened the connection but no close
SqlDataReader myread;
myread = mycomm.ExecuteReader();
dt.Load(myread);
}
}
Note
This above code work only in C#

Friday, January 18, 2008

SqlCacheDependency using ASP.NET 2.0 and SQL Server 2005

SqlCacheDependency using Asp.net 2.0 and sqlserver 2005 is a beautiful thing :) Although getting SqlCacheDependency to work with SQL Server 2000 have to add some additional step.

Now we will go with Asp.net 2.0 with sqlserver 2005

Enable Service Broker


Before SqlCacheDependency will work with SQL Server 2005, you first have to enable Service Broker, which is reponsible for the notification services that let the web cache know a change has been made to the underlying database and that the item in the cache must be removed.
ALTER DATABASE Store SET ENABLE_BROKER;
GO

--SqlCacheDependency.Start() in Global.asax


In ASP.NET, you need to run SqlCacheDependency.Start(connectionString) in the Global.asax:

Example:


void Application_Start(object sender, EventArgs e)
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
SqlDependency.Start(connectionString);
}

SqlCacheDependency in ASP.NET 2.0 Example
Now you can just create your SqlCacheDependency as normal in your ASP.NET 2.0 page. Here is a simple example:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable categories = (DataTable)Cache.Get("Categories");
if (categories == null)
{
categories = GetCategories();
Label1.Text = System.DateTime.Now.ToString();
}
GridView1.DataSource = categories.DefaultView;
GridView1.DataBind();
}
private DataTable GetCategories()
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
DataTable categories = new DataTable();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID,Code,Title
FROM dbo.Categories", connection);
SqlCacheDependency dependency =
new SqlCacheDependency(command);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
categories = dataset.Tables[0];
Cache.Insert("Categories", categories, dependency);
}
return categories;
}
}

Wednesday, January 16, 2008

Scrapping using C#.Net

using System.net;
using System.io;

WebRequest request = WebRequest.Create("http://localhost:4733/strings.aspx");
WebResponse response = request.GetResponse();
Stream s=response.GetResponseStream();
StreamReader sr = new StreamReader(s);
string line = sr.ReadLine();
while ((line=sr.ReadLine()) !=null)
{
Response.Write(line);
}

Thursday, January 10, 2008

Moving Listitem from left Listbox to right Listbox

protected void btnmoveright_Click(object sender, EventArgs e)
{
ArrayList arrfirst = new ArrayList();
foreach (ListItem lstfirstitem in lstfirst.Items)
{

if (lstfirstitem.Selected == true)
{
arrfirst.Add(lstfirstitem);
}

}
for (int i = 0; i < arrfirst.Count; i++)
{
ListItem tst = (ListItem)arrfirst[i];
if (lstsecond.Items.Contains(tst) == false)
{ lstsecond.Items.Add(tst);
lstfirst.Items.Remove(tst);
}
}
}


protected void btnmoveleft_Click(object sender, EventArgs e)
{
lstfirst.SelectionMode = ListSelectionMode.Multiple;
lstfirst.Attributes.Add("SelectionMode", "Multiple");
ArrayList arrsecond= new ArrayList();
foreach (ListItem lstseconditem in lstsecond.Items)
{ if (lstseconditem.Selected == true)
{ arrsecond.Add(lstseconditem); }
} for (int i = 0; i < arrsecond.Count; i++)
{ ListItem tst = (ListItem)arrsecond[i];
if (lstfirst.Items.Contains(tst) == false)
{ lstfirst.Items.Add(tst);
lstsecond.Items.Remove(tst);
}
}
lstfirst.SelectedItem.Selected = false;
lstfirst.SelectionMode = ListSelectionMode.Single;
}

Friday, January 4, 2008

Encrypting Connection Strings in web.config file

http://www.beansoftware.com/ASP.NET-Tutorials/Encrypting-Connection-String.aspx

What is the purpose of AppendDataBoundItems for dropdown


AppendDataBoundItems

Definition:

Using this you can append dynamically.

Example

string[] sdss ={ "test", "test1" };
this.myDropDown.AppendDataBoundItems = true;
this.myDropDown.Items.Add(new ListItem("Bitte wählen...", ""));
this.myDropDown.DataSource = sdss;
this.myDropDown.DataBind();

output

Bitte wählen
test
test1


IDictionary

Hashtable ht = new Hashtable();
ht.Add(1, "bala");
ht.Add(2, "bala1");
IDictionary idic = (IDictionary)ht;
foreach (DictionaryEntry de in idic)
{
Response.Write(de.Key);
Response.Write(de.Value);
Response.Write("
");
}

out put

2bala1
1bala

IDictionaryEnumerator

Hashtable ht = new Hashtable();
ht.Add(1, "bala");
ht.Add(2, "bala1");
IDictionaryEnumerator ss = ht.GetEnumerator();
while (ss.MoveNext())
{
Response.Write(ss.Key);
Response.Write(" "+ss.Value);
Response.Write("
");
}

output:
2 bala1
1 bala

Inbuilt Interface Using Dotnet

1) IEnumerator


Definition:

Using this interface you can read the array,string, Performance is good.


Example:1

string[] sdss ={ "test", "test1" };

IEnumerator enumerator = sdss.GetEnumerator();
while (enumerator.MoveNext())
{
Response.Write(enumerator.Current.ToString() +"
");
}

output

test
test1

Example:2

string s="dd";
IEnumerator enumerator = s.GetEnumerator();
while (enumerator.MoveNext())
{
Response.Write(enumerator.Current.ToString() +"
");

}

output

d
d

Tuesday, January 1, 2008

Interop Services

Definition

>>handling unmanaged code we have to use Interop services.

The Microsoft .NET Framework promotes interaction with COM components,
COM+ services, external type libraries, and many operating system services. Data types, method signatures, and error-handling mechanisms vary between managed and unmanaged object models. To simplify interoperation between .NET Framework components and unmanaged code and to ease the migration path, the common language runtime conceals from both clients and servers the differences in these object models.
Code executing under the control of the runtime is called managed code. Conversely, code that runs outside the runtime is called unmanaged code.

Example of Unmanaged code

COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code.

Sunday, December 9, 2007

Friday, November 2, 2007

Tips for spliting string using C#

Spliting string using C#.netstring bala = "slfjslf/dfd";
bala.Split(new string[] { "slf" }, StringSplitOptions.None);

Thursday, October 18, 2007

Null-Coalescing Operator ( ?? )

If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“।


This can now be abbreviated as follows using the Null-Coalescing Operator:


string fileName = tempFileName ?? "Untitled";

The logic is the same। If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“.


The Null-Coalescing Operator comes up a lot with nullable types, particular when converting from a nullable type to its value type:

int? count = null;

int amount = count ?? default(int);

Since count is null, amount will now be the default value of an integer type ( zero )।


These Conditional and Null-Coalescing Operators aren't the most self-describing operators :),

but I do love programming in C#!

C# 2.0 Anonymous Methods

C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. This is akin to the best practice of keeping the declaration of a variable, for example, as close to the code that uses it.
Here is a simple example of using an anonymous method to find all the even integers from 1...10:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


int[] evenIntegers = Array.FindAll(_integers, delegate(int integer)
{
return (integer%2 == 0);
}
);

The Anonymous Method is:
delegate(int integer)
{
return (integer%2 == 0);
}

which is called for each integer in the array and returns either true or false depending on if the integer is even।


If you don't use an anonymous method, you will need to create a separate method as such:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, IsEven);
private bool IsEven(int integer)
{
return (integer%2 == 0);
}

When you have very simple methods like above that won't be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.
Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):
List citiesInFlorida =cities.FindAll(delegate(City city)
{
return city.State.Name.Equals(States.SelectedValue);
}
);

You can also use anonymous methods as such:
button1.Click +=
delegate
{
MessageBox.Show("Hello");
};

which for such a simple operation doesn't “deserve“ a separate method to handle the event.
Other uses of anonymous methods would be for asynchronous callback methods, etc.
Anonymous methods don't have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.

Wednesday, October 17, 2007

Using a Thread Pool in C# for Multiple Currency Conversion

.NET Classes used :
System.Collections.Generic.List
System.Threading.ManualResetEvent
System.Threading.Thread
System.Threading.ThreadPool
System.Threading.WaitHandle
System.Threading.ThreadStart

Introduction

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. This relieves the primary thread free to perform other tasks asynchronously. Thread pools are often employed in server kind of applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without locking up the primary thread or delaying the processing of subsequent requests in the queue. Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the overhead of creating a new thread for each task. Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available. It is easier to use the thread pool provided by the .NET Framework through the ThreadPool class as against creating a custom thread pool of our own.


Real World Example: Multi currency converter

Here is an example of multi currency conversion is simulated; which does processing of currency conversion. An exchange unit is modeled by a class called ExchangeUnit which carries the information of input & output currency and amount to be converted. Multiple objects of ExchangeUnit are created with different currency information and are fed into a ThreadPool for doing the multiple conversions. The ExchangeUnit class provides a method called ThreadPoolCallback that performs the conversion. An object representing each exchange required is created, and the ThreadPoolCallback method is passed to QueueUserWorkItem, which assigns an available thread in the pool to execute the method.
There is another class called MulticurrencyExchanger which maintains an internal list of latest conversion rates among the currencies. This list is periodically updated by a different thread which arrives at the percentage change in exchange rates based on a random number principle. In real world application latest exchange rates would be fed typically fed by a web service.
Here is the code for different classes:

using System;using System.Collections;using System.Collections.Generic;using System.Threading;using ClassLibrary;class Program{ static void Main(string[] args) { //Invoke the MulticurrencyExchanger Init() method on a separate thread MulticurrencyExchanger exchanger = new MulticurrencyExchanger(); Thread thread = new Thread(new ThreadStart(exchanger.Init)); thread.Start(); ExchangeUnit[] exchanges = new ExchangeUnit[3]; // One event is used for each ExchangeUnit object ManualResetEvent[] signalEvents = new ManualResetEvent[3]; for (int i = 0; i < 3; i++) { signalEvents[i] = new ManualResetEvent(false); } exchanges[0] = new ExchangeUnit(100.00, "USD", "RS", signalEvents[0]); exchanges[1] = new ExchangeUnit(100.00, "EURO", "RS", signalEvents[1]); exchanges[2] = new ExchangeUnit(100.00, "GBP", "RS", signalEvents[2]); // Calculate exchanges for 10 times so that fluctuating exchange rates reflect for (int j = 0; j < 10; j++) { // Launch threads for an ExchangeUnit using ThreadPool for (int i = 0; i < 3; i++) { ThreadPool.QueueUserWorkItem(exchanges[i].ThreadPoolCallback, exchanges[i]); } // Wait for all threads in pool WaitHandle.WaitAll(signalEvents); // Display the results for (int i = 0; i < 3; i++) { Console.WriteLine("{0} {1}={2} {3}", exchanges[i].CurrencyIn, exchanges[i].Amount, exchanges[i].CurrencyOut, exchanges[i].ExAmount); } // Sleep for 1 sec before going to next iteration Thread.Sleep(1000); } // Stop the thread for the MulticurrencyExchanger object thread.Abort(); Console.ReadLine(); }}

Tuesday, October 9, 2007

Output Parameters using C#

Definition:

if you want to return more than one value from method, You have to use out put parameters.

Example:
Public void site(out string site)
{
Site="bala";
}

public void showord()
{
string site;
site(out site);
Response.write("The site of the day is "+site);
}

Out put:

The site of the day is bala