Monday, December 3, 2007

Visual Studio .NET Keyboard shortcuts

While I 'm working and training C# or ASP .NET some of student asking me about what are the common shortcuts that I 'm using in Visual Studio.
Here is a list of Visual Studio 2005 and also Visual Studio 2008 keyboard shortcuts.

Visual Studio .NET 2005 C# Keybinding
Visual Studio .NET 2008 C# Keybinding


Enjoy it.

Wednesday, November 21, 2007

7 of the Hardest Things Learned About Writing Software

Scott Watermasysk wrote an article on his weblog yesterday about software development.

Learning to write code is not that hard. With a book, Google, and a little free time just about anyone can hack something together. However, to become a good software developer you need a passion to constantly and continually learn.

Listed below is a list of 7 of the harder things I have learned over the last couple of years:

  1. Make choices - Not everything needs to be adjustable or needs an option. Many times, it just needs to work.
  2. Delete code - Sometimes even the best ideas will not work (or are not worth keeping). Admit that at this time, based on what you know, the tools at your disposal, and the requirements for success you just need to move on. 
  3. NIH (not invented here) - Realize that even though you would have written something better, more scalable, and usable...if it meets your goals as is, you should focus your attention elsewhere.
  4. UI is more important than code - You can write the absolute best code the world has ever seen and if you present it like a turd, your code, to the world is a turd.
  5. Solve Problems - Realize that to more than 99.9% of the worlds population, code/technology are simply a means to an end. Software solves problems. The world really doesn't care how or why it works.
  6. You Are Different - When you write software, in most cases, you are not the typical end user. Your users are not looking for a challenge. For most, there are a million other things they would rather be doing than using your application.
  7. Documentation - Yes, documentation is necessary, but users do NOT want to read it. If your users are asking you for more documentation, the lack of documentation is not really the problem. Your application is too complicated.  See The Paradox of the Active User.

Is there anything you would add to the list? You can add your item in his original post here:

http://simpable.com/software/7-hard-things/

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.

ScottGu has reviewed some of new features of Visual Studio 2008 so you can read more about this in his weblog.

kick it on DotNetKicks.com

Wednesday, October 31, 2007

mojoPortal Wins Best Other Open Source CMS 2007

Yesterday, mojoPortal Wins Best Other Open Source Content Management System.
mojoPortal, is an open source web site framework and content management system written in C# that runs under ASP.NET on Windows or under Mono on Linux or Mac OS X.

About The Award:
The Packt Open Source Content Management System Award is designed to encourage, support, recognize and reward an Open Source Content Management System (CMS) that has been selected by a panel of judges and visitors to www.PacktPub.com. Following on from the success of 2006, Packt has expanded the Award for 2007 with an increase in prize money and the addition of new categories.

The 2007 Award will continue to support open source Content Management Systems and in order to reward more than one project, Packt has developed new categories for a wider variety of CMS's to benefit from. These are broken down into five different categories including the overall winner and the most promising Open Source CMS:


After more than 18,000 votes, we've now closed the voting for the  2007 Open Source CMS Awards. Votes are currently being counted and the judges decisions are coming through . The winners will be announced starting from Monday 29 October, in the following order:

Monday 29 October:
Best Open Source Social Networking CMS

Winner:
WordPress
Joint Runners up: Drupal & Elgg

Tuesday 30 October:
Best Other Open Source CMS

Winner: mojoPortal
First Runner up: Plone
Second Runner up: Silva


you can read the full story here

Monday, October 29, 2007

Sample Code Download

During last week I got some mails and comments about problem with downloading sample codes of posts. I just fixed the problem and now all of the post 's sample code link is working properly. But anyway if there was any problem please let me know.

Masoud_TB

Saturday, October 27, 2007

Search .Net

Actually finding something about .NET is easy by using Google or any other search engine, but a custom search engine will give you better and more reliable result.
If you want to have a customize search engine about .NET topics, you can take a look at SearchDotNet.com. You can also recommend your favorite web site or book about .NET.
Here is the site features as it said:

  • OpenSearch support: If you're using Firefox 2.0 or IE7 (or other OpenSearch client), you can add SearchDotNet to your list of search engines.
  • Google Gadgets: Add SearchDotNet to your website, Google home page or Google Desktop.
  • Component search engine: Distinct Custom Search Engine includes the sites of hundreds of component vendors.
  • Book site: Top rated .NET related books.

Monday, September 10, 2007

How to get list of windows user in C#

If you want to have the list of an specific windows group in C# you can get this list by these lines of code below. Notice that you have to add a reference to System.DirectoryServices .

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators","group");
object members = admGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
    DirectoryEntry member = new DirectoryEntry(groupMember);
    lstUsers.Items.Add(member.Name);
}

you can download the source code here:
http://www.tabatabaei.info/csharpsamples/WindowsGroupMember.rar

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.

We have two kind of remotable objects, one Marshal-by-value objects and Marshal-by-reference objects.
  • 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.
Notice that the objects from other classes which are not in that two types cannot be used in remoting.

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.
Server activation it self contains two types, which can be specified with using WellKnownObjectMode enumeration items:
  • 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.
Part 2: Host Application
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#.

  1. Reference copy
  2. Shallow copy
  3. Deep copy
As you may now the default behavior of c# compiler is the first one. Let me explain it by a sample:

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, July 16, 2007

Adding a control into Menu or Toolbar

You can add a control into a menu, context menu or toolbar by using a ToolStripControlHost class.
Just pass the control reference to constructor of ToolStripControlHost class and then add your ToolStripControlHost instance as a MenuItem in you Menu or .... Just take a look at the code below:

private void Form1_Load(object sender, EventArgs e)
{
MonthCalendar picker = new MonthCalendar();
picker.DateSelected += new DateRangeEventHandler(picker_DateSelected);
ToolStripControlHost host = new ToolStripControlHost(picker);
fileToolStripMenuItem.DropDownItems.Insert(2,host);
}

void picker_DateSelected(object sender, DateRangeEventArgs e)
{
MonthCalendar picker = ((MonthCalendar)sender);
this.Text = picker.SelectionStart.ToString("yyyy/MMM/dd");
}


You can download the sample code:
http://www.tabatabaei.info/csharpsamples/CalendarContext.rar


نسخه فارسي اين پست رو مي تونين از طريق لينك زير پيدا كنين:
DeveloperCenter.ir

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

Tuesday, June 19, 2007

Impersonation in C#

Imagine you are going to create an application that have a method which is working with a file named Test.txt. When you run the application your code throws an error containing this message : "Access Denied on C:\Test\test.txt". After reviewing the code you find out that because the current user of windows does not have access to "C:\Test" directory. Now you want to force your application to use another User information in that block of code, we call this procedure Impersonation.

There is some classes in System.Security.Principal which helps you to achieve this goal. WindowsIdentity and WindowsImpersonationContext are two classes which we are going to use. We want to use Impersonate() method of WindowsIdentity which return a WindowsImpersonationContext. Then after you 've finished working with your file after calling Impersonate() method, you can return you current login of windows using Undo() method of your WindowsImpersonationContext instance. like this:

IntPtr accessToken = IntPtr.Zero;
....
//You have to initialize your accessToken with API calling
....
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
...
// Now your code is using the new WindowsLogin and you can do what ever this login can do
...

//Now you can return to your current login of Windows
context.Undo();


You can download the complete sample code here:
http://www.tabatabaei.info/csharpsamples/Impersonation.zip

Monday, June 11, 2007

Multi Row Selection in GridView

It some cases you want to have the ability to select mutli rows in GridView. By default it can not be done in GridView, but you can have a CheckBox for each row in your GridView and then users can select two or more row by checking the CheckBoxes.

So, after you created your GridView and binding that to a DataSource. You can add a TemplateColumn in your GirdView as the first Column. Like this:


<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Then you can have the selected rows index with these lines of code:

private int[] GetSelectedIndices()
{
ArrayList indicesList = new ArrayList();
for(int i = 0 ; i <>
{
GridViewRow row = GridView1.Rows[i];
// 0 means the first column if your Select column is not first write it 's correct index
CheckBox chk = row.Cells[0].FindControl("chkSelect") as CheckBox;
if(chk != nul && chk.Checked)
indeicesList.Add(i);
}
return (int[]) indicesList.ToArray(typeof(int));
}

you can find sample code here:
http://www.tabatabaei.info/csharpsamples/mutlirowselectgrid.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

Friday, June 1, 2007

ASP .NET Page Caching

ASP .NET 2.0 provides a great mechanism for page out put caching. Consider that you have a web page which is showing some information to the users. Now we want to cache this page out put for user with 60 seconds.

To achieve this goal you need just put some code in your pages like this:

<%@ OutputCache VaryByParam="None" Duration="60" %>

The OutputCache directive will create a copy of your page html output to ASP .NET Cache and from the next request to this page up to the end of Duration period the response object will return only this Html cached output. So as you see I’ve put 60 in Duration which mean that the cache duration is 60 seconds.

VaryByParam attribute is semicolon-separated list of strings used to vary the output cache. When I set it to “None” it means that this page will just have one version in its cache. But if I set it to catalogId it means that it will cache each and every page with different catalogId Query String passed. Like this:

http://www.mywebsite.com/mypage.aspx?catalogId=10 ==> version 1

http://www.mywebsite.com/mypage.aspx?catalogId=102 ==> version 2

http://www.mywebsite.com/mypage.aspx?catalogId=1010 ==> version 3


And so on....
As I said, VaryByParam can have more that one parameters as semicolon-seperated list, like this:

<%@ OutputCache VaryByParam="None" Duration="60" %>

I will discuss more about page output cache in my next post.

Wednesday, May 30, 2007

Sample Code Post

I was thinking about C# Tuning and I found out that some days I don't have enough time to write an article and post it but there are lot 's of samples that can be published here and you can get some point over them. So I decided to create a new kind of posts, which I will call it "Sample Code Post".

So I hope these samples can be useful for you and if there was any king of question about these samples you can just comment over the post and then I will answer to your questions.

Tuesday, May 29, 2007

Loading images asynchronously with JavaScripts

Sometime you may want to load a list of data in your web pages. Imagine that every row of your data has an image. So you can use a GridView control in your webpage and create you template. The point that I 'm goint to cover in this post is about how to load the images of your rows asynchronously!

It 's seems great to set a default image for your page that will be shown while the images is loading from the server asynchronously. Because that image is loaded once it will help your page load time. And then after page load completed you will start loading your images from server asynchronously.

Let 's start with creating the GridView control and setting an XML file for it 's datasource by using an XML Datasource object in our form. The source code would be something like this:

<asp:XmlDataSource ID="xmlDataSource1" runat="server" DataFile="~/App_Data/mySource.xml"></asp:XmlDataSource>

<asp:GridView ID="gridView1" runat="Server" AutoGenerateColumns="False" DataSourceID="xmlDataSource1" Enabled="false">
<Columns>
<asp:BoundField DataField="Author" HeaderText="Author" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:TemplateField>
<HeaderTemplate>Image</HeaderTemplate>
<ItemTemplate>
<img border="1" src="images/csharptuning.jpg" onError="this.src=csharptuning.jpg" onLoad="GetArticleImage(this,'<%# Eval("ImageUrl")%>');" width="125" height="125"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Notice that for loading the default image in each data row, I 've set the "src" attribute of my image control to a default value like src='csharptuning.jpg'.I have also set something to load the actual images asynchronously after the loading of image controls.

So, first I create a web page which is give me my images dynamically by a QueryString. (I have been explained how to create these kind of pages here).

Then I have to set it to load the actual image after the image control loaded. For this purpose I create a JavaScript function in my page like this:

<script>
function GetArticleImage(img, url)
{
img.onload = null;
img.src = 'GetImages.aspx?fname=' + url;
}

</script>

and then I added onLoad='GetArticleImage(this,<%# DataBinder.EvalContainer.DataItem,"ImageUrl") %>' event on my image control.

Now you can start your page, then you will see that in first seconds you will get a default image for each record, but after some seconds (in my code is 5") you will get the actual result of your images.

You can also download this sample by this link:
http://www.tabatabaei.info/csharpsamples/asyncImages.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

Thursday, May 24, 2007

Changing the Content Type of a Web Page

Some times we want to get an image dynamically from a ASP .NET web form.
So we just create a web form containing an ImageControl. Then in this form we set a value on Session.

protected void Page_Load(object sender,EventArgs e)
{

// Putting some files path on session
Session["MyValue"] = "myImage.gif";
}


Now I want another web page which is create/load an image depending on the value I 've put in Session. And then I set the ImageUrl of that Image control to my new web page. Like this:


<asp:Image ID="imgDynamic" runat="server" ImageUrl="~/getimages.aspx" />

Notice that ImageUrl have been set to an aspx file!

Now in my GetImages web form I have to decide to create/load the image depending on the value of Session variable. The important point is that the output of this web form is not HTML code, instead I is responding some images. So I have to change the content type of my web page. And finally I have to put my Image to the Response of my web page. For these I just write these lines of code:

protected void Page_Load(object sender, System.EventArgs e)
{
// Create/Load the image from the string value in session
Bitmap b = new Bitmap(Server.MapPath(Request.ApplicationPath) + "\\Images\\" + Session["MyValue"].ToString());

// Change the response headers to output a JPEG image.
this.Response.Clear();
this.Response.ContentType = "image/jpeg";

// Write the image to the response stream in JPEG format.
b.Save(this.Response.OutputStream, ImageFormat.Jpeg);

}

Download the sample code:
http://www.tabatabaei.info/csharpsamples/dynamicImage.zip

Monday, May 21, 2007

Localization in ASP .NET 2.0

I 'm going to explain How to implement multi lingual web forms in ASP .NET 2.0.
Let take it with a sample. Imagine we have a web form which user has to fill their personal information and save it to our database. Now, I want this web page to be multilingual.

So, First I just create a web page that I 'm going to have in English version. The web form name is "MultiLingualWebForm.aspx".

Then I have to add an special ASP .NET folder to my web site. So right click on web site, then Add ASP .NET Folder and choose App_LocalResources.

Now I have to add a new item in this folder like this:
R.C* on App_LocalResources --> Add New Item --> Resource File --> Set the name to "MultiLingualWebForm.aspx.resx"

Now a file will open up in Visual Studio .Net, I just try to add some Items in this Resource file and save the file.



Notice that the first part of name "WelcomeLable" is the Control name on the page, and the second part ".Text" is the property name of the control.

Then create another copy of this file with "MultiLingualWebForm.aspx.fr.resx" name.
The fr is telling that it 's the French version of that file.

And also another copy with name "MultiLingualWebForm.aspx.fa.resx" which fa is the international name of Farsi.


Then change all the values to it 's translation of target language:

Welcome ==> خوش آمديد
and so on...

Now, I 'm going to add some new attributes on my ASP controls. So in each of my Label controls I added a new tag called meta with a resourceKey property like this:


<asp:Label ID="WelcomeLabel" runat="server" Text="Label" meta:resourceKey="WelcomeLabel" ></asp:Label>

I add this to all the other Labels and also for those Buttons on my web form.
And I set two properties of my Page in my page directive.

Culture="auto:en-US" UICulture="auto"

Then I save the web page and run it.
So, to check out is it working or not? While you have your browser open, go to Tools menu then Internet Option, in the opening window go to Languages then add Farsi and French, bring up on of the to the first (it 's setting default language of your browser) then OK and OK again.

Now Refresh you page, you will see the translation of that page to your preferred language. OK That 's all.

Anyway, here is the code of my our sample you can download it.
http://www.tabatabaei.info/csharpsamples/MultiLingualWebForm.zip

ASP.NET 2.0 Data Tutorials

I was browsing ASP .Net : The Official Microsoft ASP .NET 2.0 web site and I found out a link about working with data and ASP. NET 2.0.
It 's really great articles about how to work with data in ASP .NET 2.0 and It cover 's lot of things in ASP .Net.

I strongly suggest you to read this articles if you 're interested in working data intensive web application in ASP. NET 2.0

http://www.asp.net/Learn/DataAccess/#intro

Sunday, May 20, 2007

ScottGu's Blog

I want you to introduce a blog from a Microsoft man.
His is name is Scott Guthrie, and he is General Manager within the Microsoft Developer Division. He runs the development teams that build the following products/technologies:

Common Language Runtime (CLR)
ASP.NET
Silverlight
WPF
IIS 7.0
Commerce Server
.NET Compact Framework
Visual Web Developer
Visual Studio Tools for WPF

You can find too many great tips about ASP .NET and Oracas (new version of Visual Studio) and some other Microsoft Technologies.

http://weblogs.asp.net/scottgu/

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.

Saturday, May 19, 2007

Adding Removing Items from ListBox

I this simple sample code, I 've two Listboxes which in the Left Side there is a list of cars, and you can add/remove Item from/to the RightListbox.

I 'm holding all cars, and selected cars in session two keep over post backs.
If you want to enable multi select on the sample put

SelectionMode="multiple"

for the listboxes.

You can download the code here:
http://www.tabatabaei.info/csharpsamples/AddRemoveItems.zip

Uploading Multiple Files

Sometime in your web application, especially the ones which is working with files, you may need to upload more than one file in a web page. While you don't know how many files you have to upload it seems to be a good way to create a control which can upload one or more dynamically.

The first thing that I 'm going to do is to place a FileUpload control in my control and a button for upload and a link for a new file upload control. Like this:

<div>FileName: <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:LinkButton ID="lnkAddMore" Text="Add More..." runat="server"OnClick="lnkAddMore_Click"></asp:LinkButton> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /><br /> <div runat="server" id="divFileUpload"> </div></div>

notice that, inside the last div I put another div which is a server html control.

Then in the link button event handler I wrote some codes like this:


protected void lnkAddMore_Click(object sender, EventArgs e)
{
FileUpload fileUpload = new FileUpload();
Literal lt = new Literal();
lt.Text = "<br/>";

divFileUpload.Controls.Add(fileUpload);
divFileUpload.Controls.Add(lt);

AddedControls.Add(fileUpload);
AddedControls.Add(lt);
}

I put the "AddedControls" property on the control which is List to keep all the added controls in the Session. The point is that we have to keep them to add in each and every post back.


protected List AddedControls
{
get
{
if (Session["AddedControls"] == null)
Session["AddedControls"] = new List();
return (List)Session["AddedControls"];
}
set
{
Session["AddedControls"] = value;
}
}

So, for adding this controls every time I create the event handler for "PreInit" event:


protected void Page_PreInit(object sender, EventArgs e)
{
foreach (Control ctrl in AddedControls)
{
divFileUpload.Controls.Add(ctrl);

}
}

In the last part, I 'm saving all the uploaded files using "Request.Files" property in Upload button event handler:


protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile file = (HttpPostedFile)Request.Files[i];
if (file.ContentLength > 0)
{
try
{
file.SaveAs(Request.PhysicalApplicationPath + "\\UploadedFiles\\" + file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1));
}
catch (Exception ex)
{
Response.Write("" + ex.Message + "");
continue;
}
}
}
}

in HttpPostedFile class there is a SaveAs method which I 'm using to save my files to the server. The method need a physical path so I provide it by Request.PhysicalApplicationPath.

You can download the sample code here:
http://www.tabatabaei.info/dynamicfileupload.zip

Saturday, May 12, 2007

Ehsan 's blog

Congratulations to Ehsan, for starting his weblog "EhsanBrainDump".

As you may know "Ehsan Shalchian" is one my friend and of course one of my great teachers who is famous for his knowledge over "Software Analysis & Design Patterns" and "C#" and also too many software engineering related technologies.

I suggest you to review his posts which of course would be valuable posts.

ASP .NET References

As many of my students ask from me to give them some references for ASP.NET, I will introduce a web log post from "Bill Evjen" who has wrote some books in C# and VB .NET. http://geekswithblogs.net/evjen/archive/2004/12/10/learnaspnet.aspx He has categorized some Subjects over ASP.NET. Take a look, it worth.

Getting All Selected Items of CheckListBox

Oh, after a while again I decided to start writing on this blog.

Any way, I thing sometimes it happens that you need to show some choices to your users then ask them to select any many as they want. So as you may know the best choice is CheckListBox. So after Binding it or adding your items into it you may want to get a list of SelectedItems over the checklistbox. So you have to iterate over your items then check whether if the item is checked or not like this:


foreach (ListItem item in CheckBoxList1.Items)
{
if(item.Selected)
{
Response.Write("<h3>" + item.Text + "</h3>");
}
}

Do not forget comments.

Wednesday, March 7, 2007

MutiView Control

You can think of MultiView as more advanced panel that let you switch between groups of controls on a page.

MutliView
Essentially, the MultiViewgives you a way to declare multiple views and show only one at a time.
It 's really simple to use that, just put it from the Toolbox, then add one or more View control inside this.Now you can have you user interface design in all the views, separately.
By default the ActiveViewIndex, the property which determine which of the view control 's has to be shown, is set to -1.
So you can just set the index of your desire.
It 's also a method called SetActiveView which can set the active view control by it 's reference.
It the sample that I 've been created.I set the ActiveViewIndex to 0 in Page_Load event, when it 's not post backed.

Masoud_TB

Tuesday, March 6, 2007

Sending email in ASP .NET 2

In asp.net application it may needed to send an email to specefic email address. In ASP .Net 1 and 1.1 it was so simple to send an email, as it 's in ASP .NET 2.0.

In ASP .NET 1.1 we just create a MailMessage object from the System.Web.Mail namespace setting the properties and send that mail. Just like this:

MailMessage m = new MailMessage();
m.Body = “Mail Body Text”
m.BodyEncoding = System.Text.Encoding.UTF8;
m.BodyFormat = MailFormat.Html;
m.To = "SbElse@AnotherWebSite.com";
m.Subject = ”Mail Subject”;
m.From = "Somebody@AWebSite.com";
m.Priority = MailPriority.High;


SmtpMail.Send(m);


ASP .NET team in the 2.0 version decided to move the System.Net.Mail instead of System.Web.Mail.
Actually System.Net.Mail is a new namespace which contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. (as Microsoft Says)

Anyway, for sending mail in ASP .NET 2.0 , I just create a MailMessage and set the properties of that, and at the end I use a SmtpClient object to send the mail message, like this:

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("From@WebSite.com","To@WebSite.com");
message.Subject = "Here is the subject";
message.Body = "Body of the message";
message.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure;
message.Priority = System.Net.Mail.MailPriority.High;


System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.UseDefaultCredentials = true;
smtp.Send(message);


I used the UseDefaultCredentials becuase for some SMTP servers it requires to authenticate for sending mail. So this information can be setted in web.config file when UseDefaultCredentials is true.

Finally, I set these configuration settings on the web.config file like this:

<system.net>
<mailSettings>
<smtp from="user@host.com">
<network userName="user@host.com" password="pass" host="localhost">
</smtp>
</mailsettings>
</system.net>

notice that the host attribute of the network entity is the SMTP mail server address. Which I used localhost in this sample.

I hope it can help you.
Masoud_TB

Input Language

While you have a multilingual application you may intended to set the current input language (Keyboard language) in your application. There is a class called InputLanguage in System.Windows.Forms namespace, which Provides methods and fields to manage the input language (as Microsoft says)

In this Windows C# sample I 'm going to list all the InputLanguages installed on the current windwos and set the InputLanguage which the user desired.

For instance I have installed English and Farsi keyboard installed on my windows xp. So a comboBox list these two languages and whenever the user changes the languages on it, the system input language will change to the selected one. On the other hand I have two specefied textbox which I want whenever the user tries to type something on these textboxed change the keyboard language to farsi or english as desired.


Masoud_TB

Monday, March 5, 2007

Uploading Images to Server

Last week I was working on a project and in web form we wanted to ask people to upload their images to the server, and fill the application form.

So I tried to use the FileUpload Control which is a new WebControl in ASP.NET to upload the images to the server. The point was that I wanted to restrict people to only upload images with file extension "jpg" and "gif", so because the FileUpload control by default allow all types of file format to be uploaded, I used a regular expression to extract the file extension from the file name.
Another important thing for me was the file size of the images. I just want to allow users to upload images with max size of 50Kb, so I used the Length on FileContent property of the FileUpload, and at the end of my code, I used the SaveAs method to save the file in a specific way.

Notice that while your working with web application you have to get the physical path of your web application, not the http://www.yoursite.com/ so I used the Server.MapPath(Request.ApplicationPath) to get the physical path.

Masoud_TB

Wednesday, February 28, 2007

Welcome to C# Tuning

Hi, So eventually I started to create a webblog on C# programming language which is actually a great hobby and also my profession.
Here in this blog I will try to focus on programming with Microsoft C# .NET and actually I 'm intended to be more deep on ASP .NET, but anyway if there was any question about any thing please do not hesitate and go on.

Masoud_TB