Search:

Custom Search
_________________________________________________________________

Saturday, May 8, 2010

Split function in C#

Here is a small post about using split function in c#. We are going to split a String by using delimiters. A delimiter will tell when to split the string. So here is a fragment of code to perform splitting.

String answer = "This$is|a|string";

char[] delimitator1 = new char[] { '$' };

char[] delimitator2 = new char[] { '|' };

string[] words = answer.Split(delimitator1);

Console.WriteLine("First word : " + words[0]);

//Note that now we split the second part of the string

String allRest = words[1];

string[] rest1 = allRest.Split(delimitator2);

Console.WriteLine("Second word : " + rest1[0]);

Console.WriteLine("Third word : " + rest1[1]);

Console.WriteLine("Fourth word : " + rest1[2]);


Output:

Saturday, April 18, 2009

Get integer sequence primary key in C#

Here is a nice method of getting the primary key from a table. Basicly what I do here is obtanning the first available key to insert new rows with this obtained key.

First we set the instance of the connection with the database and then we create a sql command. After this, we open the connection and execute the command directly to the database.
If everything executes correctly, we will obtain the first available key. If not, an exception is going to be raised.

public int GetOid()

{

OleDbConnection conn = ConnectionMgr.GetInstance().GetConnection();

OleDbCommand cmd = new OleDbCommand("Select * From Oid", conn);

int oidNum = 0;

try

{

conn.Open();

oidNum = (int)cmd.ExecuteScalar();

oidNum++;

cmd = new OleDbCommand("UPDATE Oid SET lastOid=" + oidNum, conn);

cmd.ExecuteNonQuery();

}

catch (OleDbException ex)

{

throw new DatabaseException("Error updating oid", ex);

}

finally

{

conn.Close();

}

return oidNum;

}

Friday, November 28, 2008

Adding new line to a txt file in C# .Net

In this very short article I will show you the easiest way to add a new text line on a txt file using C# .NET.

I was researching on this matter very hard. First I started to read the entire file to the end and then add the new line. There is a small problem on doing this: it might work at compilation time but when you execute the application, you will see an error that says that two processes cannot run at the same time. Sound fair.
Then I started working with locks. There are a couple of locks, the lock when you read and the lock when you write. This is good stuff to talk later but not right now.

So what is the easiest solution to this matter, here it is:

public void AddNewLine(String text)
{
File.AppendAllText("C:\\Logs.txt", text + Environment.NewLine);
}

Yes, just like that.
And if you want to read the txt file, you could do something like this:

public String ReadAll() {

StreamReader sr = new StreamReader("C:\\Logs.txt");
String allText = sr.ReadToEnd();
return allText;

}

Saturday, August 30, 2008

Understanding Exceptions provided by the .NET Framework - Part 2.

You may saw in the previous post, a couple of exceptions we can use that are provided by the .Net Framework derived from the System.Exception class. Those two exceptions were: The StackOverflowException and the NullReferenceException.
Now I will describe to you the OutOfMemoryException and the DivideByZeroException.

The OutOfMemoryException

This exception is thrown by the CLR when your machine runs out of memory. Every time you create an object using new, some memory will be reserved for it. In case there is now enough memory, the exception will be triggered.
Let´s write an example now. Supose you want to create a Hashtable that allocated a large capacity. If there is no memory to do this, the CLR throws the exception.
Take a look at this C# example:

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

namespace ConsoleApplication5

{

class Program

{

static void Main(string[] args)

{

try

{

Hashtable hatb = new Hashtable(91230000);

}

catch (OutOfMemoryException)

{

Console.WriteLine("CLR out of memory");

}

}

}

}


Console:



The DivideByZeroException

This exception is quite simple: when you are dividing by 0, the CLR throws this exception.
Take a look at this example:

class Program

{

static void Main(string[] args)

{

int a = 5;

int b = 0;

try {

int res = a / b;

}

catch(DivideByZeroException){

Console.WriteLine("You are dividing by 0");

}

}

}



Console:

Friday, August 22, 2008

Understanding Exceptions provided by the .NET Framework - Part 1.

The NullReferenceException:

The easiest way to explain how this works is by writing an example. What we are going to do in the following example is quite simple: we are going to create an Object and initialize it with null value. This object contains string public value type that we can malipulate. But in this particulare case, our Object was set to null, so the CLR will catch this particular exception:


Class Person


public class Person

{

public String name;

}

Main:

static void Main(string[] args)

{

try

{

Person p = new Person();

p = null;

p.name = "CoderG";

}

catch (NullReferenceException) {

Console.WriteLine("p set tu null, cannot be referenced");

}

}

Console:


The StackOverflowException:


This exception is catch by the CLR when it runs out of stack memory. Be aware that the CLR has a finite amount of stack space, so if it gets full, the StackOverflowException will catch the exception. An easy way to trigger this is by defining a recursive function that does nothing, just call itself. Eventually, if the stack was infinite, this method will never stop, but because it is finite, the exception catches this:


Main:


static void Main(string[] args)

{

try

{

callMe();

}

catch (StackOverflowException) {

Console.WriteLine("Stack run out of memory!!!!");

}

}

public static void callMe(){

callMe();

}

Console:

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: