Monday, April 8, 2013
Firefox postback twice problem
Removing this will solve the problem.
Monday, February 18, 2013
C# Not Null Value From Table Row
public class NotNullValueFromTableRow
{
private DataRow dr;
public NotNullValueFromTableRow(DataRow dataRow)
{
dr = dataRow;
}
public object get<T>(string ColumnName)
{
if (dr.Table.Columns.Contains(ColumnName))
if (dr[ColumnName] != DBNull.Value)
{
if (typeof(T) == typeof(string))
return dr[ColumnName].ToString();
return (T)dr[ColumnName];
}
if (typeof(T) == typeof(string))
return string.Empty;
return default(T);
}
}
Example:
DataRow dRow = dt.Rows[0];
NotNullValueFromTableRow notNull = new NotNullValueFromTableRow(dRow);
string Address = (string)notNull.get<string>("ClientAddress");
Monday, January 7, 2013
var type (C#)
http://msdn.microsoft.com/en-us/library/bb383973.aspx
Monday, August 13, 2012
Access GUI from background thread using C# Forms
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Threads
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
delegate void SetTextCallback(string text, int value);
private void Form1_Load(object sender, EventArgs e)
{
ThreadTest t = new ThreadTest(this);
Thread th = new Thread(t.DoWork);
th.Start();
//th.Join();
}
public void Populate(string text, int value)
{
if (this.lblMesaj.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(Populate);
this.Invoke(d, new object[] { text,value });
this.Invoke(d, new object[] { text,value });
}
else
{
this.lblMesaj.Text = text;
this.progressBarFinalize.Value = value;
}
lblMesaj.Text = text;
}
private void btnSave_Click(object sender, EventArgs e)
{
this.Close();
}
}
class ThreadTest
{
public delegate void populateTextBoxDelegate(string text);
Form1 formMain;
public ThreadTest(Form1 form)
{
formMain = form;
}
public void DoWork()
{
for (int i = 0; i < 1000; i++)
{
formMain.Populate("In progress ....", i/10);
for (int j = 0; j < 1000; j++)
{
for (int k = 0; k < 100; k++)
{
double b = Math.Sqrt(923409290423) / Math.Sqrt(423423);
}
}
}
formMain.Populate("Thread has finished!",100);
}
}
}
Monday, August 6, 2012
Generate Random String c#
{
Random rng = new Random();
string _chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZqwertyuiopplkjhgfdsazxcvbnm1234567890";
int size = rng.Next(8,12);
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[rng.Next(_chars.Length)];
}
return new string(buffer);
}
Friday, June 15, 2012
BackTracking c#
{
static int[] a;
static int k;
static int SIZE = 4;
static void Main(string[] args)
{
a = new int[20];
bkp();
System.Console.ReadLine();
}
static void bkp()
{
k = 1;
a[k] = 0;
bool getSuccesor;
while (k > 0)
{
do
{
getSuccesor = HaveSuccesor();
}
while (getSuccesor && !IsValid());
if (getSuccesor)
{
if (IsValidSolution())
{
ShowSolution();
}
else
{
k++;
a[k] = 0;
}
}
else
{
a[k] = 0;
k--;
}
}
}
static bool HaveSuccesor()
{
if (a[k] < SIZE)
{
a[k]++;
return true;
}
else
return false;
}
public static bool IsValid()
{
if (k > 1)
if (a[k] < a[k - 1]) return false;
for (int i = 1; i < k; i++)
if (a[i] == a[k]) return false;
return true;
}
public static bool IsValidSolution()
{
if(k==SIZE) return true;
return false;
}
static void ShowSolution()
{
for (int i = 1; i < = SIZE; i++)
System.Console.Write(a[i] + " ");
System.Console.Write(Environment.NewLine);
}
static void ShowTowers()
{
for (int i = 1; i < = SIZE; i++)
{
for (int j = 1; j < = SIZE; j++)
{
if(a[i]==j)
System.Console.Write("T");
else
System.Console.Write("*");
}
System.Console.Write(Environment.NewLine);
}
System.Console.Write(Environment.NewLine);
}
}
}
Monday, May 28, 2012
private void CopyFile(string file)
{
WebRequest req = WebRequest.Create(@"http:....." + file);
req.Proxy = new WebProxy("1.1.1.1", 8080);
req.Proxy.Credentials = new NetworkCredential(@"user", "pass");
WebResponse responsePic = req.GetResponse();
Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error
webImage.Save(@"D:\\pictures\" + file);
}
Wednesday, January 4, 2012
C# - Serialize/Deserialize object
{
string serObj = null;
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, rspJ);
serObj = Convert.ToBase64String(ms.ToArray());
return serObj;
}
public static string SerObjXML(object rspJ, Type type)
{
string serObj = null;
MemoryStream ms = new MemoryStream();
XmlSerializer bf1 = new XmlSerializer(type);
bf1.Serialize(ms, rspJ);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
serObj = sr.ReadToEnd();
return serObj;
}
public static object DeSerObjXML(string xml, Type type)
{
XmlSerializer xs = new XmlSerializer(type);
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return xs.Deserialize(memoryStream);
}
public static RspTestXML DeSerObj(string stringObj)
{
RspTestXML rspTestXML = null;
byte[] theByteArray = Convert.FromBase64String(stringObj);
MemoryStream ms1 = new MemoryStream(theByteArray);
BinaryFormatter bf11 = new BinaryFormatter();
ms1.Position = 0;
rspTestXML = (RspTestXML)bf11.Deserialize(ms1);
return rspTestXML;
}
private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
Friday, July 29, 2011
ReadOnly textbox loose changed information
Solution:
1. Dont assign readonly property=true in design mode.
2. Bind the readonly property from serverside page load event like:
Thursday, May 26, 2011
Format ToString Nullable DateTime
Saturday, December 18, 2010
c# format date
Friday, December 3, 2010
CNP validation
CNP - Cod Numeric Personal
Codul Numeric Personal constituie numarul de ordine atribuit de Evidenta Populatiei unui individ la nastere.Conform articolului 5 din Legea nr.105 din 25 septembrie 1996 privind evidenta populatiei si cartea de identitate, fiecarei persoane fizice i se atribuie, incepand de la nastere, un cod numeric personal care se inscrie in actele si certificatele de stare civila si se preia in celelalte acte cu caracter oficial, emise pe numele persoanei respective, precum si in Registrul permanent de evidenta a populatiei.
Codul numeric personal reprezinta un numar semnificativ ce individualizeaza o persoana fizica si constituie singurul identificator pentru toate sistemele informatice care prelucreaza date nominale privind persoana fizica.
Gestionarea si verificarea atribuirii codului numeric personal revine Ministerului de Interne, prin formatiunile de evidenta a populatiei.
Pentru persoanele fizice romane cu domiciliul in Romania codul de identificare fiscala este codul numeric personal atribuit de Ministerul de Interne.Persoanele fizice straine si persoanele fizice romane fara domiciliu in Romania vor beneficia de numar de identificare fiscala (NIF).
Un CNP este alcatuit astfel :
|S| |AA| |LL| |ZZ| |JJ| |ZZZ| |C|
|_| |__| |__| |__| |__| |___| |_|
: : : : : : :
: : : : : : :
: : : : : : --> Cifra de control
: : : : : :
: : : : : --> Numarul de ordine atribuit persoanei
: : : : :
: : : : --> Codul judetului
: : : :
: : : --> Ziua nasterii
: : :
: : --> Luna nasterii
: :
: --> Anul nasterii
:
--> Cifra sexului (M/F) pentru:
1/2 - cetateni romani nascuti intre 1 ian 1900 si 31 dec 1999
3/4 - cetateni romani nascuti intre 1 ian 1800 si 31 dec 1899
5/6 - cetateni romani nascuti intre 1 ian 2000 si 31 dec 2099
7/8 - rezidenti
Persoanele de cetatenie straina se identifica cu cifra "9"
Algoritmul de validare al unui cod CNP
Pas preliminar: Se testeaza daca codul respecta formatul unui cod CNP. Adica prima cifra sa fie cuprinsa in intervalul 1 - 6 sau sa fie 9 pentru straini. Urmatoarele sase cifre trebuie sa constituie o data calendaristica valida in formatul AALLZZ.Pas 1: Se foloseste cheia de testare "279146358279". Primele douasprezece cifre se inmultesc pe rand de la stanga spre dreapta cu cifra corespunzatoare din cheia de testare.
Pas 2: Cele douasprezece produse obtinute se aduna si suma obtinuta se imparte la 11.
- Daca restul impartirii la 11 este mai mic ca 10, atunci acesta va reprezenta cifra de control.
- Daca restul impartirii este 10 atunci cifra de control este 1.
Monday, November 8, 2010
Install .NET Service
Run InstallUtil.exe from the command line with your project's output as a parameter. Enter the following code on the command line:
Thursday, October 21, 2010
Read from WebConfig
< appSettings >
< add key="ROOT_TEMP" value="\\dir\" / >
cs CODE
using System.Configuration;
public string ROOT_TEMP = ConfigurationManager.AppSettings["ROOT_TEMP"].ToString();
Tuesday, March 16, 2010
Transform xml with xsl
using System.IO;
using System.Xml;
using System.Xml.Xsl;
namespace Microsoft.Samples.Xml
{
public class TransformXMLSample
{
private const string document1 = @"..\..\books.xml";
private const string document2 = @"..\..\ProcessParametersA.xml";
private const string document3 = @"..\..\ProcessParametersB.xml";
private const string styleSheet1 = @"..\..\books.xsl";
private const string styleSheet2 = @"..\..\StyleSheetGenerator.xsl";
private const string output1 = @"..\..\table.html";
private const string output2 = @"..\..\transform2.xsl"; //linked by books-t2.xml
private const string output3 = @"..\..\transform3.xsl"; //linked by books-t3.xml
/**
add to books.xml to view transform using transform2.xsl
add to books.xml to view transform using transform3.xsl
**/
public static void Main()
{
TransformXMLSample transformXMLSample = new TransformXMLSample();
Console.WriteLine("\n\n*********Output from the first transform:*********\n\n");
String[] args1 = {document1, styleSheet1,output1};
transformXMLSample.Run(args1);
Console.WriteLine("\n\n*********Output from the second transform:*********\n\n");
String[] args2 = {document2, styleSheet2,output2};
transformXMLSample.Run(args2);
Console.WriteLine("\n\n*********Output from the third transform:*********\n\n");
String[] args3 = {document3, styleSheet2,output3};
transformXMLSample.Run(args3);
Console.Write("Press Enter to Exit");
Console.ReadLine();
}
public void Run(String[] args)
{
Console.WriteLine();
Console.WriteLine("Read XML data file, transform and format display ...");
Console.WriteLine();
ReadTransform(args);
Console.WriteLine();
Console.WriteLine("Read XML data file, transform and write ...");
Console.WriteLine();
ReadTransformWrite(args);
Console.WriteLine();
}
public void ReadTransform(String[] args)
{
XslCompiledTransform processor = new XslCompiledTransform();
processor.Load(args[1]);
//Transform the file.
processor.Transform(args[0], null, Console.Out);
}
public void ReadTransformWrite(String[] args)
{
using (FileStream stream = File.Open(args[2], FileMode.Create))
{
//Create XsltCommand and compile stylesheet.
XslCompiledTransform processor = new XslCompiledTransform();
processor.Load(args[1]);
//Transform the file.
processor.Transform(args[0], null, stream);
}
}
}
}
Validate xml with xml Schema
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Microsoft.Samples.Xml
{
class XmlSchemaValidatorSample
{
static string document = @"..\..\books.xml";
static string xsdDocument = @"..\..\books.xsd";
public static void Main(){
XmlSchemaInfo schemaInfo = new XmlSchemaInfo();
XmlSerializer serializer = null;
Books myBooks = null;
using (TextReader reader = new StreamReader(document))
{
serializer = new XmlSerializer(typeof(Books));
myBooks = (Books)serializer.Deserialize(reader);
}
XmlSchemaValidator xsv = CreateValidator();
xsv.Initialize();
xsv.ValidateElement("books", "http://www.example.com/my-bookshelf",
schemaInfo);
xsv.ValidateEndOfAttributes(schemaInfo);
foreach (BookType book in myBooks.book)
{
xsv.ValidateElement("book", "http://www.example.com/my-bookshelf",
schemaInfo);
if (book.publisher != null)
{
xsv.ValidateAttribute("publisher", string.Empty, book.publisher, schemaInfo);
}
if (book.onloan != null)
{
xsv.ValidateAttribute("on-loan", string.Empty, book.onloan, schemaInfo);
}
xsv.ValidateEndOfAttributes(schemaInfo);
xsv.ValidateElement("title", "http://www.example.com/my-bookshelf", schemaInfo);
xsv.ValidateEndElement(null, book.title);
xsv.ValidateElement("author", "http://www.example.com/my-bookshelf", schemaInfo);
xsv.ValidateEndElement(null, book.author);
xsv.ValidateElement("publication-date", "http://www.example.com/my-bookshelf", schemaInfo);
xsv.ValidateEndElement(null, book.publicationdate);
xsv.ValidateEndElement(schemaInfo);
}
xsv.ValidateEndElement(schemaInfo);
xsv.EndValidation();
Console.WriteLine("Schema validated.");
Console.WriteLine();
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}
static XmlSchemaValidator CreateValidator()
{
NameTable nt = new NameTable();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("http://www.example.com/my-bookshelf", xsdDocument);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
XmlSchemaValidationFlags flags = XmlSchemaValidationFlags.None;
return new XmlSchemaValidator(nt, schemaSet, nsmgr, flags);
}
}
Convert String to XML - .NET/C#
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
doc.Save("SSML.xml");
Reading and writing XML with c#
First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa.
Introduction to Microsoft .NET XML Namespaces and Classes
Before start working with XML document in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library.
.NET provides five namespace
- System.Xml,
- System.Xml.Schema-
- System.Xml.Serialization
- System.Xml.XPath
- System.Xml.Xsl
to support XML classes.
The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes.
The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example.
The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas.
The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example.
The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects.
In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList.
Next namespace in Xml series is System.Xml.Schema. It classes to work with XML schemas such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType.
The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams.
The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation though XML documents. This class contains many Move methods to move through a document.
The System.Xml.Xsl namespace contains classes to work with XSL/T transformations.
Reading XML Documents
In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line:
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
Or you can use any XML file.
The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor.
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber an so on.
List 1 reads a document and displays a node information using these properties.
About Sample Example 1
In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output.
Sample Example 1.
using System;
using System.Xml;
namespace ReadXml1
{
class Class1
static void Main(string[] args)
{
//Create an instance of XmlTextReader and call Read method to read the file
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
textReader.Read();
// If the node has value
while (textReader.Read())
{
// Move to fist element
textReader.MoveToElement();
Console.WriteLine("XmlTextReader Properties Test");
Console.WriteLine("===================");
Console.WriteLine("Name:" + textReader.Name);
Console.WriteLine("Base URI:" + textReader.BaseURI);
Console.WriteLine("Local Name:" + textReader.LocalName);
Console.WriteLine("Attribute Count:" +
textReader.AttributeCount.ToString());
Console.WriteLine("Depth:" + textReader.Depth.ToString());
Console.WriteLine("Line Number:" +
textReader.LineNumber.ToString());
Console.WriteLine("Node Type:" +
textReader.NodeType.ToString());
Console.WriteLine("Attribute Count:" +
textReader.Value.ToString());
}
}
}
}
The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on.
List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has.
About Sample Example 2
In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document.
Sample Example 2.
using System;
using System.Xml;
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
int ws = 0;
int pi = 0;
int dc = 0;
int cc = 0;
int ac = 0;
int et = 0;
int el = 0;
int xd = 0;
// Read a document
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
// Read until end of file
while (textReader.Read())
{
XmlNodeType nType = textReader.NodeType;
// If node type us a declaration
if (nType == XmlNodeType.XmlDeclaration)
{
Console.WriteLine("Declaration:" + textReader.Name.ToString());
xd = xd + 1;
}
// if node type is a comment
if (nType == XmlNodeType.Comment)
{
Console.WriteLine("Comment:" + textReader.Name.ToString());
cc = cc + 1;
}
// if node type us an attribute
if (nType == XmlNodeType.Attribute)
{
Console.WriteLine("Attribute:" + textReader.Name.ToString());
ac = ac + 1;
}
// if node type is an element
if (nType == XmlNodeType.Element)
{
Console.WriteLine("Element:" + textReader.Name.ToString());
el = el + 1;
}
// if node type is an entity\
if (nType == XmlNodeType.Entity)
{
Console.WriteLine("Entity:" + textReader.Name.ToString());
et = et + 1;
}
// if node type is a Process Instruction
if (nType == XmlNodeType.Entity)
{
Console.WriteLine("Entity:" + textReader.Name.ToString());
pi = pi + 1;
}
// if node type a document
if (nType == XmlNodeType.DocumentType)
{
Console.WriteLine("Document:"+textReader.Name.ToString());
dc = dc + 1;
}
// if node type is white space
if (nType == XmlNodeType.Whitespace)
{
Console.WriteLine("WhiteSpace"+textReader.Name.ToString());
ws = ws + 1;
}
}
// Write the summary
Console.WriteLine("Total Comments:" + cc.ToString());
Console.WriteLine("Total Attributes:" + ac.ToString());
Console.WriteLine("Total Elements:" + el.ToString());
Console.WriteLine("Total Entity:" + et.ToString());
Console.WriteLine("Total Process Instructions:"+pi.ToString());
Console.WriteLine("Total Declaration:" + xd.ToString());
Console.WriteLine("Total DocumentType:" + dc.ToString());
Console.WriteLine("Total WhiteSpaces:" + ws.ToString());
}
}
}
Writing XML Documents
XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents. This class has several Writexxx method to write every type of item of an XML document. For example, WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndElement are some of them. Some of these methods are used in a start and end pair. For example, to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.
Besides many methods, this class has three properties. WriteState, XmlLang, and XmlSpace. The WriteState gets and sets the state of the XmlWriter class.
Although, it's not possible to describe all the Writexxx methods here, let's see some of them.
First thing we need to do is create an instance of XmlTextWriter using its constructor. XmlTextWriter has three overloaded constructors, which can take a string, stream, or a TextWriter as an argument. We'll pass a string (file name) as an argument, which we're going to create in C:\ root.
In my sample example, I create a file myXmlFile.xml in C:\\ root directory.
// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null) ;
After creating an instance, first thing you call us WriterStartDocument. When you're done writing, you call WriteEndDocument and TextWriter's Close method.
textWriter.WriteStartDocument();
textWriter.WriteEndDocument();
textWriter.Close();
The WriteStartDocument and WriteEndDocument methods open and close a document for writing. You must have to open a document before start writing to it. WriteComment method writes comment to a document. It takes only one string type of argument. WriteString method writes a string to a document. With the help of WriteString, WriteStartElement and WriteEndElement methods pair can be used to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute.
WriteNode is more write method, which writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write a ProcessingInstruction and DocType items of a document.
//Write the ProcessingInstruction node
string PI= "type='text/xsl' href='book.xsl'"
textWriter.WriteProcessingInstruction("xml-stylesheet", PI);
//'Write the DocumentType node
textWriter.WriteDocType("book", Nothing, Nothing, "");
The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 5-14. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter:
After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter.
About Sample Example 3
In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items.
Sample Example 3.
using System;
using System.Xml;
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);
// Opens the document
textWriter.WriteStartDocument();
// Write comments
textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
textWriter.WriteComment("myXmlFile.xml in root dir");
// Write first element
textWriter.WriteStartElement("Student");
textWriter.WriteStartElement("r", "RECORD", "urn:record");
// Write next element
textWriter.WriteStartElement("Name", "");
textWriter.WriteString("Student");
textWriter.WriteEndElement();
// Write one more element
textWriter.WriteStartElement("Address", "");
textWriter.WriteString("Colony");
textWriter.WriteEndElement();
// WriteChars
char[] ch = new char[3];
ch[0] = 'a';
ch[1] = 'r';
ch[2] = 'c';
textWriter.WriteStartElement("Char");
textWriter.WriteChars(ch, 0, ch.Length);
textWriter.WriteEndElement();
// Ends the document.
textWriter.WriteEndDocument();
// close writer
textWriter.Close();
}
}
}
Using XmlDocument
The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article.
Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter.
About Sample Example 4
This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file.
Sample Example 4.
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(("
ex
//Save the document to a file.
doc.Save("C:\\std.xml");
You can also use Save method to display contents on console if you pass Console.Out as a
arameter. For example:
doc.Save(Console.Out);
About Sample Example 5
Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method argument displays data on the console
Sample Example 5.
XmlDocument doc = new XmlDocument();
//Load the the document with the last book node.
XmlTextReader reader = new XmlTextReader("c:\\books.xml");
reader.Read();
// load reader
doc.Load(reader);
// Display contents on the console
doc.Save(Console.Out);
Writing Data from a database to an XML Document
Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document.
The DataSet class provides method to read a relational database table and write this table to an XML file. You use WriteXml method to write a dataset data to an XML file.
In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query.
About Sample Example 6
In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter.
In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir.
Sample Example 6.
using System;
using System.Xml;
using System.Data;
using System.Data.OleDb;
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
// create a connection
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";
// create a data adapter
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);
// create a new dataset
DataSet ds = new DataSet();
// fill dataset
da.Fill(ds, "Customers");
ds.WriteXml("C:\\OutputXML.xml");
}
}
}
Random numbers with c#
Without further ado, I present you what is needed in order to generate a random number in C#:
Random randNum = new Random();
randNum.Next();
That's all it takes. The creation of a Random object (of the System.Random class) and calling its Next() method, which is going to return a non-negative random number as an integer.
Random Numbers Within a RangeAs soon as you test the code above, you realize it returns a quite large number. However, most of the time you'll want to generate a number between a desired range. For instance if in your contest 108 people participated, you'll want to generate a random no larger than 108:
Random randNum = new Random();
randNum.Next(108); // No larger than 108
This will generate you a positive number of up to 108, including 108. However in certain situations (such as picking the contest winner), you'll want the number to be 1 to 108, while the code above returns a number that is 0 to 108. Since people would probably not take kindly to you announcing that the winner is participant number 0, thanks to another overload of the Next() function, you will be able to specify a minimum value, as such:
Random randNum = new Random();
randNum.Next(1, 108); // No larger than 108, no smaller than 1
Using SeedsC++ programmers and others may wonder what happened to the seed. Who's seeding this random number because you sure aren't? Well, in the default constructor of the Random() object that we've seen above, where no parameter was specified, a seed will be automatically generated for you based on the current system time (which should always be unique.) Not having to specify the system time yourself as a parameter is very convinient, since the great majority of programmers would do that when generating random numbers.
However, there are advantages to specifying your own seed. One important thing to note is that for as long as you specify the same seed, you will get the same random number. Let's look at an example:
Random randNum = new Random(1986);
randNum.Next(); // This will always generate 564610494
Here we specify a seed, more exactly the number 1986, in order to generate a random number based on that seed. However, what is the point of using this, when it always generates the same number? Check this out:
Random randNum = new Random(1986);
randNum.Next(); // This will always generate 564610494
randNum.Next(); // This will always generate 1174029081
randNum.Next(); // This will always generate 2057658224
The interesting concept behind this is that each time you apply the Next() method, it will come up with a different number, so more exactly you will get a sequence of random numbers, but since they're based on the same seed, whenever you use that seed again, you are guaranteed to get the same random numbers. Thus if we create a new Random object and pass the 1986 value, get some random values, then create another Random object and pass the same 1986 value as the seed, the same random numbers will be retrieved in the exact same sequence . I'm not going to get very deep into explaining this, but it's not hard to imagine where you would need this, and when you will need this (if ever), you'll know it.
Double-Precision Numbers Sometimes you may want to generate double-precision numbers, and C# has a method for that. Instead of using Next(), the NextDouble() method will return a number between 0 and 1:
Random randNum = new Random();
randNum.NextDouble();
randNum.NextDouble();
randNum.NextDouble();
This will generate numbers such as 0.12820489450164194, 0.81203657295197121 and 0.0582018419231087554.
Now if you picked into IntelliSense, you've probably noticed a new method:
Array of Random BytesThe NextBytes() method will fill an array of bytes with random bytes. Thus, each element of the array will be a byte with a value of 0 to 255:
byte[] randBytes = new byte[108];
Random randNum = new Random();
randNum.NextBytes(randBytes);
This code would produce an array with values as such: 196 231 77 225 52 144 146 72 3 90 18 233 161 205 147 196 35 152 30 220 41 114 156 25 184 185 30 64 140 138 215 62 178 90 158 94 0 47 101 234 151 44 71 189 146 113 111 90 3 93 59 104 91 143 81 82 75 51 40 123 113 81 188 121 130 212 55 71 47 52 195 243 50 52 68 252 42 222 135 70 74 196 61 46 79 111 227 34 8 75 19 205 6 234 120 70 112 206 58 190 58 39 42 206 153 71 53 38. But of course, since we don't specify a seed and the current system time is being used, you'll get a different set of values.
That's all for random numbers using C#.
Arrays in c#
Static Arrays
Arrays can be declared in many ways. These first examples demonstrate arrays that are created at "design time" – (programmer sets the value(s) and length). This array is "hard coded". Hard coded means that the values and length of the array are established at the time the array is declared and isn't based on user input or stored data. It won't vary while the program is running. Notice that there is more than one way to declare this type of arrays.
string[] strFruitArray = {"apple", "banana", "orange", "grape", "pineapple"};
string[] strFruitArray = new string[]{"apple", "banana", "orange", "grape", "pineapple"};
string[]strFruitArray;
strFruitArray = new string [5] {"apple", "banana", "orange", "grape", "pineapple"};
Regardless of which method is used to declare the array, referencing the individual values is done the same way
strFruitArray[0] = "apple"
strFruitArray[1] = "banana"
strFruitArray[2] = "orange"
strFruitArray[3] = "grape"
strFruitArray[4] = "pineapple"
Dynamic Arrays
Most of the time, we need to have arrays that we won't know the values or how many items. The next example is an example of a completely dynamic array. The only information set at design time is the data type (int), the variable name (intArray), and that it is an array ([]). The values and the number of values will be based on user input or data retrieved from at runtime. The following is an example of how this type of array is declared.
No length or values set at the time of declaration. Set this at the class level (see full example download) in order for it to be visible to the entire form class.
int[] intArray;
Fixed length at the time of declaration but not the values
intArray = new int[5];
Practical Example of a Dynamic Array
In the example below, there is a list box with some values. When the user clicks the "Create Array" button, the array size is set to the number of items in the list box and a for loop is used to add the values to the dynamic array.
private void btnCreateArray_Click(object sender, EventArgs e)
{
//the number of items in the list box is the size of our array.
int intNumItems = lstBoxValues.Items.Count;
//get the number of items
strListItems = new string[intNumItems];
//use a for iteration to add the items.
//List boxes are also 0 based. The first item in the list will be referred
//to as lstBoxValues[0].
for (int intX = 0; intX < lstBoxValues.Items.Count; intX++)
strListItems[intX] = lstBoxValues.Items[intX].ToString();
//Show array properties in a rich text box named rtbArrayValues
rtbArrayValues.Text = "Total number of elements = " + strListItems.LongLength + "\n" ;//the \n is a return
rtbArrayValues.Text += "The LowerBound() value = " + strListItems.GetLowerBound(0).ToString() + "\n";
rtbArrayValues.Text += "The UpperBound() value = " + strListItems.GetUpperBound(0).ToString() + "\n" ;
//show all of the values using the for iteration
for (int intX = 0; intX <= strListItems.GetUpperBound(0); intX++)
rtbArrayValues.Text += "value " + intX + " is " + strListItems[intX] "\n";
}