Mar 2
Lambda Expressions
icon1 Boyan Mihailov | icon2 C# | icon4 03 2nd, 2008| icon3No Comments »

In C# 2.0 there are anonymous methods, which allows you to write your method code inline instead of creating a new method in your class. In C# 3.0 there is a new feature - lambda expressions. The goal of this expressions is the same as the anonymous methods, but the syntax is more concise.

Let’s have the following code:

class LambdaExpressionTest
{
  public delegate int myDelegate(int x);

  static void Main()
  {
    myDelegate testFunc = new myDelegate(LambdaExpressionTest.myFucn);
    Console.WriteLine(testFunc(5)); // returns 23
  }

  public static int myFucn(int x) { return x * x - 2; }
}

If we want to rewrite this code using anonymous method, it will get the following look:

class LambdaExpressionTest
{
  public delegate int myDelegate(int x);

  static void Main()
  {
    myDelegate testFunc = new myDelegate(delegate(int x) { return x * x - 2; });
    Console.WriteLine(testFunc(5));
  }
}

And if we want to rewrite this code using lambda expressions, it will look like this:

class LambdaExpressionTest
{
  public delegate int myDelegate(int x);

  static void Main()
  {
    myDelegate testFunc = x => x * x - 2;
    Console.WriteLine(testFunc(5));
  }
}

Isn’t it so simple? :) The sign ‘=>‘ is read as “goes to”. We first indicate the arguments of our method and after that we do our calculations in it.

Feb 23
Xml Serialization
icon1 Boyan Mihailov | icon2 C# | icon4 02 23rd, 2008| icon3No Comments »

If you want to store data, you often use a database. It’s very good way. But, sometimes you need to save too little amount of data that using a database is thoughtless. Another way to store data is to put it in a simple text file. One of the most convenient ways to do this is to use a XML file. It stores data in such a way, that you can easily access it later. XML files are used everywhere and for every type of usage. For example, two (or more) computers can communicate with XML files.

I am going to show you how you can convert your object to a XML file in order to save its data. This process if called serialization. There are many ways to serialize an object. I am going to show you how you can you do this by using the IXmlSerializable interface. It’s in System.Xml.Serialization namespace. You’ll need to include System.Xml namespace, too.

If you look at the source of this interface, you will probably see something like this:

interface IXmlSerializable
{
  System.Xml.Schema.XmlSchema GetSchema ();
  void ReadXml (System.Xml.XmlReader reader);
  void WriteXml (System.Xml.XmlWriter writer);
}

Read the rest of this entry »

Feb 22
Simple Gradient
icon1 Boyan Mihailov | icon2 C# | icon4 02 22nd, 2008| icon3No Comments »

A simple was how to draw a gradient on a form. All you need is to include both Drawing and Drawing2D namespaces in your project. As we are going to draw onto the form, we need to assure, that if user resizes it, we will have our gradient spread over the whole form. We can do this by using form’s Resize event. Each time the form is being resized, we tell it to repaint.

private void Form1_Resize(object sender, EventArgs e)
{
  this.Invalidate();
}

In order to paint on the form, we are going to use its Paint event. In this way, the next time a message to repaint is received, we will have our gradient repainted.

The class LinearGradientBrush creates a special brush, which we can use in our further work. It accepts four arguments:

  1. a rectangle, which determines the area where we are going to paint
  2. color one
  3. color two
  4. an angle

Here is a simple example.

private void Form1_Paint(object sender, PaintEventArgs e)
{
  e.Graphics.Clip = new Region(ClientRectangle);
  LinearGradientBrush gradient = new LinearGradientBrush(ClientRectangle, Color.Peru, Color.Pink, 90f);
  e.Graphics.SmoothingMode = SmoothingMode.HighQuality; // set the quality
  e.Graphics.FillRectangle(gradient, ClientRectangle);

  gradient.Dispose();
}

Gradient

Feb 10
Filesize To String
icon1 Boyan Mihailov | icon2 C# | icon4 02 10th, 2008| icon3No Comments »

I’ve made a simple function that converts a file size to a string. It computes the remainder after dividing the input size by 1024 and puts it in an array. This step is being performed while we have a size under 1024 - this is the number of the bytes.

uint[] s = new uint[7];
short n = 0;

while (size >= 1024)
{
  s[n] = (uint)(size % 1024);
  size = size / 1024;
  n++;
}

s[n] = (uint)size;

The type of size is Int64. It allows you to calculate too big numbers. After filling up the array, you can start walking it from its end like this:

StringBuilder results = new StringBuilder();
string[] sizes = { "bytes(s)", "KB", "MB", "GB", "TB", "PB", "EB" };

for(n = 6; n >= 0; n--)
{
  if (s[n] > 0)
  {
    result.Append(s[n]);
    result.Append(sizes[n]);
    result.Append(" ");
  }
}

Calling this function with argument Int64.MaxValue gives you the following result:

7EB 1023PB 1023TB 1023GB 1023MB 1023KB 1023bytes(s)

Feb 7
Allow Only One Instance
icon1 Boyan Mihailov | icon2 C# | icon4 02 7th, 2008| icon3No Comments »

Sometimes you need your application to have no more than one instance. Here comes the Mutex Class.

When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.

Here is a simple example showing how you can control the instances of you application.

[STAThread]
static void Main()
{
  bool createdNew;

  Mutex mutex = new Mutex(true, "MyAppName", out createdNew);

  if (!createdNew)
  {
    Console.WriteLine("You cannot start more than one instance of this program!");
    return;
  }

  Application.Run(new Form1());

  GC.KeepAlive(mutex);
}

It’s very important to use GC.KeepAlive(mutex), because you want to hold the mutex as long as your application is running. If you omit this, the Garbage Collector may free this resource, when more memory is needed and when you try to start another instance of your application, you will succeed. Another variant is to use static variable for the mutex, but the second way is preferable.

« Previous Entries