Archive for the ‘C#’ Category

How can universally unique primary keys can be generated ?

The generic solution is to generate a 32 digit key, encoded in hexadecimal composed as follows:
1: Unique down to the millisecond. Digits 1-8 are the hex encoded lower 32 bits of the System.DateTime.Now.Millisecond() call.
2: Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit integer of the underlying IP address.
3: Unique [...]

Reading and Writing Window Registry in C#

Since its introduction in Windows 95, the registry has more often than not intimidated developers. The registry acts as a central repository of information for the operating system and the applications on a computer. When you store information in the registry, choose the appropriate location based on the category of information being stored.
Here is how [...]

Indenting XML using C#

There are times when you need to display an XML string to be able to view in a good format.

// Pretty XML format with consistant indentation.

public static String prettyXMLPrint(String XML)
{
String Result = “”;

MemoryStream msStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(msStream , Encoding.Unicode);
XmlDocument xmlDocument = new XmlDocument();

try
{
// Load the XmlDocument with the [...]

Find out if an URL exists – C#

Trying to find out if the url is valid ? Use the following code:

public static bool urlExist(string url)
{
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse;
[...]

Generate a temporary file name on disk – C#

public static string getTemporaryFile(string extension)
{
string tempfile = String.Empty;

if (!extension.StartsWith(“.”))
[...]

Reading and Parsing XML Nodes – C#

The XmlTextReader provides a forward only mean of reading a specific XML node. The application reads each node of an XML document, determining along the way whether the current node is what is needed. This is typically accomplished by constructing an XmlTextReader object and then iteratively calling—within a loop—the XmlTextReader::Read method until that method returns [...]

How to: Create a File or Folder – C#

This example creates a folder and a subfolder on a computer.

// Specify a “currently active folder”
string activeDir = @”c:\testdir2″;

//Create a new subfolder under the current active folder
[...]

Random number always the same – C#

A typical mistake when creating random number in C# is to forget the static definition.
To make the C# random class work appropriately, make sure that the declaration of your random is static as follow.

using System;

class Program {

static void Main()
{
// Call method that uses [...]