The .NET blog

The Process class: Is my application already running?

June 10, 2009

In the last blog post, we used the Process class from the System.Diagnostics namespace to start applications and URL’s. However, you can do other things with this class as well – for instance, you can see which processes are running on the system:

Process[] runningProcesses = Process.GetProcesses();
foreach(Process p in runningProcesses)
	Console.WriteLine(p.ProcessName);

This piece of code will simply obtain a complete list of processes running on the system, and output the name of each one of them to the Console. We can use this to see if our own application is already running. First some code, and then I will explain it all:

public Form1()
{
	InitializeComponent();
	Process currentProcess = Process.GetCurrentProcess();
	Process[] runningProcesses = Process.GetProcessesByName(currentProcess.ProcessName);
	foreach(Process p in runningProcesses)
	{
		if(p.Id != currentProcess.Id)
		{
			MessageBox.Show("This application is already running. Terminating this instance...");
			Environment.Exit(-1);
		}
	}
}

We start out by obtaining a reference to our own process, by calling the GetCurrentProcess() method. We need the name of the process, to get a list of processes running with the same name, by calling the GetProcessesByName() method. Now since we’re executing code, our process is already alive, which means that there will always be at least one process with the name: The one executing the code :) . We check the Id property, to make sure that the process we have found is not "our self" – if it is, the Id will be the same, but if it’s not, it will be another instance of the same application. If we do find out that we already have an instance of our application running, we exit the current process. Try running the compiled application twice (from outside Visual Studio) and you will see that while the first instance runs just fine, the second will alert you that it’s already running and then close. Simple, yet effective :)

Filed under: C# — admin @ 11:33 am

The Process class: Starting an application or URL

May 21, 2009

The Process class from the System.Diagnostics namespace can be quite useful, especially for launching other applications or even URL’s. An application can be started with a single line of code:

Process.Start(@"C:\Windows\System32\calc.exe");

It doesn’t get simpler than that, in a perfect world. But as we all know, the world is not perfect, and that line could go wrong for a number of reasons, the most simple one being that the path I specified doesn’t fit with your computer. We should obviously handle any exception thrown, like this:

try
{
	Process.Start(@"C:\Windows\System32\calc.exe");
}
catch(Exception ex)
{
	MessageBox.Show("Could not start the file: " + ex.Message);
}

In case the file can’t be found, a specific FileNotFoundException will be thrown, which you could handle differently than other exceptions, but to keep it simple, we just catch all exceptions and treat them the same way.

Now, perhaps you want to include a parameter or something like that. The Process.Start() method does have an overload that takes a set of arguments, but it also comes with one that takes a ProcessStartInfo object, which makes you capable of doing some pretty advanced stuff. For instance, have a look at this example:

try
{
	ProcessStartInfo processStartInfo = new ProcessStartInfo();
	processStartInfo.FileName = @"C:\Windows\System32\notepad.exe";
	processStartInfo.Arguments = @"C:\somedocument.txt";
	processStartInfo.WindowStyle = ProcessWindowStyle.Minimized;
	Process.Start(processStartInfo);
}
catch(Exception ex)
{
	MessageBox.Show("Could not start the file: " + ex.Message);
}

We specify that the file to be started is Windows Notepad, that the arguments should be a .txt file on my local computer (create this file or specify another path to make this work on your computer), and that the application window of this new process should be minimized from the start. This code will launch Notepad, load the specified file and make the window minimized. There are many more cool options, which you can investigate on your own. To end this post, I want to mention that launching an URL is just as simple as an application:

try
{
	Process.Start("http://blog.net-tutorials.com");
}
catch(Exception ex)
{
	MessageBox.Show("Could not start the URL: " + ex.Message);
}

This will simply launch this fine blog in your default browser. Enjoy :)

Filed under: C# — admin @ 10:09 am

New articles on localization

April 8, 2009

I just added a bunch of new articles on localizing your ASP.NET website. You should go have a look right now, if you’re in the process of, or at least considering, localizing your website:

Enjoy :)

Filed under: General — admin @ 1:28 pm

How to: Alternate row color with the ASP.NET Repeater control

April 2, 2009

The ASP.NET Repeater control is great in a whole range of scenarios. I use it all the time my self because it’s flexible and simple to use. Often, it’s for outputting rows of data, where I want to avoid using the GridView control, or simply because I don’t want it to be built as a table. In that case, I find my self wanting to apply a different color to every second row a lot of the time, to get an effect like this:

John Doe
Jane Doe
John Doe
Jane Doe

Microsoft offers a way to accomplish this with the repeater:

<asp:Repeater runat="server" ID="repData">
	<ItemTemplate>
		<div style="background-color: #fff;">
			<%# Container.DataItem.ToString() %>
		</div>
	</ItemTemplate>
	<AlternatingItemTemplate>
		<div style="background-color: silver;">
			<%# Container.DataItem.ToString() %>
		</div>
	</AlternatingItemTemplate>
</asp:Repeater>

Now, that’s just fine for such a simple example, but usually my repeater will contain way more markup. Having it in two separate places fills up my file and forces me to make modifications in two places instead of one. It’s simply not a very practical solution, especially not when considering that we’re doing all that to output a different background color. It’s time to get creative:

<asp:Repeater runat="server" ID="repData">
	<ItemTemplate>
		<div style="background-color: <%# GetRowColor() %>;">
			<%# Container.DataItem.ToString() %>
		</div>
	</ItemTemplate>
</asp:Repeater>

As you can see, instead of outputting the color directly, we make a call to a function called GetRowColor(). It should be implemented in your CodeBehind file like this:

private int counter = 0;
protected string GetRowColor()
{
	if(counter++ % 2 == 0)
		return "#fff";
	else
		return "silver";
}

If you’re new to C#, you might wonder what that function does, but in fact, it’s quite simple. We have a counter variable, and each time the GetRowColor() method is called, we increment that variable (counter++ is the same as counter = counter + 1). We then use the modulo operator (%) to test if the number is an equal number or not – if it is, we return one color, and if it’s not, we return another color. This ensures that every other row is rendered with another background color.

Now, in a real life example, you might want to output the color choice another way. For instance, you could have an “even” and an “odd” CSS class to use each time you want even and odd rows, allowing you to define the color in one common place. Or perhaps you only want the style declaration on odd rows, letting equal rows default to the parent background color? No problem, just change the GetRowColor() method into something else and use it accordingly.

Filed under: ASP.NET, C# — admin @ 11:43 am

How to: Download a file from the Internet with C#

March 16, 2009

With .NET, working with remote files are very easy. From the System.Net namespace, we get several classes which comes in handy for doing just that. For instance, downloading a file to your computer can be accomplished with a few lines of code, using the WebClient class:

try
{
	WebClient webClient = new WebClient();
	webClient.DownloadFile("http://www.google.com/intl/en_ALL/images/logo.gif", @"c:\google_logo.gif");
}
catch(Exception ex)
{
	Console.WriteLine("Could not download file: " + ex.Message);
}

Besides the exception handling, downloading a file, in this case an image, is a two-line job. However, by doing it like this, we will be blocking the application completely while downloading the file. If you have to download larger files than a simple logo, you should definitely do it asynchronously. Fortunately for us, the WebClient class supports this right out of the box. But hey, wouldn’t it be cool if we could somehow see the status of the download in progress? No problem, WebClient can do that too. Here’s a complete example:

using System;
using System.Text;
using System.Net;
using System.ComponentModel;

namespace WebClientDemo
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				WebClient webClient = new WebClient();
				webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
				webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
				webClient.DownloadFileAsync(new Uri("http://upload.wikimedia.org/wikipedia/en/2/2e/STS-95_Florida_From_Space.jpg"), @"c:\STS-95_Florida_From_Space.jpg");
				Console.ReadKey();
			}
			catch(Exception ex)
			{
				Console.WriteLine("Could not download file: " + ex.Message);
			}
		}

		static void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
		{
			Console.WriteLine(String.Format("{0} of {1} bytes downloaded ({2}% done)", e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage));
		}

		static void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
		{
			if(e.Error == null)
				Console.WriteLine("All done downloading the file!");
			else
				Console.WriteLine("Could not download file: " + e.Error.Message);
		}
	}
}

We’re downloading a large image from Wikipedia, and as you will see, progress is written to the console. You can obviously fine tune this a bit – for instance, you might want to limit how often progress is written out, but besides that, it’s working pretty decent, and with a pretty limited amount of code. This is a console application, so there’s not that much need for doing stuff asynchronously, but for a WinForms application, doing stuff like this on a separate thread can be really important. If not for a more responsive UI, then at least for being able to report progress while downloading.

If you want direct access to the data being downloaded, without saving to a file first, you should have a look at the DownloadData() method, which returns a byte array, or the DownloadString() method, which downloads the file and returns a string representation of the content (mostly usable for plaintext files, obviously). Both have an asynchronous version too. Enjoy :)

Filed under: ASP.NET, C# — admin @ 10:14 pm

Microsoft releases free chart controls

December 1, 2008

In case you haven’t noticed it yet, Microsoft has just released a set of Chart controls to be used with both ASP.NET and WinForms applications. They support both 2D and 3D charts, and has a bunch of cool features, which should cover most of your charting needs :) . They can be downloaded from this page and Scott Guthrie from Microsoft has a more detailed post about the ASP.NET aspects of it here. Enjoy :)

Filed under: AJAX.NET, ASP.NET, C#, General — admin @ 6:13 pm

New articles on Reflection

November 13, 2008

Just a small note to let you know that a set of chapters about Reflection has been added to the C# tutorial. You can find the introduction right here. I simply love using Reflection, so I’m probably going to write some more on it in the near future – anything specific you would like me to look into? I’m all ears :)

Filed under: C#, General — admin @ 10:35 pm

Sorting items in a generic List<T>

October 27, 2008

Generic lists were introduced in .NET 2.0, and I have been a big fan of them ever since. I used to use the ArrayList class, before .NET 2.0, but the List<T> has the major advantage of being strongly typed, which is cool because the compiler will let me know if I’m trying to add another type than the one specified. When .NET is aware of which type of objects are in the list, everything becomes much faster too, because no boxing is required when adding and pulling items from the list.

This post is about sorting your generic lists, mainly because I do it all the time, and it’s actually quite easy, once you understand how it works. The Sort() method on a generic list has 4 overloads, and since the first one doesn’t take any parameters at all, it’s by far the easiest one to use :) . Here is an example:

List<string> list = new List<string>();
list.Add("Tom Hanks");
list.Add("Al Pacino");
list.Add("Mel Gibson");
list.Sort();
foreach(string name in list)
    Console.WriteLine(name);

We simply create a new list, add some names to it, call the Sort() method and then we output the list to the console. If you try the example, you will see that the items get sorted just perfectly – but how? Because the String object has a CompareTo() method that will do all the work, and since the compiler knows that the list will contain strings only, it can safely compare each item using the CompareTo() method of the string class. You can try changing the list type to a List<int> and add numbers to it instead – it will work like a charm! However, this was a simple example. In a lot of situations, you will be using the List<T> to store your own types in, and .NET won’t necessarily know how to sort them. Look at this example:

public class Person
{
    private string firstName;
    private string lastName;
 
    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
 
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
 
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
 
    public override string ToString()
    {
        return this.firstName + " " + this.lastName;
    }
}

If you create a new List<Person> and add some persons to it and try to call the Sort() method, you will get the following error:

Failed to compare two elements in the array.

Why? Because .NET has no idea how you want this new and strange type sorted. Fortunately, it’s easy to fix. I usually prefer doing it by letting my classes implement the IComparable interface:

public class Person : IComparable
{
    ...
 
    public int CompareTo(object obj)
    {
        if(obj is Person)
            return this.LastName.CompareTo(((Person)obj).LastName);
        else
            return 0;
    }
    
    ...
}

The CompareTo method is rather simple: It returns 0 if the two compared items are identical, and -1 or +1, based on which item is considered “bigger”. In this case, we simply take advantage of the fact that the String class has a CompareTo method, and then return the result of comparing the current object’s LastName property to the LastName property of the object passed in through the argument (obj). Try running the code now, and you should see the list get sorted by the persons last names. Now, if you wish to sort in the reverse order, you simply use the CompareTo() method on the obj instead of on this:

return ((Person)obj).LastName.CompareTo(this.LastName);

If you don’t want to, or can’t, implement the IComparable interface on the target class, you can do it “on the fly” by passing a delegate to the Sort() method. Here is a complete example:

List<Person> list = new List<Person>();
list.Add(new Person("Tom", "Hanks"));
list.Add(new Person("Al", "Pacino"));
list.Add(new Person("Mel", "Gibson"));
list.Sort(delegate(Person p1, Person p2) { return p1.FirstName.CompareTo(p2.FirstName); });
foreach(Person p in list)
    Console.WriteLine(p.ToString());

It might seem a bit faster and simpler, but it does require you to either write this delegate each time you use it, or declare it somewhere and pass it to the Sort method. Letting the objects them self do the comparing is probably a more clean solution, but not always possible. Hopefully this covers all your sorting needs :)

Filed under: C# — admin @ 12:32 am

Using the using statement

September 19, 2008

With .NET we have the garbage collector to clean up all the mess we make through the lifecycle of an application. But does that mean that we will never have to clean up anything our self? Not really. As a general rule, classes which implements the IDisposable interface should be manually disposed, usually by calling a Close() or Dispose() method on the instance. It could look a bit like this:

StreamReader sr = new StreamReader(@"C:\temp\myfile.txt");
while(!sr.EndOfStream)
{
        Console.WriteLine(sr.ReadLine());
}
sr.Close();

As you can see, we call the Close() method in the end – if we don’t do that, an unmanaged reference to the file will be kept open, which is something we really don’t want. However, you might have lots of lines of code working with the file, and in the end, you forget to dispose of the object. The using statement in C# can help prevent this, and also comes with another benefit, explained after this example of using it:

using(StreamReader sr = new StreamReader(@"C:\temp\myfile.txt"))
{
    while(!sr.EndOfStream)
    {
        Console.WriteLine(sr.ReadLine());
    }
}

As you can see, there are no explicit call to the Close() method – the using statement takes care of it for us. Since it has its own scope, the .NET framework knows that once this scope ends, the object(s) declared in the using statement can be disposed. You can even have several using statements for one block, like this:

using(Pen p = new Pen(Color.Black, 2))
using(SolidBrush sb = new SolidBrush(Color.Red))
{
    // Do stuff with p and sb here
}

As mentioned, the using statement comes with another advantage: It works as a try..finally block too! In the first two examples, an exception could easily occur, because we were dealing with files and doing no error checking at all. In the first example, an exception would cause the execution of the code to end, and the reference to the file would not be closed! This could be solved by creating the file reference within a try block, and then calling the Close() method in the finally block, but in fact, the using() statement does just that for us automatically, meaning that you can be sure that objects instantiated in a using statement will be disposed, no matter what!

So in conclusion: Use the using statement! :)

Filed under: C# — admin @ 10:28 am

Testing on different machines

September 14, 2008

In case you haven’t noticed, testing your applications on several machines is a very good idea, especially in that pre-beta phase, where you want to get rid of the most obvious bugs before showing your work for the first time. Especially with the .NET framework, testing your work on other machines than the one it’s being developed on is recommendable. You could easily have forgotten to include a specific assembly, or include an older version than the one you are currently using. Another common pitfall is to develop on Windows XP, and not testing on Windows Vista. A lot of things have changed, and some of them may break your application. And it goes the other way too – in my experience, several things which will work just fine on XP, will not work as well on a Windows 2000 machine.

Now, don’t go out and buy 2-3 new computers, with different OS’ on them. This scenario is perfect for the Virtual Machine. Many people swear by vmware, which is supposed to be really good, but personally I just use Microsoft Virtual PC 2007. With version 2007, it can now be downloaded and used for free, and in my experience, it’s very stable and extremely easy to use.

The absolute top feature of a virtual machine for software developers, is the undo disk feature. It allows you to boot the VPC, work on it, and then delete all changes. This gives you the possibility to test your application on a clean machine each time. Once you have installed a version of Windows in your Virtual PC, select it from the list and click Settings. Now, from the list of options, select Undo Disks and make sure that it has been enabled. Now, boot the OS, make it comfortable for you to work with (for instance, I always enable the display of file extensions, because I hate not being able to see them) and visit Windows Update and make sure that it’s fully updated. Once you close the system, make sure that you commit the changes to disk. You now have a fully functional test OS, and whenever you use it for testing purposes, just make sure that the “Commit changes to disk” is not checked, and the changes you have made will not be persisted. You may still choose to save changes from session to session, but it will be stored separately, and only committed to your VPC if you want it to – if not, simply select the delete option upon closing the OS.

With a setup like this, you have clean and mean testing environment for your applications :)

Filed under: General — admin @ 11:21 am
Older Posts »



© net-tutorials.com 2006 - 2010