Search:

Custom Search
_________________________________________________________________

Wednesday, August 6, 2008

Using destructors in C#

Destructors are similar to de Constructors, almost the oposite.
The destructor is used by the CLR when objects are destroyed.
All this process happens in the background so the developer does not have to preocupate about deleting
created objects. Writing a destructor is not necessary but if you are going to create one in your class,
you can only add one.
The Destructors sintaxis are very similar to the constructors.
They start with the simbole ~ and the name must be the same to the class.
Also, there are a few particulares things about destructors you should know:
-No parameters are allowed here.
-As said before, you can only write one.
-You can not call a constructor like you will normally do with a method. They are automatically used by the CLR (by the garbage collection).
-No overload or inheritances are allowed.
So let’s write a small C# class.

-Class Plane

using System;
using System.Text;

class Plane
{

public String type;
public String company;

public Plane(String t, String c){
type = t;
company = c;

Console.WriteLine("Constructor in action\n");

}

~Plane() {
type = "N/A";
company = "N/A";

Console.WriteLine("Destructor in action");
}

}

- Main

static void Main(string[] args)
{

Plane p = new Plane("AirBus", "Tam");

}

- Console

Monday, August 4, 2008

Defining methods in Structures (C#)

Normally you will see structures with only variables on it, but methods can also be included. This is usefull when you need to write a method that works directly with the content of the stuct.

- The first method that I will create inside the structure is a constructor. Remember that there can be many constructores as long as the parameter list is different of each other.
- The second method you will see next is a simple bool method that return true if both values of the structure varaibles (integers) are 50.

Ok, lets now proceed to write this example.

using System;

class Program
{

struct Point {

public int x;
public int y;

public Point(int x1, int y1) {

x = x1;
y = y1;
}

public bool check50() {

if ((x == 50) && (y == 50))
return true;

return false;

}
}

Main:

static void Main(string[] args)
{

Point p = new Point(50 , 50);
Point p2 = new Point(10, 20);

if (p.check50())
Console.WriteLine("Point p is at 50s");

else
Console.WriteLine("Point p not at 50s");

if(p2.check50())
Console.WriteLine("Point p2 is at 50s");

else
Console.WriteLine("Point p2 not at 50s");
}
}

Console:

Thursday, July 31, 2008

Implementing Interfaces in C#

Interfaces are a set of methods, properties and event that provides functionalities. This interces can be implemented by C# classes or structures.

Interfaces do not provide methods of their own. They only contain methods identifiers, return values and parameters.
This is very useful when you have certain behaviour that need to follow a set of operations, such as manipulating a Data Base.
C# classes are allowed to implement many interfaces.

Implementing an Interfaz in a class says that the class must provide implementation to all of the methods signatures from the interface.

Let’s write a small C# example. In this example you will see of to implement interfaces that contain methods signatures and how a class implements this interface.

Code:

interface Interface1
{

void Method1();
void Method2();

}

public class Class1 : Interface1
{

public void Method1()
{

//Implementation of the method
}

public void Method2() { }

}

Now, you can also use interfaces that the .NET Frameworks has. In this example you will see how to implement the Idisposable interface. The Idisposable interface supports a method called Dispose(). It also supports a constructor and a destructor.

Also you will see in the Main class, the keyword using. It is used to create a new object and can be manipulated only within the braces ({}). After the close brace is reached, the object will be automatically destroyed.

Code:

class Class2 : IDisposable
{

public Class2()
{

Console.WriteLine("Constructor");
}

~Class2()
{

Console.WriteLine("Destuctor");
}

public void Dispose()
{

Console.WriteLine("Dispose from IDisposable.Dispose");
}

}


Main:

class Program
{

static void Main(string[] args)
{

using (Class2 myC = new Class2()) { }
}
}

Console:


Thursday, July 17, 2008

MessageBox using AbortRetryIgnore Button in C#

This example is very similar to the previous one where I showed you how to write an example using the YesNo MessageBox. Here the only difference is that the MessageBox is with the AbortRetryIgnore Button.

Ok, now I will proceed to write a small example of this. Basicly what I want to do here is to distinguish between the three different types of buttons that this type of MessageBox contains. Here I will use a swith statment because I find it a little more correct.
So the complete C# code is this:


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

private void button1_Click(object sender, EventArgs e)

{

DialogResult result;

result = MessageBox.Show("The Cd drive is not ready. \nReinsert and try again!", "Error on Drive", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);

switch (result)

{

case DialogResult.Abort:

MessageBox.Show("Abort Selected");

break;

case DialogResult.Retry:

MessageBox.Show("Retry Selected");

break;

case DialogResult.Ignore:

MessageBox.Show("Ignore Selected");

break;

default:

break;

}

}


Result when executing:

Friday, June 27, 2008

MessageBox using YesNo Button


With the previous post you could see that MessageBox class is very powerful and contains a lot of options for the static method Show. Now we will see in more detail how to implement the functionalities of a Dialog containing a YesNo Button.

When you give the user that option, it is obvious that the behavior of the Yes Button must be different from the No so you must set this.

Let's proceed to write an example. This C# code example has basicly 2 functions: when the Dialog popus up, the user must select between the Yes or No options. If the Yes is selected, the application exits. If the No button is clicked, a Dialog will appear. So here is the code:


private void button1_Click(object sender, EventArgs e)
{

DialogResult result;
result = MessageBox.Show("Are you sure you want to exit?", "Application 1", MessageBoxButtons.YesNo);
if (result == DialogResult.No) {
MessageBox.Show("App won´t close");
}
if (result == DialogResult.Yes) {
this.Dispose();
}
}

If there are more options that the user can choose from, a switch statment could be a better option:


witch (result)
{
case DialogResult.No:
MessageBox.Show("App won´t close");
break;
case DialogResult.Yes:
this.Dispose();
break;
default:
break;
}

Result when executing:



MessageBox Tuning in C#

MessageBox class is used when you want to show some kind of information or when the application needs user intervention.
This class contains static methods that help to interactuate with users. All you have to do is set the correct parameters of the show method. Some are: title, a proper message, icons, botons, quantities and more.

The show method returns a DialogResult type value that will need to be evaluated in order to make future actions, for example, open another dialog window.

Let’s look at some examples now:

I´ll start by creating a Windows From. Next, I´ll add 5 Buttons controls to the form and create a click event for all of them. On the click event method I created different messageBoxs for each one. Let’s analize them:

-For the button0, the code line is:

MessageBox.Show(this, "Hello", "Title Button0");

Nothing really complicated here. This creates a simple dialog with the text Hello, owner this and title Title Button0.

-For the button1, the code line is:

MessageBox.Show("Abort, Retry, Ignore example", "Title 1", MessageBoxButtons.AbortRetryIgnore);


This is a little more interesting. We indicated here that the title would be Title 1, the message Abort, Retry, Ignore example and the Button for this specific dialog is the AbortRetryIgnore Button, the same one you see in most windows applications.

-For the button2, the code line is:

MessageBox.Show(this, "Error on button2, Continue?" , "Title2", MessageBoxButtons.YesNo , MessageBoxIcon.Error);


This is very similar to the previus one: Owner this, title Title2, message Error on button2, Continue? , Button YesNo and Icon Error. This will create a dialog that contains both options Yes and No, and also an Error Icon located left of the message will appear.

-For the button3, the code line is:

MessageBox.Show("Warning", "Button3 Title", MessageBoxButtons.OK, MessageBoxIcon.Warning);

Similar to the others but now the Button is the Ok button and the Icon Warning will apear. So the purpose of this is to indicate an error, warning or a message that the user must see and give the only option of clicking the OK button.

-For the button4, the code line is:

MessageBox.Show(this, "Warning", "Button4 title", MessageBoxButtons.RetryCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button3);


Here the Button is the usual RetryCancel, the Icon Asterisk and the DefautlButton indicated to Button3. This defines the constat button.

Thursday, June 19, 2008

Writing Registry keys

We saw before how to read a registry key. Writing is similar and also accomplished by the RegistryKey object. C# .Net provides very easy methods under this object to write keys.

Be aware that the registry is a key part of an Operating System so you should know exactly what you are doing before actually doing it. Check every single line of the code written. On this example I’ll show you below, I will create a couple of keys with its proper folder too. By doing this I can be sure that any other registry key would be overwritten.

Take a look now at this example:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace WritingRegKeys
{
class Program
{
static void Main(string[] args)
{

RegistryKey RegKeyWrite = Registry.CurrentUser;
RegKeyWrite = RegKeyWrite.CreateSubKey
("Software\\MySoftware\\SubKeys");
RegKeyWrite.SetValue("Try", "True");
RegKeyWrite.SetValue("NumberValue", 1);

RegKeyWrite.Close();

RegistryKey RegKeyRead = Registry.CurrentUser;
RegKeyRead = RegKeyRead.OpenSubKey("Software\\MySoftware\\SubKeys");
Object regTry = RegKeyRead.GetValue("Try");
Object regNumber = RegKeyRead.GetValue("NumberValue");
RegKeyRead.Close();
Console.WriteLine("Try value: " + (String)regTry + " - - NumberValue: " + regNumber);

}
}
}

You can see that after creating the RegistryKey object I also created a subkey with the CreateSubKey method. This will generate another “subfolder” under MySoftware.

The Complete root is: HKEY_CURRENT_USER\Software\MySoftware\SubKeys.

With the RegKeyWrite.SetValue you have to specify the name of that key and the actual values you want to be stored. You can see that the fist value to be stored is a String and the second a Numeric value.

You can try this by reading the keys created above. That why the RegKeyRead Object is also created. Then we just open the SubKey and ask the values for the Try key and the NumberValue key. Run the code and the Console should look something like this:

When you execute the code, a new registry should be created. So let’s take a look at the registry to see if this is true. Open regedit to see the changes.


Saturday, June 7, 2008

Accessing the Registry for reading keys in C#

C# contains class object that make the job of manipulating the registry very easy.
Also, the registry is indexed that make much faster the reading job.

Ok, let’s now proceed to read from the registry.
First you need to make the import of the Microsoft.Win32 namespace that contains the registry access functions.
The second important thing you need to use RegistryKey object to make the actual reading.

Let’s now write a small piece of code to see how this works.

using System;
using System.Text;
using Microsoft.Win32;

namespace RegRead
{

class Program
{

static void Main(string[] args)
{


//Example 1
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(
"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\1");
Object cpuName = RegKey.GetValue("ProcessorNameString");
Console.WriteLine("Your CPU name is:" + cpuName);

Console.WriteLine("");

//Example 2
RegistryKey RegKey2 = Registry.CurrentUser;
RegKey2 = RegKey2.OpenSubKey("Printers");
Object printerName = RegKey2.GetValue("DeviceOld");
Console.WriteLine("Your Printer name is: " + printerName);

Console.Read();
}
}
}


The first thing you need to do is to import the Microsoft.Win32 namespace.
Then, if you look at the definition of the instance of the RegistryKey object, you will see that it is pointing to Local Machine, which means that the HKEY_LOCAL_MACHINE folder will be enable for reading.

(To open the Registry editor just go to start->Run: regedit).
After this step, we simple need to find the folders/subfolders where the key is located and read it.

The second example is pretty much the same. The only major difference is that the
HKEY_CURRENT_USER folder will be available.