Tuesday, September 8, 2009

.Net 2.0 - Inbuilt Code Snippets for C# and Asp.net

# region File-Folder Operation

//1. write to file
using (StreamWriter sw = File.CreateText(@"C:\test.txt"))
{
sw.Write("Some text");
}

//2. copy one file data to another file
File.Copy(@"C:\Source.txt", @"C:\NewFolder\Dest.txt");

//3. cretaed folder
Directory.CreateDirectory(@"C:\NewDirectory");

//4. get temp file name
string filename = Path.GetTempFileName();

//5. delete files
string fileName = @"DeleteThisFile.txt";
if (File.Exists(fileName))
{
DialogResult result = MessageBox.Show("Do you want to Delete the file : " + fileName, "Delete File", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
File.Delete(fileName);
}
else
MessageBox.Show("Specified file does not exist");

//6. get hard drive names
System.Collections.ObjectModel.ReadOnlyCollection drives = new System.Collections.ObjectModel.ReadOnlyCollection(DriveInfo.GetDrives());

// 7. loop through all hard drives in a system
foreach (DriveInfo drive in DriveInfo.GetDrives())
{

}

# endregion File-Folder Operation

// 8. includes or i don't know
#if true

#endif

// 9.
#region MyRegion

#endregion

// 10. type "~" and press tab, creates cunstructor of the current class

#region Data Access Operations

//* Add expression to a data column
DataColumn OrderTotalColumn = new DataColumn();
OrderTotalColumn.ColumnName = "OrderTotal";
OrderTotalColumn.DataType = typeof(double);
OrderTotalColumn.Expressoin = "UnitPrice * Quantity";
ds.Order_Details.Columns.Add(OrderTotalColumn);

//* Add data relations
DataRelation customersOrders = new DataRelation("CustomersOrders", ds.Customers.Columns["CustomerID"], ds.Orders.Columns["CustomerID"]);
ds.Relations.Add(customersOrders);

//* Create sql connection
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = @"Data Source=ServerName;Initial Catalog=Northwind;Persist Security Info=True;User ID=;Password=";

//*Create sql connection
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True;User Instance=True";

//* Execute Non Query
int rowCount;
ConnectionState previousConnectionState;
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}

rowCount = cmd.ExecuteNonQuery();
}
finally
{
if (previousConnectionState == ConnectionState.Closed)
{
conn.Close();
}
}

//* Execute Scalar
System.Data.SqlClient.SqlDataReader reader;
ConnectionState previousConnectionState = conn.State;

try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}

reader = cmd.ExecuteReader();

using (reader)
{
while (reader.Read())
{
// Process SprocResults datareader here.
Console.WriteLine(reader.GetValue(0));
}
}
}
finally
{
if (previousConnectionState == ConnectionState.Closed)
{
conn.Close();
}
}

//* Add new row
NorthwindDataSet.CustomersRow newRow = this.NorthwindDataSet.Customers.NewRow();
newRow.CustomerID = "A124";
newRow.CompanyName = "Acme";

this.NorthwindDataSet.Customers.Rows.Add(newRow);

//* Parameters in ado.net
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT CustomerID, CompanyName FROM Customers WHERE CompanyName LIKE @companyName";
cmd.Connection = conn;

// Create a SqlParameter for each parameter in the stored procedure.
System.Data.SqlClient.SqlParameter companyNameParam = new System.Data.SqlClient.SqlParameter("@companyName", "a%");
cmd.Parameters.Add(companyNameParam);

//* parameters in SP in ado.net
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "CustOrderHist";

// Create a SqlParameter for each parameter in the stored procedure.
System.Data.SqlClient.SqlParameter customerIDParam = new System.Data.SqlClient.SqlParameter("@customerID", "ALFKI");
cmd.Parameters.Add(customerIDParam);

#endregion

//#region Exception Handling

////* try catch in C#
//try
//{
// // Add your data task here.
//}
//catch (ConstraintException constraint)
//{
// throw constraint;
//}
//catch (DeletedRowInaccessibleException deletedRow)
//{
// throw deletedRow;
//}
//catch (DuplicateNameException duplicateName)
//{
// throw duplicateName;
//}
//catch (InRowChangingEventException inRowChanging)
//{
// throw inRowChanging;
//}
//catch (InvalidConstraintException invalidConstraint)
//{
// throw invalidConstraint;
//}
//catch (InvalidExpressionException invalidExpression)
//{
// throw invalidExpression;
//}
//catch (MissingPrimaryKeyException missingPrimary)
//{
// throw missingPrimary;
//}
//catch (NoNullAllowedException noNull)
//{
// throw noNull;
//}
//catch (ReadOnlyException readOnlyEx)
//{
// throw readOnlyEx;
//}
//catch (RowNotInTableException rowNotInTable)
//{
// throw rowNotInTable;
//}
//catch (StrongTypingException strongTyping)
//{
// throw strongTyping;
//}
//catch (TypedDataSetGeneratorException typedDataset)
//{
// throw typedDataset;
//}
//catch (VersionNotFoundException versionNotFound)
//{
// throw versionNotFound;
//}
//catch (DataException dataEx)
//{
// throw dataEx;
//}
//catch (Exception ex)
//{
// throw ex;
//}
//finally
//{
// // Dispose of any resources you used in the Try block.
//}


//#endregion

#region Framework

//* Activate application
Microsoft.VisualBasic.Interaction.AppActivate("Untitled - Notepad");

//* Activate application in a process
System.Diagnostics.Process process = System.Diagnostics.Process.Start("NOTEPAD.EXE");
Microsoft.VisualBasic.Interaction.AppActivate(process.Id);

//* Loop through each app arguments
//foreach (string argument in args)
//{
// // do something
//}

// #region StartBackTasks
// private void startBackgroundTask()
// {
// // Execute the background task
// backgroundWorker1.RunWorkerAsync();
// }

// // The following two event handlers need to be attached in order to be called. This can be done via the properties
// // grid with the backgroundworker component selected or by adding the following lines of code to InitializeComponent():
// // this.backgroundWorker1.DoWork += this.backgroundWorker1_DoWork;
// // this.backgroundWorker1.RunWorkerCompleted += this.backgroundWorker1_RunWorkerCompleted;

// private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
// {
// // This method will execute in the background thread created by the BackgroundWorker componet

// }

// private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
// {
// // This event fires when the DoWork event completes

// }
//#endregion

//* back color
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.Gray;
Console.Clear();

//*
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed && System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CheckForUpdate())
{

}

//* console access
Console.WriteLine("Type in a sentence and hit Enter:");
string input = Console.ReadLine();
string output = input.ToUpper();
Console.WriteLine(output);

//*
string appFullName = "";
string currentVersion = "";
string updateLocation = "";
string lastUpdate = "";

System.Deployment.Application.ApplicationDeployment currentDeployment = System.Deployment.Application.ApplicationDeployment.CurrentDeployment;
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
appFullName = currentDeployment.UpdatedApplicationFullName;
currentVersion = currentDeployment.CurrentVersion.ToString();
updateLocation = currentDeployment.UpdateLocation.ToString();
lastUpdate = currentDeployment.TimeOfLastUpdateCheck.ToString();
}

//*
Cursor newCursor = new Cursor(Properties.Resources.ResourceManager.GetStream("CursorResourceName"));
this.Cursor = newCursor;

//*
if ((System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) && (!System.Deployment.Application.ApplicationDeployment.CurrentDeployment.IsFileGroupDownloaded("Media")))
{
System.Deployment.Application.ApplicationDeployment.CurrentDeployment.DownloadFileGroup("Media");
}

//*
// Create the source, if it does not already exist.
if(!System.Diagnostics.EventLog.SourceExists("ApplicationName"))
{
System.Diagnostics.EventLog.CreateEventSource("ApplicationName", "Application");
}

// Create an EventLog instance and assign its source.
System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
myLog.Source = "ApplicationName";

// Write an informational entry to the event log.
myLog.WriteEntry("Action complete.");

//*
pictureBox1.Image = Properties.Resources.Image1;

//*
System.IO.IsolatedStorage.IsolatedStorageFile isolatedStorage = System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForAssembly();
ulong spaceAvailable = isolatedStorage.MaximumSize - isolatedStorage.CurrentSize;

//*
System.IO.IsolatedStorage.IsolatedStorageFile isolatedStorage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForAssembly();
isolatedStorage.DeleteFile(@"FullPath\FileName.txt");

//*
System.IO.IsolatedStorage.IsolatedStorageFile isoStore = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain();
System.IO.IsolatedStorage.IsolatedStorageFileStream isoStream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(@"myfile.txt", FileMode.Open, isoStore);
string inputText = "";

using (StreamReader reader = new StreamReader(isoStream))
{
inputText = reader.ReadToEnd();
}

//*
System.IO.IsolatedStorage.IsolatedStorageFile isoStore = System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForApplication();
System.IO.IsolatedStorage.IsolatedStorageFileStream isoStream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(@"TestStore.txt", FileMode.Append, FileAccess.Write, isoStore);

using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Text to write to file.");
}

//*
System.IO.IsolatedStorage.IsolatedStorageScope scope = isolatedStorage.Scope;

//*
SendKeys.SendWait("{ENTER}");

//*
System.Reflection.Assembly loadedAssembly = System.Reflection.Assembly.LoadFile(@"C:\Folder\AssemblyName.dll");

//*
System.Diagnostics.Process consoleApp = new System.Diagnostics.Process();
consoleApp.StartInfo.UseShellExecute = false;
consoleApp.StartInfo.RedirectStandardOutput = true;
consoleApp.StartInfo.FileName = "ConsoleApplication.exe";
consoleApp.Start();
consoleApp.WaitForExit();

string output = consoleApp.StandardOutput.ReadToEnd();

//*
Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
string[] resources = executingAssembly.GetManifestResourceNames();

//*
System.Reflection.Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
Stream appStream = executingAssembly.GetManifestResourceStream("AssemblyName.Filename.txt");
StreamReader textStream = new StreamReader(appStream);
string text = textStream.ReadToEnd();

//*
System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcessesByName("notepad");
foreach (System.Diagnostics.Process proc in processList)
{
proc.CloseMainWindow();
}

//*
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateAsync();
}

//*
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
System.Deployment.Application.ApplicationDeployment.CurrentDeployment.Update();
}

//*
Console.Clear();

//* compare
// public class IntComparer: Comparer
//{
// public override int Compare(int param1, int param2)
// {
// if (param1 < param2) // { // return -1; // } // else if (param1 > param2)
// {
// return 1;
// }
// else
// {
// return 0;
// }
// }
//}


//*
string[] nameArray = (string[])existingArrayList.ToArray(typeof(string));

//*
int[] oneDimArray = {1, 2, 3};

//*
int index;
index = Array.IndexOf(myArray, "value");

//*
string[] theList = {"lion", "turtle", "ostrich"};
Array.Sort(theList);

//* Attribues in C#
/*
[global::System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
// See the attribute guidelines at
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconusingattributeclasses.asp
readonly string _positionalString;
int _namedInt;

// This is a positional argument.
public MyAttribute (string positionalString)
{
this._positionalString = positionalString;

// TODO: Implement code here.
throw new Exception("The method or operation is not implemented.");
}
public string PositionalString
{
get
{
return this._positionalString;
}
}
// This is a named argument.
public int NamedInt
{
get
{
return this._namedInt;
}
set
{
this._namedInt = value;
}
}
}
*
* */


//* bar time
/*
ToolStripLabel systemClockPanel = new ToolStripLabel();

private void AddClock()
{
// Create clock to add to status strip
statusStrip1.Items.Add(systemClockPanel);
systemClockPanel.Text = DateTime.Now.ToLongTimeString();

// Create timer to update the clock.
timer1.Interval = 1000;
timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
systemClockPanel.Text = DateTime.Now.ToLongTimeString();
}
*
* */

//* button autosize
button1.AutoSize = true;

//*
// Use a Graphics object to measure the button's text. Then add blanks to leave space on either side.
SizeF textSize;

using(Graphics surface = button1.CreateGraphics())
{
textSize = surface.MeasureString(" " + button1.Text + " ", button1.Font);
}

button1.Width = (int)textSize.Width;

//*
monthCalendar1.SetSelectionRange(DateTime.Parse("3/1/2005"), DateTime.Parse("3/21/2005"));

//*
comboBox1.DataSource = arrayListName;

//*
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
comboBox1.AutoCompleteSource = AutoCompleteSource.AllUrl;

//*
this.comboBox1.DataSource = dt;
this.comboBox1.DisplayMember = "";

//* don't know what it is but called checked block in C#
//checked
//{

//}

//* class
//class MyClass
//{

//}

//*
Clipboard.SetData(DataFormats.Serializable, classInstance);

//*
Clipboard.SetImage();

//*
Clipboard.SetText("My String");

//* copy image
Image picture;
if (Clipboard.ContainsImage())
{
picture = Clipboard.GetImage();
}

//* get text from clipboard
string text;
if (Clipboard.ContainsText())
{
text = Clipboard.GetText();
}

//* create list with single type
List names = new List();
names.Add("John");

//* create key
Dictionary stateCaps = new Dictionary();
stateCaps.Add("NM","Santa Fe");

//* create sorted dict
SortedDictionary sortedStudents = new SortedDictionary();
sortedStudents.Add(1, "Mary Chase");

//* indexes
string capitol = stateCaps["NM"];

//* foreach for items
//foreach(string name in names)
//{

//}

//*
foreach(string capitol in stateCaps.Values)
{

}

//*
foreach(int rank in sortedStudents.Keys)
{
string student = sortedStudents[rank];
}

//*
bool isAvailable = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

//* convert urls
Uri baseUri = new Uri("http://www.contoso.com/");
Uri relativeUri = new Uri("images/index.htm?id=null", UriKind.Relative);

// Compose absolute Uri using the base and the relative Uri.
Uri absoluteUri = new Uri(baseUri, relativeUri);

string absolute= absoluteUri.AbsolutePath;

//*
using (System.IO.Ports.SerialPort comPort= new System.IO.Ports.SerialPort("COM1", 2400))
{
comPort.DtrEnable = true;
comPort.Write("ATDT 206-555-1000" + "\r\n");
// All data transfer code goes here.
}

//*
System.Net.WebClient Client = new System.Net.WebClient();
Client.DownloadFile("http://www.URLtoDownloadFrom.net", @"C:\filename.html");

//* send mail
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("from@address", "to@address", "Subject", "Message Text");

System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("Email Server Name");
mailClient.Send(message);

//* pinging systems
System.Net.NetworkInformation.Ping pingObject = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply pingReplyObject = pingObject.Send("www.contoso.com");
System.Net.NetworkInformation.IPStatus status = pingReplyObject.Status;

//*
foreach (string portname in System.IO.Ports.SerialPort.GetPortNames())
{

}

//* reading ports
StringBuilder buffer = new StringBuilder();

using (System.IO.Ports.SerialPort comPort = new System.IO.Ports.SerialPort("COM1"))
{
try
{
comPort.Open();
do
{
string line = comPort.ReadLine();

if (line == null)
break;
else
buffer.Append(line);

} while(true);
}
finally
{
comPort.Close();
}
}


//*
ToolTip tooltip = new ToolTip();
tooltip.SetToolTip(button1, "ToolTip Text");

//* upload to internet
System.Net.WebClient Client = new System.Net.WebClient();
Client.UploadFile(@"c:\File.txt", "http://www.cohowinery.com/upload.aspx");

//* chnage server name and db name for crystal reports

CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
string oldServerName = "OldServer";
string newServerName = "NewServer";
string oldDatabaseName = "OldDatabase";
string newDatabaseName = "NewDatabase";
string userID = "MyUserID";
string password = "MyPassword";

report.Load(@"C:\My Crystal Reports\Report Name.rpt");

// Change the server name and database in main reports
foreach(CrystalDecisions.Shared.IConnectionInfo connection in report.DataSourceConnections)
{
if ((String.Compare(connection.ServerName, oldServerName, true) == 0) &&
(String.Compare(connection.DatabaseName, oldDatabaseName, true) == 0))
{
// SetConnection can also be used to set new logon and new database table
report.DataSourceConnections[oldServerName, oldDatabaseName].SetConnection(
newServerName, newDatabaseName, userID, password);
}
}

// Change the server name and database in subreport
foreach(CrystalDecisions.CrystalReports.Engine.ReportDocument subReport in report.Subreports)
{
foreach(CrystalDecisions.Shared.IConnectionInfo connection in subReport.DataSourceConnections)
{
if ((String.Compare(connection.ServerName, oldServerName, true) == 0) &&
(String.Compare(connection.DatabaseName, oldDatabaseName, true) == 0))
{
// SetConnection can also be used to set new logon and new database table
subReport.DataSourceConnections[oldServerName, oldDatabaseName].SetConnection(
newServerName, newDatabaseName, userID, password);
}
}
}



//* export crtstal report to a file on disk
// You can change other export options like page range by calling Export method with an ExportOptions object.
CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
report.Load(@"C:\My Crystal Reports\Report Name.rpt");
report.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, @"C:\My Crystal Reports\Report Name.pdf");
report.Close();

//* export crtstal report to a file on disk with options
CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
CrystalDecisions.Shared.ExportOptions exportOptions = new CrystalDecisions.Shared.ExportOptions();
CrystalDecisions.Shared.PdfRtfWordFormatOptions pdfExportFormatOptions = new CrystalDecisions.Shared.PdfRtfWordFormatOptions();
CrystalDecisions.Shared.DiskFileDestinationOptions diskDestinationOptions = new CrystalDecisions.Shared.DiskFileDestinationOptions();

// Set the export format and format options

exportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
pdfExportFormatOptions.FirstPageNumber = 1;
pdfExportFormatOptions.LastPageNumber = 5;
pdfExportFormatOptions.UsePageRange = true;
exportOptions.ExportFormatOptions = pdfExportFormatOptions;

// Set the disk file options.

exportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
diskDestinationOptions.DiskFileName = @"C:\My Crystal Reports\Report Name.pdf";
exportOptions.DestinationOptions = diskDestinationOptions;

report.Load(@"C:\My Crystal Reports\Report Name.rpt");
report.Export(exportOptions);
report.Close();


//* pring creports
// You can change more print options via PrintOptions property of ReportDocument
CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
report.Load(@"C:\My Crystal Reports\Report Name.rpt");
report.PrintToPrinter(1, true, 0, 0);
report.Close();

//* set CR credentials
CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

string serverName1 = "Server1";
string userID = "MyUserID";
string password = "MyPassword";
report.Load(@"C:\My Crystal Reports\Report Name.rpt");

//Set Database Logon to main report
foreach (CrystalDecisions.Shared.IConnectionInfo connection in report.DataSourceConnections)
{
if (connection.ServerName == serverName1)
{
connection.SetLogon(userID, password);
}
}

//Set Database Logon to subreport
foreach (CrystalDecisions.CrystalReports.Engine.ReportDocument subreport in report.Subreports)
{
foreach (CrystalDecisions.Shared.IConnectionInfo connection in subreport.DataSourceConnections)
{
if (connection.ServerName == serverName1)
{
connection.SetLogon(userID, password);
}
}
}

//* set parameter
CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
report.Load(@"C:\My Crystal Reports\Report Name.rpt");

CrystalDecisions.Shared.ParameterField parameterField;
parameterField = report.ParameterFields["Parameter1"];

// If the parameter is from a subreport, specify the subreport name
// parameterField = report.ParameterFields("Parameter1", subreportName.rpt);

// Add all parameters value here
parameterField.CurrentValues.AddValue(100.0);

//* set descrete parameters
CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
report.Load(@"C:\My Crystal Reports\Report Name.rpt");

CrystalDecisions.Shared.ParameterField parameterField;
parameterField = report.ParameterFields["Parameter1"];

// If the parameter is from a subreport, specify the subreport name
// parameterField = report.ParameterFields("Parameter1", subreportName.rpt);

// Add all parameters value here
parameterField.CurrentValues.AddValue(100.0);

//* crSetRangeParam
CrystalDecisions.CrystalReports.Engine.ReportDocument report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
report.Load(@"C:\My Crystal Reports\Report Name.rpt");

CrystalDecisions.Shared.ParameterField parameterField;
parameterField = report.ParameterFields["Parameter1"];

// If the parameter is from a subreport, specify the subreport name
// parameterField = report.ParameterFields("Parameter1", subreportName.rpt);

// Add all parameters value here
parameterField.CurrentValues.AddRange(0.0, 100.0, CrystalDecisions.Shared.RangeBoundType.BoundInclusive, CrystalDecisions.Shared.RangeBoundType.BoundInclusive);

//* ctor
public Form1 ()
{

}

//*cw
Console.WriteLine();

//* do
do
{

} while (true);

//* drawBitmap at runtime

Bitmap flag = new Bitmap(10, 10);
int x;
int y;
// Make the entire bitmap white.
for(x = 0 ; x <= flag.Height - 1;x++) { for(y = 0; y<= flag.Width - 1; y++) flag.SetPixel(x, y, System.Drawing.Color.White); } // Draw a diagonal red stripe. // now i am skipping all snippets from "drawBand" till "drawVertText" as all are drwaing things for(x = 0; x <= flag.Height - 1; x++) flag.SetPixel(x, x, System.Drawing.Color.Red); pictureBox1.Image = flag; //* dtBindingSourceCurrent NorthwindDataSet.CustomersRow row; row = ((NorthwindDataSet.CustomersRow)(DataRowView)this.CustomersBindingSource.Current); //* dtNonQueryOutParam public int GetNonQueryOutputParameter() { this.GetCustomerCount(); return this._commandCollection(1).Parameters(1).Value; } //* dtTableAdaptPartial namespace NorthwindDataSetTableAdapters { public partial class CustomersTableAdapter { } } //* else else { } //* enum enum MyEnum { } //* equals /* System.Diagnostics.EventLogEntry[] entries; entries = (System.Diagnostics.EventLogEntry[])(entriesList.ToArray(typeof(System.Diagnostics.EventLogEntry))); // override object.Equals public override bool Equals (object obj) { // // See the full list of guidelines at // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconequals.asp // and also the guidance for operator== at // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconimplementingequalsoperator.asp // if (obj == null || GetType() != obj.GetType()) { return false; } // TODO: write your implementation of Equals() here. throw new Exception("The method or operation is not implemented."); return base.Equals (obj); } // override object.GetHashCode public override int GetHashCode() { // TODO: write your implementation of GetHashCode() here. throw new Exception("The method or operation is not implemented."); return base.GetHashCode(); } */ //* evReadApp System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application"); System.Collections.ArrayList entriesList = new System.Collections.ArrayList(); foreach(System.Diagnostics.EventLogEntry entry in log.Entries) { if(entry.Source == "SourceName") entriesList.Add(entry); } //* evReadLog System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); System.Diagnostics.EventLogEntryCollection entries = log.Entries; //* evWriteApp System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", "SourceName"); log.WriteEntry("Message text", System.Diagnostics.EventLogEntryType.Warning, 123); //* exception /* [global::System.Serializable] public class MyException : Exception { // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // public MyException() { } public MyException( string message ) : base( message ) { } public MyException( string message, Exception inner ) : base( message, inner ) { } protected MyException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context ) : base( info, context ) { } } */ //* for file operation related snippets type "fil" and press ctrl+ tab, you will get like filCopyDir //* filCopyDir public static void copyDirectory(string src, string dst) { string[] files; if(dst[dst.Length-1] != Path.DirectorySeparatorChar) dst+=Path.DirectorySeparatorChar; if(!Directory.Exists(dst)) Directory.CreateDirectory(dst); files = Directory.GetFileSystemEntries(src); foreach(string element in files) { if(Directory.Exists(element)) copyDirectory(element,dst + Path.GetFileName(element)); else File.Copy(element,dst + Path.GetFileName(element),true); } } //* filCopyFile File.Copy(@"C:\Source.txt", @"C:\NewFolder\Dest.txt"); //* filCreateFile using(StreamWriter sw = File.CreateText(@"C:\test.txt")) { sw.Write("Some text"); } //* filCreateFold Directory.CreateDirectory(@"C:\NewDirectory"); //* filCreateTemp string filename = Path.GetTempFileName(); //* filDelFile string fileName = @"DeleteThisFile.txt"; if(File.Exists(fileName)) { DialogResult result = MessageBox.Show("Do you want to Delete the file : " + fileName,"Delete File",MessageBoxButtons.YesNo); if(result == DialogResult.Yes) File.Delete(fileName); } else MessageBox.Show("Specified file does not exist"); //* filDriveNames System.Collections.ObjectModel.ReadOnlyCollection drives = new System.Collections.ObjectModel.ReadOnlyCollection(DriveInfo.GetDrives());

//* filDrives
foreach(DriveInfo drive in DriveInfo.GetDrives())
{

}

//* fileComp
/*
private bool CompareFiles(string file1, string file2)
{
FileInfo fileInfo1 = new FileInfo(file1);
FileInfo fileInfo2 = new FileInfo(file2);

if (fileInfo1.Length == fileInfo2.Length)
{
//Read the bytes from both files.
byte[] bytes1 = File.ReadAllBytes(file1);
byte[] bytes2 = File.ReadAllBytes(file2);

//Make sure the arrays are of equal length.
if (bytes1.Length != bytes2.Length)
{
return false;
}

//Compare each byte.
for (int i = 0; i <= bytes1.Length - 1; i++) { if (bytes1[i] != bytes2[i]) { return false; } } return true; } else { return false; } } */ //* filExistFile bool exists = File.Exists(@"C:\Test.txt"); //* filExistFold bool exists = Directory.Exists(@"C:\TestDirectory"); //* filFileInfo FileInfo fileData = new FileInfo(@"C:\Test.txt"); //* filMoveFile File.Move(@"C:\OldDirectory\File.txt", @"C:\NewDirectory\File.txt"); //* filParseText /* string filename = @"C:\Test.txt"; string[] fields; string[] delimiter = new string[]{ "," }; using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) { parser.Delimiters = delimiter; while (!parser.EndOfData) { //Read in the fields for the current line fields = parser.ReadFields(); //Add code here to use data in fields variable. } } */ //* filReadBin byte[] fileContents; fileContents = File.ReadAllBytes(@"C:\Test.txt"); //* filReadMy string fullFilePath; string fileContents; fullFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"test.txt"); using(StreamReader sr = new StreamReader(fullFilePath)) { fileContents = sr.ReadToEnd(); } //* filReadText string fileContents; using(StreamReader sr = new StreamReader(@"C:\Test.txt")) { fileContents = sr.ReadToEnd(); } //* filRenDir Directory.Move(@"C:\OldDirectory", @"C:\New"); //* filRenFile File.Move(@"C:\OldFilename.txt", @"NewFileName.txt"); //* filSearchDir /* * System.Collections.ArrayList files = new System.Collections.ArrayList(); DirSearch(@"C:\",ref files); //Method to Search Directory for specified file Type.Paste it outside the function public void DirSearch(string sDir,ref System.Collections.ArrayList files) { try { foreach (string d in Directory.GetDirectories(sDir)) { foreach (string f in Directory.GetFiles(d, "*.txt")) { files.Add(f); } DirSearch(d,ref files); } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } } //Method to Search Directory for specified file Type.Paste it outside the function public void DirSearch(string sDir,ref System.Collections.ArrayList files) { try { foreach (string d in Directory.GetDirectories(sDir)) { foreach (string f in Directory.GetFiles(d, "*.txt")) { files.Add(f); } DirSearch(d,ref files); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } } **/ //* filSearchTxt /* System.Collections.ArrayList fileList = new System.Collections.ArrayList(); string searchString = "SearchString"; System.Collections.ArrayList files = new System.Collections.ArrayList(); DirSearch(@"C:\",ref files); foreach(string filename in files) { // Read the file into a string. System.IO.StreamReader fileReader = new System.IO.StreamReader(filename); string fileString = fileReader.ReadToEnd(); fileReader.Close(); if(fileString.Contains(searchString)) { // Add the file to the file list. fileList.Add(filename); } } * */ //* filSize FileInfo fileinfo = new FileInfo(@"filename.txt"); long filesize = fileinfo.Length; //* filSpace DriveInfo driveinfo = new DriveInfo("C:"); long freeSpace = driveinfo.TotalFreeSpace; //* filWriteBin /* byte[] fileContents = new byte[] {244, 123, 56, 34}; File.WriteAllBytes(@"C:\Output.bin", fileContents); */ //* filWriteText using(StreamWriter sw = new StreamWriter(@"C:\test.txt", true)) { sw.WriteLine("Text"); } //* fontCreate Font italic = new Font("Courier New", 12, FontStyle.Italic); //* for for (int i = 0; i < length; i++) { } //* foreach foreach (object var in collection_to_loop) { } //* formAdd - adds controls to form // Note - type "form" to get snippets related to form development, i have skipped all those snippets System.Windows.Forms.TextBox textBox1 = new System.Windows.Forms.TextBox(); textBox1.Location = new Point(64, 40); textBox1.Size = new Size(100, 20); textBox1.TabIndex = 0; textBox1.Text = "TextBox1"; Controls.Add(textBox1); //* formBeep enum BeepKind { MB_SIMPLEBEEP = -1, MB_ICONASTERISK = 0x00000010, MB_ICONEXCLAMATION = 0x00000020, MB_ICONHAND = 0x00000040, MB_ICONQUESTION = 0x00000020, MB_OK = 0x00000000 } static class Win32Methods { [System.Runtime.InteropServices.DllImport("User32.dll")] public static extern bool MessageBeep(BeepKind beepKind); } //* forr - reverse for loop for (int i = length - 1; i >= 0 ; i--)
{

}

//* gridLock - lock column width of gridview
dataGridView1.AllowUserToResizeColumns = false;

//* if
if (true)
{

}

//* indexer
public object this[int index]
{
get { /* return the specified index here */ }
set { /* set the specified index to value here */ }
}

//* interface
interface IInterface
{

}

//* invoke - invokes event
EventHandler temp = MyEvent;
if (temp != null)
{
temp();
}

//* iterator
/*
public System.Collections.Generic.IEnumerator GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
yield return default(ElementType);
}
* */

//* iterindex
/*
public MyViewIterator MyView
{
get
{
return new MyViewIterator(this);
}
}

public class MyViewIterator
{
readonly MyOuterClass outer;

internal MyViewIterator(MyOuterClass outer)
{
this.outer = outer;
}

// TODO: provide an appropriate implementation here
public int Length { get { return 1; } }

public ElementType this[int index]
{
get
{
//
// TODO: implement indexer here
//
// you have full access to MyOuterClass privates.
//
throw new Exception("The method or operation is not implemented.");
return default(ElementType);
}
}

public System.Collections.Generic.IEnumerator GetEnumerator()
{
for (int i = 0; i < this.Length; i++) { yield return this[i]; } } } * */ //* lbClear listBox1.DataSource = null; listBox1.Items.Clear(); //* lbData listBox1.DataSource = dt; listBox1.DisplayMember = "ColumnName"; //* lbLocate int index; index = listBox1.FindString("Maria"); if (index != ListBox.NoMatches) { // Item found. } else { // Item not found. } //* lbSelect listBox1.SelectedIndex = 1; //* lock - may be OSystem concurrent process lock concept lock (this) { } //* lvSelected /* ListViewItem selectedItem = new ListViewItem(); if(listView1.SelectedItems.Count > 0)
{
selectedItem = listView1.SelectedItems[0];
}
else
{
selectedItem = null;
}
*/


//* skipped all match snippets starting from "mathCos" as below
double radians = 120 * Math.PI / 180;
double cos = Math.Cos(radians);

//* mbox
MessageBox.Show("Test");

//* Note: skipped all of mdiActive, menuAddCheck and mqCreate series

//* skipping so many "os" snippets

//* osUser
string userName = Environment.UserName;

//* pbIterate - progress bar to show status of a task like looping here
progressBar1.Minimum = 1;
progressBar1.Maximum = 100000;
progressBar1.Value = 1;
progressBar1.Step = 1;

for (int i = progressBar1.Minimum; i <= progressBar1.Maximum; i++) { // Perform one step of the action being tracked. progressBar1.PerformStep(); } //* procBrowser - open default browser System.Diagnostics.Process.Start("about:blank"); /* now all process things...*/ //* procList - list running appplication System.Diagnostics.Process[] processList; processList = System.Diagnostics.Process.GetProcesses(); //* procRun System.Diagnostics.Process.Start(@"C:\Test.txt"); //* procStart System.Diagnostics.Process.Start("notepad.exe"); //* procStop System.Diagnostics.Process[] processList; processList = System.Diagnostics.Process.GetProcessesByName("notepad"); foreach(System.Diagnostics.Process proc in processList) { DialogResult response; response = MessageBox.Show("Terminate " + proc.ProcessName + "?","Terminate?",MessageBoxButtons.YesNo); if (response == DialogResult.Yes) proc.Kill(); } //* prop - property with field private int myVar; public int MyProperty { get { return myVar;} set { myVar = value;} } //* propg - with only get private int myVar; public int MyProperty { get { return myVar;} } //* rbString - create rbutton group from string array /* RadioButton radio; int y = 30; foreach (string button in names) { radio = new RadioButton(); radio.Location = new Point(10, y); radio.Text = button; y += 30; this.groupBox1.Controls.Add(radio); } * */ //* regCreate Microsoft.Win32.RegistryKey newKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\CompanyName\ProductName"); //* regDel using( Microsoft.Win32.RegistryKey delKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software")) { delKey.DeleteSubKey("KeyToDelete"); } //* regExist bool exists = true; using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\TestApp\1.0")) { if (key == null) exists = false; } //* regRead string keyValue = (Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\CompanyName\ProductName\KeyName", "Name", "Deafult Value")).ToString(); //* regWrite Microsoft.Win32.Registry.SetValue(@"HKEY_CURRENT_USER\Software\CompanyName\ProductName\KeyName", "Name", "value"); //* skipped all from "rich" and almost all "sd". knoiw all sd are for small/smart devices... :) //* sdculture private string GetCultureInfoName() { System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); System.Globalization.CultureInfo ci = asm.GetName().CultureInfo; // Return the culture name in English return ci.EnglishName; } /* security snippets starts here*/ //* secDecrypt /* using (FileStream fStream = File.Open("encrypted.txt", FileMode.OpenOrCreate)) { System.Security.Cryptography.Rijndael rijndaelAlg = System.Security.Cryptography.Rijndael.Create(); using(System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(fStream, rijndaelAlg.CreateDecryptor(rijndaelAlg.Key, rijndaelAlg.IV), System.Security.Cryptography.CryptoStreamMode.Read)) using (StreamReader sReader = new StreamReader(cStream)) { string plainText = sReader.ReadLine(); } } */ //* secEncrypt /* using (FileStream fStream = File.Open("encrypted.txt", FileMode.OpenOrCreate)) { System.Security.Cryptography.Rijndael rijndaelAlg = System.Security.Cryptography.Rijndael.Create(); using(System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(fStream, rijndaelAlg.CreateEncryptor(rijndaelAlg.Key, rijndaelAlg.IV), System.Security.Cryptography.CryptoStreamMode.Write)) using (StreamWriter sWriter = new StreamWriter(cStream)) { sWriter.WriteLine("Text to encrypt"); } } * */ //* secHashPass - get hash code of a password System.Security.Cryptography.SHA1CryptoServiceProvider sha1CryptoService = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] byteValue = Encoding.UTF8.GetBytes("passwordString"); byte[] hashValue = sha1CryptoService.ComputeHash(byteValue); //* secHashStr - hash code of a string /* public enum HashMethod { MD5, SHA1, SHA384 } public string GenerateHashDigest (string source, HashMethod algorithm) { System.Security.Cryptography.HashAlgorithm hashClass = null; switch(algorithm) { case HashMethod.MD5: hashClass = new System.Security.Cryptography.MD5CryptoServiceProvider(); break; case HashMethod.SHA1: hashClass = new System.Security.Cryptography.SHA1CryptoServiceProvider(); break; case HashMethod.SHA384: hashClass = new System.Security.Cryptography.SHA384Managed(); break; default: // Error case. break; } byte[] byteValue = Encoding.UTF8.GetBytes(source); byte[] hashValue = hashClass.ComputeHash(byteValue); return Convert.ToBase64String(hashValue); } * */ //* secRanNum - generates crypto basis random number System.Security.Cryptography.RandomNumberGenerator randomNumGen = System.Security.Cryptography.RNGCryptoServiceProvider.Create(); byte[] randomBytes = new byte[8]; randomNumGen.GetBytes(randomBytes); //* secUser string username = Environment.UserName; //* servCont - continue a windows service works even for any OS service System.ServiceProcess.ServiceController controller; controller = new System.ServiceProcess.ServiceController("IISAdmin"); if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Paused) { controller.Continue(); } //* servList - list of services System.ServiceProcess.ServiceController[] services; services = System.ServiceProcess.ServiceController.GetServices(); //* servPause - pause service System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("IISAdmin"); controller.Pause(); //* servStart System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("IISAdmin"); controller.Start(); //* servStop System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("IISAdmin"); controller.Stop(); //* sim - create main static int Main(string[] args) { return 0; } //* skipped all "snd" //* struct for struct struct MyStruct { } //* svm static void Main(string[] args) { } //* switch switch (switch_on) { default: } //* all sys are almost skipped //* sysDir string systemDirectory; systemDirectory = Environment.SystemDirectory; //* sysMem ulong totalPhysicalMemory; Microsoft.VisualBasic.Devices.ComputerInfo compInfo = new Microsoft.VisualBasic.Devices.ComputerInfo(); totalPhysicalMemory = compInfo.TotalPhysicalMemory; //* sysOS current os version string OSVersion = Environment.OSVersion.ToString(); //* sysRegion - get regional setting of the system System.Globalization.CultureInfo installed = System.Globalization.CultureInfo.InstalledUICulture; System.Globalization.CultureInfo current = System.Globalization.CultureInfo.CurrentCulture; System.Globalization.CultureInfo ui = System.Globalization.CultureInfo.CurrentUICulture; //* sysRes - get resolution of the system int height = Screen.PrimaryScreen.Bounds.Height; int width = Screen.PrimaryScreen.Bounds.Width; //* sysSpace DriveInfo drive = new DriveInfo(@"C:\"); long space = drive.AvailableFreeSpace; //* sysTime - local system time DateTime localTime = DateTime.Now; //* tbArray - multiline string to multiline textbox textBox1.Lines = names; //* try try { } catch (Exception) { throw; } //* tryf try { } finally { } /* tree view */ //* tvSelect TreeNode selectedNode; selectedNode = treeView1.SelectedNode; //* typeByteStr private string ConvertByteArrayToString(byte[] byteArray) { Encoding enc = Encoding.UTF8; string text = enc.GetString(byteArray); return text; } //* typeDate - calculate time span between two time DateTime oldDate = DateTime.Parse("1/1/2002"); DateTime newDate = DateTime.Now; TimeSpan spanFromDays = newDate - oldDate; MessageBox.Show (spanFromDays.Days.ToString()); //* typeHex - number to hexadecimals string hexString = Microsoft.VisualBasic.Conversion.Hex(48); //* typeMulti - generate multiline string literals string longString = "This is the first line of my string." + "\r\n" + "This is the second line of my string." + "\r\n" + "This is the third line of my string."; //* typeOct - number to octal string octal = Microsoft.VisualBasic.Conversion.Oct(48); //* typeParseEmail - parse email /* private void ParseAnEmailAddress(string email, out string user, out string provider) { try { string[] parts = email.Split("@".ToCharArray(),2); user = parts[0]; provider = parts[1]; } catch { user = null; provider = null; throw new Exception("Email address is not valid. The expected format is user@provider."); } } * */ //* typeRemove string withParts = "Books and Chapters and Pages"; string withoutParts = withParts.Replace("and ", ""); //* typeStrByte - string to byte array byte[] bytes = Encoding.Unicode.GetBytes("StringToConvert"); //* typeTime DateTime oldTime = DateTime.Today; DateTime newTime = DateTime.Now; // You can also determine the difference in times in other units. TimeSpan spanSeconds = newTime - oldTime; MessageBox.Show (spanSeconds.Seconds.ToString()); //* unchecked unchecked { } //* unsafe //unsafe // { // } //* using using(resource) { } //* while while (true) { } /* XML starts here */ //* xmlAdd - add child node System.Xml.XmlNode newElement; newElement = xml.CreateElement("Keyword"); newElement.InnerText = "Value"; xml.AppendChild(newElement); //* xmlEnum - enumerates attributes in xml foreach(System.Xml.XmlAttribute attribute in node.Attributes) { } //* xmlFind - find node data in xml using element name System.Xml.XmlNodeList nodes; nodes = xml.GetElementsByTagName("ElementName"); //* xmlInfer - infer schema from xml // Gets the schema. System.Xml.Schema.XmlSchemaInference infer = new System.Xml.Schema.XmlSchemaInference(); System.Xml.Schema.XmlSchemaSet sc = new System.Xml.Schema.XmlSchemaSet(); sc = infer.InferSchema(new System.Xml.XmlTextReader("sample.xml")); // Writes the schema. System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(new StreamWriter("sampleSchema.xsd")); foreach (System.Xml.Schema.XmlSchema schema in sc.Schemas()) { schema.Write(w); } // Update the schema with another xml fragment. sc = infer.InferSchema(System.Xml.XmlReader.Create("anothersample.xml"), sc); w = System.Xml.XmlWriter.Create(new StreamWriter("anotherschema.xsd")); foreach (System.Xml.Schema.XmlSchema schema in sc.Schemas()) { schema.Write(w); } //* xmlIter - iterates named nodes in xml foreach(System.Xml.XmlNode node in xmlDoc.GetElementsByTagName("ElementName")) { } //* xmlNavDoc - navigate using xpathnavigator System.Xml.XPath.XPathNavigator nav = xmlDoc.CreateNavigator(); // Move to the first non-comment element. nav.MoveToChild(System.Xml.XPath.XPathNodeType.Element); System.Xml.XPath.XPathNodeIterator nodeIterator = nav.SelectChildren(System.Xml.XPath.XPathNodeType.Element); while(nodeIterator.MoveNext()) { } //* xmlNavNodes - select nodes uisng xpathnavgator System.Xml.XPath.XPathExpression myXPathExpr; System.Xml.XPath.XPathDocument myXPathDocument = new System.Xml.XPath.XPathDocument(@"data.xml"); // Create an XPathNavigator. System.Xml.XPath.XPathNavigator myXPathNavigator = myXPathDocument.CreateNavigator(); // Get the Book elements. string selectExpr = "parent/child"; // Ensure we are at the root node. myXPathNavigator.MoveToRoot(); myXPathExpr = myXPathNavigator.Compile(selectExpr); // Create an XPathNodeIterator to walk over the selected nodes. System.Xml.XPath.XPathNodeIterator myXPathNodeIterator = myXPathNavigator.Select(myXPathExpr); //* xmlReadClass - read object data from xml using class name System.Xml.XmlSerializer reader = new System.Xml.XmlSerializer(typeof(TheClass)); using(StreamReader file = new StreamReader(@"ClassData.xml")) { TheClass fileData; fileData = (TheClass)reader.Deserialize(file); } //* xmlReadString - read xml from a string // Create the reader. System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new StringReader(""));

while(reader.Read())
{

}

//* xmlReadText - read xml from a text xml file using xmltextreader
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("Snippet.xml");
string contents = reader.ReadInnerXml();

//* xmlReadUrl - read xml from url
string myUrl = "http://www.contoso.com/books.xml";
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(myUrl);

while(reader.Read())
{

}

//* xmlWriteClass - write class data to xml
System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ArrayList));

using(StreamWriter file = new StreamWriter("SerializedData.xml"))
{
writer.Serialize(file, dataToWrite);
}

//* xmlXsl - transform xml to html using "xsl" style sheet
/*
using(FileStream stream = File.Open("output.html", FileMode.Create))
{
// Create XsltCommand compile stylesheet.
System.Xml.Xsl.XslCompiledTransform processor = new System.Xml.Xsl.XslCompiledTransform();
processor.Load("stylesheet.xsl");

// Transform the file.
processor.Transform("data.xml", null, stream);
}
*/

//* xmlXslt - xml to html using xslt
System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();

xslt.Load("theXsltFile.xslt");
xslt.Transform("theXmlFile.xml", "theOutputFile.html");

#endregion

-----------------------------------------------------------------

// Copy folder to another folder
public static void copyDirectory(string src, string dst)
{
string[] files;
if (dst[dst.Length - 1] != Path.DirectorySeparatorChar)
dst += Path.DirectorySeparatorChar;
if (!Directory.Exists(dst))
Directory.CreateDirectory(dst);
files = Directory.GetFileSystemEntries(src);
foreach (string element in files)
{
if (Directory.Exists(element))
copyDirectory(element, dst + Path.GetFileName(element));
else
File.Copy(element, dst + Path.GetFileName(element), true);
}
}

// compare two file data
private bool CompareFiles(string file1, string file2)
{
FileInfo fileInfo1 = new FileInfo(file1);
FileInfo fileInfo2 = new FileInfo(file2);

if (fileInfo1.Length == fileInfo2.Length)
{
//Read the bytes from both files.
byte[] bytes1 = File.ReadAllBytes(file1);
byte[] bytes2 = File.ReadAllBytes(file2);

//Make sure the arrays are of equal length.
if (bytes1.Length != bytes2.Length)
{
return false;
}

//Compare each byte.
for (int i = 0; i <= bytes1.Length - 1; i++)
{
if (bytes1[i] != bytes2[i])
{
return false;
}
}
return true;
}
else
{
return false;
}
}

---------------------------------------------------------------