Search:

Custom Search
_________________________________________________________________

Saturday, July 24, 2010

Converting XML to String

In this short post I will show you how to convert XML to String, o viceversa, in order for example, to send it via Tcp/Ip.


In this example, a Client is going to genereta a XML Document and convert it to string.

The Server side must recive the string and generate the XML.

(Here you will not see how the communication is done, for example the convertion between string and stream)


Client Code:


XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(@"C:\XML\" + test + ".xml");


//Getting the Xml as String

String message = xmlDoc.InnerXml;

client.Send(message);


Server Code:


String innerXml = response;

XmlDocument xmlServer = new XmlDocument();


//Set the string to the Xml created above

xmlServer.InnerXml = innerXml;

Tuesday, July 20, 2010

More XML options in C#


Continuing the xml posts, in this oportunity I will show you more options to create your XmlDocument.

Here we will see:

- Adding comment to the xml document (XmlComment)

- Adding fragment (XmlDocumentFragment)

- Creation of attributes (XmlAttribute)

- Adding information about the document Type (XmlDocumentType)

- And also, declarations and elements


Code:


XmlDocument xmlDoc = new XmlDocument();


XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

xmlDoc.AppendChild(xmlDec);


XmlElement root = xmlDoc.CreateElement("root-element");


//Adding info about the document type

XmlDocumentType docType = xmlDoc.CreateDocumentType("BOOKS", null, null, null);

xmlDoc.AppendChild(docType);


XmlAttribute xmlAtt = xmlDoc.CreateAttribute("attribute");

xmlAtt.Value = "value_for_xmlAtt";

root.SetAttributeNode(xmlAtt);

xmlDoc.AppendChild(root);


//Placing a comment in the Xml

XmlComment xmlComment = xmlDoc.CreateComment("First Book information");

root.AppendChild(xmlComment);


XmlElement book1 = xmlDoc.CreateElement("book-1");

book1.SetAttribute("name", "Harry Potter");

root.AppendChild(book1);


//Creating a Fragment

XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();

xmlDocFragment.InnerText = "---------Inner text-------";

xmlDoc.DocumentElement.AppendChild(xmlDocFragment);


XmlElement book2 = xmlDoc.CreateElement("book-2");

book2.SetAttribute("name", "Robles");

root.AppendChild(book2);


xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");


Output:



Saturday, July 17, 2010

Xml document edition

In the previous post I showed you how to create a XmlDocument following some easy steps. The idea now is to read the created xml and find elements by a specific tag. Then we are going to change that value and save the edited xml.


Code:


For the first book element, we are going to add inner text:


XmlDocument xmlDoc = new XmlDocument();


//Load the Xml created previously

xmlDoc.Load(@"C:\XML\" + "xmlTest.xml");

XmlNodeList books;

books = xmlDoc.GetElementsByTagName("book-1");


//Since there is only one element with this tag, the loop is not necessary.

foreach (XmlNode node in books)

{

node.InnerText = "Great Book";

}


For the second element, we are changing the attributes values:


books = xmlDoc.GetElementsByTagName("book-2");

foreach (XmlNode node in books)

{

node.Attributes[0].Value = "Time";

}

xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");


Output:


Friday, July 16, 2010

Xml Document creation using DOM

In this article I´ll show you how to create a .xml document using proper tags and definitions. To do this you need to import the System.Xml library.

The idea is simple and the best way to learn this is by a small example.


Here I´ll create a XmlDocument with a couple of child elements.


Code:


XmlDocument xmlDoc = new XmlDocument();

//First, create the declaration


XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

xmlDoc.AppendChild(declaration);

XmlElement books = xmlDoc.CreateElement("BOOK");

xmlDoc.AppendChild(books);


//Child 1 for BOOK

XmlElement book1 = xmlDoc.CreateElement("book-1");

book1.SetAttribute("name", "Harry Potter");

books.AppendChild(book1);


//Child 2 for BOOK

XmlElement book2 = xmlDoc.CreateElement("book-2");

book2.SetAttribute("name", "People");

book2.SetAttribute("type", "magazine");

books.AppendChild(book2);


//Save the Xml

xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");


Output:


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: