Finally, I've started to publish some training videos about C# and ASP .NET.
In first video I will explain how to call a method with asynchronous delegates.
C# Tuning Training Videos - Asynchronous Method Calling - Part 1
Friday, June 13, 2008
C# Tuning Training Videos - Async Method Calling - Part One
Thursday, April 24, 2008
Simple Windows Explorer by C#
Please let me know if there any error or question within this sample.
Download
Tuesday, November 20, 2007
Visual Studio 2008 and .NET 3.5 Released
Today Microsoft shipped Visual Studio 2008 and .NET 3.5.
You can download the final release using one of the links below:
If you are a MSDN subscriber, you can download your copy from the MSDN subscription site (note: some of the builds are just finishing being uploaded now - so check back later during the day if you don't see it yet).
If you are a non-MSDN subscriber, you can download a 90-day free trial edition of Visual Studio 2008 Team Suite here. A 90-day trial edition of Visual Studio 2008 Professional (which will be a slightly smaller download) will be available next week. A 90-day free trial edition of Team Foundation Server can also be downloaded here.
If you want to use the free Visual Studio 2008 Express editions (which are much smaller and totally free), you can download them here.
If you want to just install the .NET Framework 3.5 runtime, you can download it here.
Saturday, September 8, 2007
Detecting is current user an Administrator
In some cases in your windows application you may want to know is the current user a member of Aministrators group or not?
To detect this you can get an object of WindowsIdentity like this:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
Then create an instance of WindowsPrincipan by :
WindowsPrincipal principal = new WindowsPrincipal(identity);
and finally check it by using IsInRole() method like this:
string role = "BUILTIN\\Administrators";
bool IsAdmin = principal.IsInRole(role));
then you can use the IsAdmin variable to determine whether the current user is an Admin or not.
Wednesday, September 5, 2007
Remoting in C#
While you are developing distributed application by csharp, you might need to have communication between objects that run in different processes.
.NET remoting enables client applications to use objects in other processes on the same computer or on any other computer available on its network.(MSDN)
Each remoting application consist of three part:
A remotable object.
A host application domain to listen for requests for that object.
A client application domain that makes requests for that object.
- Marshal-by-value objects are either inherited from ISerializable interface or using a Serializable attribute, which are copied and passed from the application domain.
- Marshal-by-reference objects are the objects from a class which is inherited from MarshalByRefObject class.
Part 1: Remotable Types
In my first post about remoting I will create a class named "MyRemotableType" which is a Marshal-by-reference type, and I will put this class into a class library with name MyRemotableTypes.dll.
public class MyRemotableType:MarshalByRefObject
{
public MyRemotableType()
{
Console.WriteLine("A New MarshalByRefObject created");
}
public void AddNumbers(int a,int b)
{
Console.WriteLine("Sum is : {0}",a+b);
}
public string CaldSum(int a,int b)
{
return string.Format("Sum is: {0}", a + b);
}
}
Notice that Marshal-by-reference objects needs to be activated. Activation for Marshal-by-reference objects has two types:
- Server activation: which means that objects will be created by server at the first method call, but not when the object is initializing by calling new keyword.
- Client activation: which means that objects will be created by server when the client calls the new keyword.
- Singleton: It means that there will always be only one instance, regardless of how many clients there are for that object, and which have a default lifetime.
- SingleCall: It means that the system creates a new object for each client method invocation.
Now I need another application which will listen to request from clients. In this sample I 'm going to create a console application. First I have to add a reference to System.RunTime.Remoting. Then I have to prepare a communication line between clients and server. To do this you can use a TCP or HTTP channel. Like this:
HttpChannel channel = new HttpChannel(1234);
ChannelServices.RegisterChannel(channel);
Then you have register the remotable types you want to prepare. As I said before you can choose with activation you want to use. If you want to have Server Activation use this line of code:
RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyRemotableType),"RemotingTest.soap", WellKnownObjectMode.Singleton);
Console.WriteLine("Remote server started ...\r\nPress enter to stop");
Console.ReadLine();
Notice that in line above I used the Singleton but you can change it to SingleCall, also.You can also use RegisterActivatedServiceType . Notice that here in server application I used ReigsterXXXXServicesType
but in the client side you have to use RegisterXXXXClientType. And I also passed a name for this channel " RemotingTest.soap", this name is used to find the remote channel.
Part 3: Client Application
Now I want to use MyRemotableType and create instance from that but as a remote object. To do this first I add a reference to my MyRemotableTypes.dll. The I have to set the channel in my client application. I do this by using the RegisterWellKnownClientType method of RemotingConfiguration, as I said before.
RemotingConfiguration.RegisterWellKnownClientType(typeof(MyRemotableType),"http://RemoteServerName/RemotingTest.soap");
But notice that you give the type you want to use by remoting and also the url of remote server as parameters.
Now try to create some objects from the MyRemotableType.
MyRemotableType t = new MyRemotableType();
t.AddNumbers(10,10);
Console.WriteLine(t.CaldSum(10,10));
Part 4: Test the Applications
Now for testing the application, first run the Server Application,then while the server is running start the client application. And see the result.
As you may see, you will get just one line printed in client :
Sum is: 20
But in server side you got two printed line:
A New MarshalByRefObject created
ُS um is: 20
It means that you the object is created on server and the first method call is Writing to Console of server, but the result of method is accessible in client.
It will discuss more about remoting in my next posts.
You can download the sample code at:
http://www.tabatabaei.info/csharpsamples/firstremoting.rar
Tuesday, September 4, 2007
C# Copy Semantics
Let 's talk about Copy Semantics a little bit in C# Tuning
There is three type of object copy in C#.
- Reference copy
- Shallow copy
- Deep copy
Person p = new Person("Ali", 40);
Person p2 = p;
p2.Name = "Reza";
Console.WriteLine(p.Name); // ==>> the result is Reza
Console.WriteLine (p2.Name); // ==>> the result is Reza
By default when you have the code above you will get a reference copy of your p object. It means that, if you change the value of p2 it will effect the values of p.
So if I want a real copy of my object what I have to do?
There is two way to do this, but with a different. Imagine that I have a class named Invoice which has a reference to Person class, like this:
public class Invoice
{
public int No;
public DateTime Date;
public Person Customer;
//.............
}
Now I want to have a copy of my Invoice object inc.
Invoice inc = new Invoice("1001",DateTime.Now,new Person("Reza",40));
// Invoice inc2 = inc; // It 's not what I really want.
So I have to use the second type of object copy which is Shallow copy. In Shallow Copy you will get a new object with all the values copies to the new object. But the point is that you just have a reference copy of you related references types (like Customer: Person). To get a Shallow Copy of your object you can use MemberwiseClone() method of object. I've created a method called ShallowCopy() in my Invoice class.
public Invoice ShallowCopy()
{
return (Invoice)this.MemberwiseClone();
}
Then if you create an object copy of your invoice and change No or Date values this will not effect to the inc object values. But changing the value of it 's Customer, will do:
Invoice inc2 = inc.ShallowCopy();
inc2.No = 1002;
inc2.Customer.Name = "Masoud";
Console.WriteLine("Invoice No: {0}, Customer Name :{1}",inc.No,inc.Customer.Name); // ==> I nvoice No: 1001, Customer Name : Masoud
Console.WriteLine("Invoice No: {0}, Customer Name :{1}",inc2.No,inc2.Customer.Name);// ==> Invoice No: 1002, Customer Name : Masoud
To get a Deep Copy of you object, you have to implement IClonable interface for Invoice and all of it 's related classes:
public class Invoice: IClonable
{
public int No;
public DateTime Date;
public Person Customer;
//.............
public object Clone()
{
Invoice myInvoice = (Invoice)this.MemberwiseClone();
myInvoice.Customer = (Person) this.Customer.Clone();
return myInvoice;
}
}
public class Person: IClonable
{
public string Name;
public int Age;
public object Clone()
{
return this.MemberwiseClone();
}
}
Now you have a real deep copy of you invoice object.
Invoice inc3 = (Invoice) inc.Clone();
inc3.No = 1003;
inc3.Customer.Name = "Mohammad";
Console.WriteLine("Invoice No: {0}, Customer Name :{1}",inc.No,inc.Customer.Name); // ==> I nvoice No: 1001, Customer Name : Masoud
Console.WriteLine("Invoice No: {0}, Customer Name :{1}",inc2.No,inc2.Customer.Name);// ==> Invoice No: 1002, Customer Name : Masoud
Console.WriteLine("Invoice No: {0}, Customer Name :{1}",inc3.No,inc3.Customer.Name);// ==> Invoice No: 1003, Customer Name : Mohammad
You can download the sample code at:
http://www.tabatabaei.info/csharpsamples/copysemantics.rar
Sunday, August 19, 2007
Service Controller Sample
In this sample I've used the ServiceController class to view services installed on local or any machine.
You can download the source code here:
http://www.tabatabaei.info/csharpsamples/serviceController.rar
Please let me know if there was any question.
Windows Service Applications
In some cases you may want to have an application which is performing since the computer has been turned on. For instance consider an application which is logging changes in an specific directory in your server, or you might think about Anti Viruses or any other application like that.
Windows Services a kind of windows application without any user interface, which is working in background of your system. In many situation you may want to have an application which is working on your system, event before any user has been logged in.
There is a class names ServiceBase in System.ServiceProcess namespace which has to be derived if you want to have your own Windows Service application. The ServiceBase classs has OnStart() method which will occur when the service has been started using SCM (Service Control Manager) which is accessible by Services icon on Administrative Tools of Control Panel. You can override the OnStart() method for doing any special task in your service. You can also stop your service tasks by overriding the OnStop() method of ServiceBase.
Consider that every service class needs an Service Installer to install the service. So for creating the service installer just goto design mode of your service class and Right Click on it and then click on Add Installer then you will see that a new class has been added to your project. Consider that your services will be run with an specific User of system, to change this behavior you have to change the Account property of ServiceProcessIntaller instance in the new added class to LocalSystem. In the next post I will talk more about other accounts and properties of this class.
َFor running a service you SCM first you have to install. To achieve this goal you can use the InstallUtil application with your assembly (the exe file) passed as parameter. You may also want to uninstall a service which can be done by passing /U at the end of InstallUtil.
I've prepared a sample which will log all the changes in a specified directory within the configuration file. The log file path is also can be set within the configuration file.
You can download the source code here:
http://www.tabatabaei.info/csharpsamples/systemwatcher.rar
Monday, June 25, 2007
Hashing Passwords
In many web site you have seen that they reset your password instead of giving your current password. The only reason that they do this is that actually they cannot retrieve your password.
The way that you store passwords in databases it 's really important. If you store all the users and passwords in clear text, if somebody can access to your database she might do what ever she want. Because of this it 's recommended to store passwords in a way that nobody can get it.
In Hash algorithms you cannot get the original value from the hashed value. And It 's approximately impossible to find a value which the hash of that value become the same as your hashed value. (But not 100%). So I 'm going to tell you how you can Hash your password and store that in your database.
In System.Security.Cryptography namespace there is a class named HashAlgorithm which is a base class for all Hashing algorithm classes such as SHA1Managed or MD5 and ...
It has a method named ComputeHash which return a byte[] of hashed value you passed as byte[]. Take a look at these lines:
HashAlgorithm hashAl = HashAlgorithm.Create("MD5");
byte[] myPasswordInBytes = Encoding.Unicode.GetBytes(txtPassword.Text);
byte[] myHashedPassword = hashAl.ComputeHash(myPasswordInBytes);
Now you can store your hashed password in wherever you want.
Notice that next time the user tries to login , you have to again hash the password and compare it with the one it 's stored in Database, like this:
private bool CompareHashPasswords(byte[] hashedNewPass, byte[] hashedPass)
{
if (hashedNewPass == null || hashedPass == null || hashedNewPass.Length != hashedPass.Length)
return false;
for (int i = 0; i <>
{
if (hashedPass[i] != hashedNewPass[i])
return false;
}
return true;
}
Download the sample code:
http://www.tabatabaei.info/csharpsamples/HashPassword.zip
Sunday, June 3, 2007
Constructor Overloading
Here is a simple sample of constructor overloading.
There is nothing to explain I think, but if anybody has question leave it on comment, I will answer.
Here is the link:
http://www.tabatabaei.info/csharpsamples/ConstructorOverloading.zip
Monday, May 28, 2007
Background Worker
I 'm going to explain how you can use the C# BackgroundWorker component of System.ComponentModel namespace, in your windows form applications.
BackgroundWorker component gives you a way to run a time-consuming task on a separate thread. Actually it works the same way as the asynchronous delegates, but in asynchronous delegate approach you have to consider some issues about working with your UI elements, because there are running on another thread. In BackgroundWorker marshalling issues are abstracted away with an event-based model.
Now let start working with BackgroundWorker.
First, you need an instance of BackgroundWorker class, no diff you are creating this programmatically or by dragging it onto a form at design time from your Component tab of Toolbox.
Next step is to set the event handlers of you object, and finally you have to call RunWorkerAsync() method.
Whenever you call this method it get a free thread from CLR and fires DoWork event. Now you put your codes (The codes that you want to be executed in another thread) in event handler of DoWork event. If the code completed it will raise an event called RunWorkerCompleted to notify you. It 's important to know that this event is not raised on the new thread instead, it will be raised on main thread of your application.
In many cases you may want to prepare some information (Arguments) for your time-consuming task. So, you can achieve this by passing an object into RunWorkerAsync() method, this object is accessible in your DoWork event as an object with it 's event argument.
The event args of DoWork event is an object of type DoWorkEventArgs.
In this object you have a property called Argument for getting what you have passed in RunWorkerAsync() method. You can use it in your time-consuming task.
Then you may want to have the result of your task in your UI. Again for this purpose you have a property called Result which you can set it in your DoWorkEventArgs. And it will be accessible in your RunWorkerCompletedEventArgs of RunWorkerCompleted event.
BackgroundWorker sample download link:
http://www.tabatabaei.info/csharpsamples/backgroundworker.zip
Sunday, May 20, 2007
Starting new process
In the last post, I explained how to get a list of existing process on local or remote machine.
Now I want to explain how to start a new process in C#.
If you create an object of Process class, you can set some information on StartInfo property of the object to specify what to do when you start the process. In the line below I 'm going to Print a word document in my C# sample:
Process printProcess = new Process();
try
{
OpenFileDialog op = new OpenFileDialog();
op.Filter = "Microsoft Word Document (*.doc)*.doc";
if(op.ShowDialog() == DialogResult.OK)
{
printProcess.StartInfo.FileName = op.FileName;
printProcess.StartInfo.Verb = "Print";
printProcess.StartInfo.CreateNoWindow = true;
printProcess.Start();
}
}
catch(Win32Exception ex)
{
if(e.NativeErrorCode ==2)
MessageBox.Show(e.Message + ". Check the path.");
else if(e.NativeErrorCode == 5)
MessageBox.Show(e.Message + ". You do not have permission to print this file.");
}
Notice that I 've used "Print" for Verb property of StartInfo. If you don't know what are available verbs on a extension (if it 's not executable) you can get list of verbs by using Verbs proerty of the process. Just like this:
ProcessStartInfo stInfo = new ProcessStartInfo(fileNameWithExtension);
foreach(string verb in stInfo.Verbs)
{
Console.WriteLine(" {0}",verb);
}
Notice that after you ran the process, changing the value of StartInfo property does not effect on the running process.
And you can use specific username and password withing UserName,Password property in StartInfo but if you set thses property the process starts in new window even if the CreateNoWindow property value is true of the WindowStyle property value is Hidden.
Getting processes on local or remote machine
The Process class in System.Diagnostics namespace, provide information about processes on current or a remote machine.
You can get list of all process on your local machine by this line of code:
Process[] process = Process.GetProcesses();
or if you want to have a list of a remote computer process list:
Process[] processList = Process.GetProcesses("machineName");
You can also use IP instead of computer name if desired.
There are also some static methods that help you to get specific process by it 's Name/Id on local or a remote computer.
Process proc = Process.GetProcessesByName("notepad");
Then you can get some information about the process. For instance in the line below I 'm getting the process filename from the MainModule property:
foreach(Process proc in Process.GetProcesses())
{
Console.WriteLine(" ProcessName : {0}, File Name: {1}",proc.MainModule.ModuleName, proc.MainModule.FileName);
}
If you want to stop a process you can use the Kill method on that process. But notice that if the process cannot be terminated you will get a Win32Exception or if the process has already exited you will get an InvalidOperationException.
It 's important to know when you are using Kill method, that you can only Kill local processes and if you try to terminate a remote process by calling Kill method, you will get a SystemException.
