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.

Feb 5
Matrices
icon1 Boyan Mihailov | icon2 C# | icon4 02 5th, 2008| icon3No Comments »

I have constructed a class library to perform different operations with matrices. I was inspired by my university course of Linear Algebra. This library is still beta, so don’t wonder if you encounter a problem.

Introduction

In mathematics, a matrix is a rectangular table of numbers. Instead of using integers only, I have used my fraction class to represent numbers in the matrix. You can sum matrices, multiply them, determine their determinant and their rang, inverse & transpose them.

Initialization & General Usage

Here is a simple example of the usage of this library. I want to remark something: when you access an element of the matrix, you use a row & a column index. This indexes are not zero-based!

Matrix matrix = new Matrix(2, 2);
matrix[1, 1] = 1;
matrix[1, 2] = -3;
matrix[2, 1] = new Fraction(-2, 9);
matrix[2, 2] = new Fraction(1, 3);

Multiplication of two matrices

If you want to multiply two matrices, the number of columns of the first one must be equal to the number of rows the second one. Here is the algorithm of multiplication of two matrices.

public static Matrix operator *(Matrix lhs, Matrix rhs)
{
  Matrix result = new Matrix(lhs.Rows, rhs.Cols);
  Fraction rowByCol = new Fraction();

  for (int r = 1; r <= lhs.Rows; r++)
  {
    for (int c = 1; c <= rhs.Cols; c++)
    {
      for (int i = 1; i <= lhs.Cols; i++)
      {
        rowByCol += lhs[r, i] * rhs[i, c];
      }

      result[r, c] = rowByCol;
      rowByCol.Numerator = 0;
    }
  }

  return result;
}

And here is the simple usage.

Matrix matrix1 = new Matrix(2, 3);
Matrix matrix2 = new Matrix(3, 5);
Matrix mul = matrix1 * matrix2;

Solving a Matrix Equation

A matrix equation is an equation like Ax=b, where A, b and x are matrices. To solve such an equation, you have to find a matrix and when you multiply A by this matrix to get b. Solving a matrix equation uses the Gauss elimination method.

private void toEchelonForm(bool rowsBeginWithOne, bool full, int cols)
{
  int r = 1;
  int c = 1;
 
  Begin:
  this.rearrangeZeroRows(r, c);
 
  if (this[r, c] == 0)
  {
    c++;
    if (c < cols) goto Begin;
  }
  else
  {
    if (this[r, c] != 1 && rowsBeginWithOne)
      this.divideRowByNumber(r, this[r, c]);
 
    r++;
    this.setZeros(r, c);
    c++;
 
    if (r <= Rows && c <= cols) goto Begin;
  }
 
  if (full)
  {
    for (int i = Rows; i >= 1; i--)
      for (int j = cols; j >= 1; j--)
        if (this[i, j] == 1)
        {
          for (int k = i - 1; k >= 1; k--)
          if (this[k,j] != 0) this.addRowToRow(k, i, this[k, j] * (-1));
         
          break;
        }
  }
}

Matrix Equation

Matrix A = new Matrix(2, 2);
Matrix b = new Matrix(2, 1);
Matrix x = A.SolveEquation(b);

Other Features

You can invert a matrix (if it can be inverted), transpose a matrix, use the identity and zero matrices. Here are a few examples, which demonstrate that features.

Matrix matrix = new Matrix(4, 5);
// fill the matrix with numbers
Matrix transposition = matrix.Transpose();
Matrix inverse = matrix.Inverse();
Matrix identity = Matrix.Identity(4);
Matrix zero = Matrix.Zero(5);

Download

« Previous Entries