Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Tuesday, September 22, 2009

How to find an element in c# Generic List

The following sample code demonstrates you how to find a matching element in the object list.

Let's say we have an object called Person with public properties PersonID, Name, Age, Gender as defined below.

using System.Collections.Generic.List;

public class Person
{
public int PersonID {get; set;}
public string Name {get; set;}
public int Age {get; set;}
public bool Gender {get; set;}
}

class program
{
public static void Main(string[] args)
{
// Let's say we have a method defined as dbAccess.GetPersons() to
//return all the records from Person table and populates the
//list object "persons" as shown below.
List persons = dbAccess.GetPersons();

int personIDToFind = 1234;
//Find person in persons list by PersonID using predicate
//"p=>p.PersonID == personIDToFind"
Person personByFindOperation = persons.Find( p=>p.PersonID == personIDToFind );

string personName = "Kiran"
//Find person in persons list by Name using predicate
//"p=>p.Name == personName"
Person personByFindOperation2 = persons.Find( p=>p.Name == personName );

}
}

Note: The Find method of List returns the first occurrence of the exact match within the entire System.Collections.Generic.List.


kick it on DotNetKicks.com
Shout it

Thursday, September 10, 2009

How to create a windows service in dot net framework

Windows service is an application which always runs in background. We can view all the installed windows services in ControlPanel/Administrativetools/Services. Sql server, Oracle, ... are the good examples of windows service.

Using visual studio it is very easy to create windows service. Please follow the below steps to create a windows service.
  1. Open visual studio and create a new project of template "Windows Service" as shown below
  2. After you click OK in the above step you will see a new solution named "WindowsService1" created as shown below.
  3. Right click on the above screen and click "Add Installer". This will create an installer component which helps us in installing this service.
  4. You can notice a new component "ProjectInstaller.cs" added and opened as shown below. It has 2 controls "ServiceProcessInstaller1" and "ServiceInstaller1".
  5. You can set whether this service is manual, automatic, or disabled by changing the StartType property of "ServiceInstaller1" (Right click -> Properties).
  6. Change the "ServiceProcessInstaller1"'s property "Account" to "LocalSystem"
  7. Right click on Service1.cs in solution explorer and click "View Code"
  8. In code you will see the service event handlers "OnStart", "OnStop".
  9. Write code that initiates a thread in OnStart event handler.
  10. Write code that stops execution of the thread in OnStop event handler.
  11. Please see below for sample code
  12. Build the solution. You have the windows service built ready.
  13. But until we install this service we cannot see it is running or not.
  14. To install this service you need to open the Visual Studio 2005/2008 Command prompt in Start->Visual Studio 2005/2008->Visual Studio Tools
  15. Run the command : InstallUtil.exe Windows_Service_EXE_Full_Path
  16. Here Windows_Service_EXE_Full_Path is the exe generated for the WindowsService1 project. Let's say the full path of the exe is C:/WindowsService1/Bin/Debug/WindowsService1.exe then our command to install it would be like this.
  17. InstallUtil.exe C:/WindowsService1/Bin/Debug/WindowsService1.exe
  18. If the above command is successful then you will notice a new service named "Service1" is shown in Control Panel->Administrative Tools/Services
  19. To uninstall a service, InstallUtil.exe -u C:/WindowsService1/Bin/Debug/WindowsService1.exe
  20. To make the life easier to install/uninstall windows services we can create a setup project which will let people easily install/uninstall with a wizard Please read this link. http://cherupally.blogspot.com/2009/09/how-to-create-setup-project-to-install.html

kick it on DotNetKicks.com
Shout it

Tuesday, June 16, 2009

Occasionally Connected Systems Sync Framework

Every one of us must have realized that there should be a system which allows us to work offline and online. Nowadays most of the people started using laptops and working remotely. So we got a need of a framework which lets the developers build applications to sync the offline changes with the server.

Fortunately Microsoft has released this kind of framework which is called Microsoft Sync Framework. This enables the developers to build applications with the ability to sync the files in file system, table records in the database between two machines.

For more details on microsoft sync framework please read the following.
  1. Sync Framework Overview
  2. Introduction to Occasionally Connected Database Synchronization
  3. Introduction to File Synchronization

kick it on DotNetKicks.com

Monday, May 11, 2009

Web page loading twice problem

We had a problem when working on a web project (C# ASP .Net). The problem was, the page was loading twice for every request made. This was happening only for GET requests. And it was working fine for POST requests. After doing a long research on it I found the issue why it was loading 2 times.

We had a master page with 2 images defined with empty (#) src attributes.

The exact code we had was

<img src='#' width='1000' height='392' alt='you need to install flash or turn on javascript' />

<img src='' width='1000' height='300' alt='' class='hide' />

The attribute src must be set other than empty or #. After fixing this we noticed that the page is loading only once.

Due to that bug all the pages which are using this master page were having the problem. After the fix every page worked fine with no issues.

For more details about this issue please check.

http://www.velocityreviews.com/forums/t21131-aspnet-page-load-twice-problem.html

Friday, May 1, 2009

Code to Serialize Object in C# .Net

Please use the below method if you want to serialize any object. This method returns you a string which is XML consists of all public properties and public data members of the object passed. It perfectly works for any type of reference type object.


String SerializeObject(Object obj)
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();

XmlSerializer xs = new XmlSerializer(obj.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

xs.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}

catch (Exception e)
{
System.Console.WriteLine(e);
return null;
}
}

Tuesday, April 28, 2009

How to sort list of objects in C#

The following code helps in sorting list of objects based on some property’s value.

public class Person
{
public int age;
public string name;

public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}

List people = new List();

people.Add(new Person(50, “Kiran”));
people.Add(new Person(30, “Raghava”));
people.Add(new Person(26, “Andrew”));
people.Add(new Person(24, “Praveen”));
people.Add(new Person(5, “Sudhir”));
people.Add(new Person(6, “Prudhvi”));

Console.WriteLine(”Unsorted list”);
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

Console.WriteLine(”Sorted list, by name”);
people.Sort(delegate(Person p1, Person p2) { return p1.name.CompareTo(p2.name); });
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

people.Sort(delegate(Person p1, Person p2) { return p1.age.CompareTo(p2.age); });
Console.WriteLine(”Sorted list, by age”);
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

How to invoke a process/application from parent application using C#

You can start a new process/application using the following C# code line.

System.Diagnostics.Process.Start(filePATH);

filePATH is the relative path of the application executable.

If you give a website url in filePATH then it will be opened in a default web browser.

Ex: System.Diagnostics.Process.Start(”http://rampgroup.com”); will cause to open the website home page in a default web browser.

Friday, April 24, 2009

Asp.Net Server.UrlEncode doesn't work if performed once

Hi,

I have found one interesting thing about UrlEncode when I was working on a project.

In many page requests we were passing sensitive query string parameters. As these were sensitive we were encrypting them using some encrypting algorithm. That algorithm was producing non numeric characters (Ex:'/', '&', '=','?',...) which are recognized by the web server. This was leading to conflicts by the web server and the application was breaking.

To Avoid this we started performing Server.UrlEncode on the encrypted string and using it in any url or querystring. On landing page we were doing Server.Decode and then decrypting the resulted string. Please see the blow code for better understanding.

Server.UrlEncode(Utility.Encrypt("sensitive data"));
Utility.Decrypt(Server.UrlDecode("url encoded and encrypted sensitive data"));

But this didn't help us. Even though we did url encoding we were not seeing the url encoded url in the browser. And due to this the application was breaking. After this we did a long research and tried all combinations but nothing helped.

Finally we got the solution. The solution is we need to perform the url encoding twice and url decoding once. That's how it was working perfectly. We changed the code accordingly in the entire project and we didn't see any issue. The final fix for this problem is shown below.

Server.UrlEncode(Server.UrlEncode(Utility.Encrypt("sensitive data"))); //Encode twice
Utility.Decrypt(Server.UrlDecode("url encoded and encrypted sensitive data")); //Decode once


Example:

....
.....
int CustomerID;
string CustomerIDEncrypyted = Utility.Encrypt(CustomerID.ToString());
string CustomerIDEncoded = Server.UrlEncode(Server.UrlEncode(CustomerIDEncrypyted));
string url = string.Format("Customer.aspx?CID={0}", CustomerIDEncoded );
anchorNext.Href = url;
.....
.....

//PageLoad event code in Customer.aspx.cs page

protected void Page_Load(object sender, EventArgs e)
{
string CustomerIDEncoded = Request.QueryString["CID"];
string CustomerIDDecoded = Server.Decode(CustomerIDEncoded);
string CustomerIDDecrypted = Utility.Decrypt(CustomerIDDecoded);
.....
.....
}
kick it on DotNetKicks.com