Detect When Network Goes Up or Down

namespace My
{
 internal partial class MyApplication
 {
  private void MyApplication_NetworkAvailabilityChanged(object sender, Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs e)
  {
   if (e.IsNetworkAvailable) {
    Diagnostics.Debug.WriteLine("Network went up.");
   } else {
    Diagnostics.Debug.WriteLine("Network went down.");
   }
  }
  public MyApplication()
  {
   NetworkAvailabilityChanged += MyApplication_NetworkAvailabilityChanged;
  }
 }
}

Difference Between Dates/Times Including Daylight Savings Time

System.DateTime StartTime = DateTime.SpecifyKind(3/8/2009 1:59:00 AM, DateTimeKind.Local);
System.DateTime EndTime = DateTime.SpecifyKind(3/8/2009 3:01:00 AM, DateTimeKind.Local);
TimeSpan TimeDifference = EndTime.ToUniversalTime - StartTime.ToUniversalTime;
ulong MinutesBetweenTimes = DateDiff(DateInterval.Minute, StartTime.ToUniversalTime, EndTime.ToUniversalTime);

Force the program to pause

[] Paws = new[];
public void Paws(ulong Milliseconds)
{
 System.DateTime WaitUntil = Now + new TimeSpan(0, 0, 0, 0, Milliseconds);
 while (Now < WaitUntil) {
  Threading.Thread.Sleep(18);
  Application.DoEvents();
 }
}

Alphabetize drop down list and remove duplicate items.

protected void AlphabetizeDropDownListAndRemoveDuplicates(DropDownList ThisDropDownList)
{
 SortedList AlphabetizedItems = new SortedList();
 foreach (ListItem ThisListItem in ThisDropDownList.Items) {
  if (AlphabetizedItems.Contains(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Strings.Trim(ThisListItem.Text))) == false) {
   AlphabetizedItems.Add(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Strings.Trim(ThisListItem.Text)), ThisListItem.Value);
  }
 }
 ThisDropDownList.Items.Clear();
 foreach (DictionaryEntry AlphabetizedItem in AlphabetizedItems) {
  ThisDropDownList.Items.Add(new ListItem(AlphabetizedItem.Key, AlphabetizedItem.Value));
 }
}

Create a table of unique cells from a column in a table.

Data.DataTable UniqueTable = DataTable1.DefaultView.ToTable(true, new string[] { "FieldName" });

Display row numbers in a DataGridView

{
 if (DataGridView1.Rows.Count > 0) {
  for (ulong r = 0; r <= DataGridView1.Rows.Count - 1; r++) {
   DataGridView1.Rows(r).HeaderCell.Value = (r + 1).ToString;
  }
 }
 DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
}

Remove extra spaces and tabs from a string of characters.

string TextWithExtraSpaces = "The    Quick   Brown   Fox    Jumps    Over          A           Lazy Dog.";
string TextWithExtraSpacesRemoved = System.Text.RegularExpressions.Regex.Replace(TextWithExtraSpaces, "\\s+", " ");

Get minimum and maximum values from an array

double[] NumberArray = {
 1,
 2,
 3,
 9,
 8,
 7,
 System.Math.PI
};
if (NumberArray.Length > 0) {
 double[] SortArray = NumberArray.Clone;
 Array.Sort(SortArray);
 double MinValue = SortArray(0);
 double MaxValue = SortArray(SortArray.Length - 1);
 SortArray = null;
}

Reverse the values in an array to their opposite order

double[] NumbersArray = {
 1,
 2,
 3,
 9,
 8,
 7,
 System.Math.PI
};
Array.Reverse(NumbersArray);

Capitalize the first letter of each word in a string of text

private string Capatalize(string StringToCapatalize)
{
 dynamic ReturnString = StringToCapatalize;
 dynamic CapsString = ReturnString.ToLower;
 CapsString = CapsString.Replace("o'", "o" + Strings.ChrW(8203) + "'");
 ReturnString = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(CapsString);
 return ReturnString;
}

Get the number of lines, words and characters in a text file

string FileContents = My.Computer.FileSystem.ReadAllText("C:\\Temp\\Temp.TXT");
System.Text.RegularExpressions.MatchCollection LinesFound = System.Text.RegularExpressions.Regex.Matches(FileContents, "\\n");
System.Text.RegularExpressions.MatchCollection WordsFound = System.Text.RegularExpressions.Regex.Matches(FileContents, "\\w+");
ulong NumberOfLines = LinesFound.Count;
ulong NumberOfWords = WordsFound.Count;
ulong NumberOfCharacters = FileContents.Length;

Add strongly typed columns and rows to a memory resident data table

Data.DataTable DataTable1 = new Data.DataTable();

while (DataTable1.Columns.Contains("Record ID Column") == false) {
 Data.DataColumn NewDataColumn = new Data.DataColumn();
 NewDataColumn.ColumnName = "Record ID Column";
 NewDataColumn.DataType = System.Type.GetType("System.Int64");
 NewDataColumn.AutoIncrement = true;
 NewDataColumn.AutoIncrementSeed = 0;
 NewDataColumn.AutoIncrementStep = 1;
 DataTable1.Columns.Add(NewDataColumn);
 Data.DataColumn[] DataColumnArray = { DataTable1.Columns("Record ID Column") };
 DataTable1.PrimaryKey = DataColumnArray;
}

while (DataTable1.Columns.Contains("String Column") == false) {
 Data.DataColumn NewDataColumn = new Data.DataColumn();
 NewDataColumn.ColumnName = "String Column";
 NewDataColumn.DataType = System.Type.GetType("System.String");
 DataTable1.Columns.Add(NewDataColumn);
}

while (DataTable1.Columns.Contains("Date Column") == false) {
 Data.DataColumn NewDataColumn = new Data.DataColumn();
 NewDataColumn.ColumnName = "Date Column";
 NewDataColumn.DataType = System.Type.GetType("System.DateTime");
 DataTable1.Columns.Add(NewDataColumn);
}

while (DataTable1.Columns.Contains("Boolean Column") == false) {
 Data.DataColumn NewDataColumn = new Data.DataColumn();
 NewDataColumn.ColumnName = "Boolean Column";
 NewDataColumn.DataType = System.Type.GetType("System.Boolean");
 DataTable1.Columns.Add(NewDataColumn);
}

//Make NewDataRow reusable by wrapping it in a loop structure.
do {
 Data.DataRow NewDataRow = DataTable1.NewRow;
 NewDataRow.Item("String Column") = "Text 1";
 NewDataRow.Item("Date Column") = Today;
 NewDataRow.Item("Boolean Column") = true;
 DataTable1.Rows.Add(NewDataRow);
 break; // TODO: might not be correct. Was : Exit Do
} while (true);

do {
 Data.DataRow NewDataRow = DataTable1.NewRow;
 NewDataRow.Item("String Column") = "Text 2";
 NewDataRow.Item("Date Column") = Now;
 NewDataRow.Item("Boolean Column") = false;
 DataTable1.Rows.Add(NewDataRow);
 break; // TODO: might not be correct. Was : Exit Do
} while (true);

Create a data table from a CSV file.

private void Form1_Load(object sender, System.EventArgs e)
{
 this.Size = new System.Drawing.Size(640, 480);
 DataGridView DataGridView1 = new DataGridView();
 DataGridView1.Location = new System.Drawing.Point(0, 0);
 DataGridView1.Size = new System.Drawing.Size(635, 445);
 DataGridView1.Anchor = 15;
 this.Controls.Add(DataGridView1);
 Data.DataTable CsvTable = new Data.DataTable();
 string Filename = "C:\\Temp\\Temp1.csv";
 string[] Fields = null;
 string Delimiter = ",";
 using (Microsoft.VisualBasic.FileIO.TextFieldParser Parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(Filename)) {
  Parser.SetDelimiters(Delimiter);
  while (!Parser.EndOfData) {
   Fields = Parser.ReadFields();
   if (CsvTable.Columns.Count == 0) {
    //This code presumes the first line of data contains the column names.
    foreach (string Field in Fields) {
     string ColumnName = Field;
     while (CsvTable.Columns.Contains(ColumnName)) {
      ColumnName = Conversion.Val(ColumnName) + 1 + "-" + Field;
     }
     CsvTable.Columns.Add(ColumnName, System.Type.GetType("System.String"));
    }
   } else {
    Data.DataRow NewDataRow = CsvTable.NewRow;
    for (int i = 0; i <= Math.Min(CsvTable.Columns.Count - 1, Fields.Length - 1); i++) {
     NewDataRow.Item(i) = Fields(i);
    }
    CsvTable.Rows.Add(NewDataRow);
   }
  }
 }
 DataGridView1.DataSource = CsvTable;
 DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
 DataGridView1.AutoResizeColumns();
}

Display header in GridView cell when mouse pointer hovers over it

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
 if ((e.Row.RowType == DataControlRowType.DataRow) | (e.Row.RowType == DataControlRowType.Header)) {
  foreach (DataControlFieldCell GridViewDataControlFieldCell in e.Row.Cells) {
   //Remove any hidden hyphens that might be in the header.
   string GridViewHeaderText = GridViewDataControlFieldCell.ContainingField.HeaderText.Replace(Strings.Chr(173), "");
   if (e.Row.RowType == DataControlRowType.DataRow) {
    GridViewDataControlFieldCell.Attributes.Add("Title", GridViewHeaderText);
    GridViewDataControlFieldCell.Attributes.Add("onmouseover", "this.bgColor='lightyellow'");
    GridViewDataControlFieldCell.Attributes.Add("onmouseout", "this.bgColor=''");
   } else {
    GridViewDataControlFieldCell.Attributes.Add("Title", "Click link to sort by " + GridViewHeaderText);
   }
  }
 }
}

Save and restore column order of DataGridView

private void DataGridView1_DataBindingComplete(object sender, System.Windows.Forms.DataGridViewBindingCompleteEventArgs e)
{
 Collections.ArrayList ColumnDisplayOrder = new Collections.ArrayList();
 //ColumnsOrder setting must be of type mscorlib.System.Collections.ArrayList
 ColumnDisplayOrder = My.Settings.ColumnDisplayOrder;
 if (ColumnDisplayOrder != null) {
  if (ColumnDisplayOrder.Count > 0) {
   for (int I = 0; I <= ColumnDisplayOrder.Count - 1; I++) {
    DataGridView1.Columns.Item(I).DisplayIndex = ColumnDisplayOrder(I);
   }
  }
 }
}

private void DataGridView1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
 Collections.ArrayList ColumnDisplayOrder = new Collections.ArrayList();
 for (int I = 0; I <= DataGridView1.Columns.Count - 1; I++) {
  ColumnDisplayOrder.Add(DataGridView1.Columns.Item(I).DisplayIndex);
 }
 //ColumnsOrder setting must be of type mscorlib.System.Collections.ArrayList
 My.Settings.ColumnDisplayOrder = ColumnDisplayOrder;
 My.Settings.Save();
}

Formatting dates in a data grid view to display seconds.

private void DataGridView1_ColumnAdded(object sender, System.Windows.Forms.DataGridViewColumnEventArgs e)
{
 if (object.ReferenceEquals(e.Column.ValueType, System.Type.GetType("System.DateTime"))) {
  e.Column.DefaultCellStyle.Format = "yyyy-MM-dd hh:mm:ss";
 }
}

Function to standardize a telephone number.

public class Form1
{

 private void Form1_Load(object sender, System.EventArgs e)
 {
  string RawPhoneNumber = "(800) 555-1212";
  string StandardizedPhoneNumber = StandardizePhoneNumber(RawPhoneNumber);
  Interaction.MsgBox("Phone number: " + RawPhoneNumber + ControlChars.CrLf + "Standardized: " + StandardizedPhoneNumber);
 }

 public string StandardizePhoneNumber(string PhoneNumber)
 {
  if (PhoneNumber // ERROR: Unknown binary operator Like
 == true) {
   PhoneNumber = System.Text.RegularExpressions.Regex.Replace(PhoneNumber, "\\D", "");
   if (PhoneNumber.StartsWith("1") == false) {
    PhoneNumber = "1" + PhoneNumber;
   }
   if (PhoneNumber // ERROR: Unknown binary operator Like
) {
    ulong PhoneNumberValue = Conversion.Val(Strings.Left(PhoneNumber, 11));
    PhoneNumber = PhoneNumberValue.ToString("0-000-000-0000");
   }
  }
  return PhoneNumber;
 }
 public Form1()
 {
  Load += Form1_Load;
 }

}

Prevent ASP textbox from accepting Enter key.

protected void TextBox1_Load(object sender, System.EventArgs e)
{
 TextBox1.Attributes.Add("onKeyPress", "return event.keyCode!=13");
}

Create a new table from some columns of an existing table.

string[] ColumnsToKeep = {
 "Column1",
 "Column2",
 "Column3"
};
DataTable1.DefaultView.Sort = "Column1 DESC";
Data.DataTable DataTable2 = DataTable1.DefaultView.ToTable(false, ColumnsToKeep);

Upload picture and correct file extension.

protected void Button1_Click(object sender, System.EventArgs e)
{
 // Specify the path on the server to save the uploaded picture to. MUST END WITH A TRAILING SLASH!
 string SavePath = Server.MapPath("PictureFolder\\");
 if ((FileUpload1.HasFile == true)) {
  //Get the correct file extension.
  string PictureFileExtension = GetPictureFileType(ref FileUpload1);
  if (PictureFileExtension != ".UNKNOWN") {
   int fileSize = FileUpload1.PostedFile.ContentLength;
   if ((fileSize < 2097152)) {
    //Delete any previously uploaded pictures with this name.
    System.Collections.ObjectModel.ReadOnlyCollection PictureFiles = My.Computer.FileSystem.GetFiles(SavePath, FileIO.SearchOption.SearchTopLevelOnly, Now.ToString("'Picture'yyyyMMddhhmmssfffffff") + PictureFileExtension);
    if (PictureFiles.Count > 0) {
     for (ushort P = 0; P <= PictureFiles.Count - 1; P++) {
      System.IO.FileInfo FileData = My.Computer.FileSystem.GetFileInfo(PictureFiles.Item(P));
      if (FileData.Extension != PictureFileExtension) {
       My.Computer.FileSystem.DeleteFile(FileData.FullName, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently);
      }
     }
    }
    SavePath += Now.ToString("'Picture'yyyyMMddhhmmssfffffff") + PictureFileExtension;
    FileUpload1.SaveAs(SavePath);
    Response.Write("The picture was uploaded successfully.");
   } else {
    Response.Write("The picture was not accepted because it exceeds 2 megabytes in size.");
   }
  } else {
   Response.Write("The file was not a picture that can be displayed by this system.");
  }
 } else {
  Response.Write("You did not specify a picture to upload.");
 }
 Response.Flush();
}

public static string GetPictureFileType(ref FileUpload UploadedFile)
{
 string functionReturnValue = null;
 if ((UploadedFile.PostedFile.ContentType == null)) {
  return ".UNKNOWN";
  return functionReturnValue;
 }
 switch (UploadedFile.PostedFile.ContentType.ToLower) {
  case "image/gif":
   return ".GIF";
  case "image/jpeg":
   return ".JPG";
  case "image/pjpeg":
   return ".JPG";
  case "image/x-png":
   return ".PNG";
  case "image/jpg":
   return ".JPG";
  case "image/bmp":
   return ".BMP";
  case "image/x-wmf":
   return ".WMF";
  default:
   return ".UNKNOWN";
 }
 return functionReturnValue;
}

Test SQL Connection

private void TestSqlConnection(string TableNameString, string ConnectionString)
{
 Debug.WriteLine("Generic SQL connection test started.");
 Debug.WriteLine("This subroutine will attempt to create a record in a SQL table, then delete that record.");
 Debug.WriteLine("If no errors are generated in this subroutine, the test was successful.");
 string SelectString = string.Format("sp_pkeys [{0}]", TableNameString);
 System.Data.SqlClient.SqlDataAdapter DataAdapter = new System.Data.SqlClient.SqlDataAdapter(SelectString, ConnectionString);
 System.Data.SqlClient.SqlCommandBuilder DatabaseCommandBuilder = new System.Data.SqlClient.SqlCommandBuilder(DataAdapter);
 DatabaseCommandBuilder.QuotePrefix = "[";
 DatabaseCommandBuilder.QuoteSuffix = "]";
 Data.DataTable KeysDataTable = new Data.DataTable();
 SelectString = string.Format("sp_pkeys [{0}]", TableNameString);
 DataAdapter.Fill(KeysDataTable);
 if (KeysDataTable.Rows.Count != 1) {
  Interaction.MsgBox(string.Format("This subroutine can only test a SQL table with 1 key field.  {0}The [{1}] table has {2} key fields.", ControlChars.CrLf, TableNameString, KeysDataTable.Rows.Count));
  return;
 }
 string KeyColumnName = KeysDataTable.Rows(0).Item("COLUMN_NAME");
 Data.DataTable TestDataTable = new Data.DataTable();
 SelectString = string.Format("Select * from [{0}]", TableNameString);
 DataAdapter.SelectCommand = new SqlClient.SqlCommand(SelectString, new SqlClient.SqlConnection(ConnectionString));
 DataAdapter.Fill(TestDataTable);
 Debug.WriteLine("Test dataset filled.");
 Data.DataRow NewTestDataRow = null;
 NewTestDataRow = TestDataTable.NewRow;
 foreach (Data.DataColumn TestDataColumn in TestDataTable.Columns) {
  string ColumnName = TestDataColumn.ColumnName;
  if (object.ReferenceEquals(TestDataColumn.DataType, System.Type.GetType("System.DateTime"))) {
   NewTestDataRow.Item(ColumnName) = Now;
  } else {
   NewTestDataRow.Item(ColumnName) = TestDataTable.Rows.Count;
  }
 }
 dynamic NewRowKey = NewTestDataRow.Item(KeyColumnName);
 TestDataTable.Rows.Add(NewTestDataRow);
 DataAdapter.Update(TestDataTable);
 Debug.WriteLine("Test dataset updated (row added).");
 TestDataTable.Clear();
 DataAdapter.Fill(TestDataTable);
 Data.DataColumn[] DataColumnArray = { TestDataTable.Columns(KeyColumnName) };
 TestDataTable.PrimaryKey = DataColumnArray;
 Data.DataRow RowToDelete = TestDataTable.Rows.Find(NewRowKey);
 TestDataTable.Rows(TestDataTable.Rows.IndexOf(RowToDelete)).Delete();
 Data.DataTable TableChanges = TestDataTable.GetChanges;
 DataAdapter.Update(TestDataTable);
 Debug.WriteLine("Test dataset updated (row deleted).");
 Debug.WriteLine("Generic SQL connection test ended.");
}

Get the differences between two data tables.

public Data.DataTable GetDifferencesBetweenTwoTables(Data.DataTable DataTable1, Data.DataTable DataTable2)
{
 Debug.WriteLine("Looking for changed records.");
 Debug.WriteLine("This function will compare two data tables and return a data table with the changed rows.");
 Debug.WriteLine("The two tables must have the same columns and at least one key column.");
 //Create an empty table with the correct fields to return the differences.
 Data.DataTable ModifiedDataTable = DataTable1.Clone;
 //Create an array to store the names of the key columns.
 string[] KeyColumnNames = new string[DataTable1.PrimaryKey.Length];
 //Get the key column names from the first table.
 for (int I = 0; I <= DataTable1.PrimaryKey.Length - 1; I++) {
  KeyColumnNames(I) = DataTable1.PrimaryKey(I).ColumnName;
 }
 //Look at each row in the second table.
 foreach (Data.DataRow RowInTable2 in DataTable2.Rows) {
  //Create a flag to record if the rows are different or not.
  bool RowChanged = false;
  //Create an array to store the key values.
  string[] RowKeys = new string[KeyColumnNames.Length];
  //Get the key values from the current row in the second table.
  for (int I = 0; I <= RowKeys.Length - 1; I++) {
   RowKeys(I) = RowInTable2.Item(KeyColumnNames(I));
  }
  //Look for a row in the first table that matches the current row in the second table.
  Data.DataRow RowInTable1 = DataTable1.Rows.Find(RowKeys);
  //If a match was found...
  if (RowInTable1 != null) {
   //Look at each column.
   foreach (Data.DataColumn ColumnInTable1 in DataTable1.Columns) {
    //Get the column number
    int ColumnIndex = ColumnInTable1.Ordinal;
    //Figure out what type of data is in the column.
    Type ColumnType = ColumnInTable1.DataType;
    //Compair the cell of this column in both of the rows to see if they match.
    //The cells must be converted to the correct type before comparison because nulls will cause it to fail.
    if (Convert.ChangeType(RowInTable1.Item(ColumnIndex), ColumnType) != Convert.ChangeType(RowInTable2.Item(ColumnIndex), ColumnType)) {
     //The cells do not match, so flag the change.
     RowChanged = true;
     //No use looking at the rest of the cells, so leave the for/next loop.
     break; // TODO: might not be correct. Was : Exit For
    }
   }
  } else {
   //The row in the second table does not exist in the first table so add this row to the table of modified rows.
   RowChanged = true;
  }
  if (RowChanged == true) {
   //Something in the current row was changed, so add it to the table to be returned by this function.
   ModifiedDataTable.Rows.Add(RowInTable2.ItemArray);
  }
 }
 Debug.WriteLine(ModifiedDataTable.Rows.Count + " records were changed.");
 return ModifiedDataTable;
}

Remove all nulls from a data table.

public void RemoveAllNullsFromDataTable(Data.DataTable TheDataTable)
{
 foreach (Data.DataRow RowInTable in TheDataTable.Rows) {
  foreach (Data.DataColumn ColumnInTable in TheDataTable.Columns) {
   int ColumnIndex = ColumnInTable.Ordinal;
   if (object.ReferenceEquals(RowInTable.Item(ColumnIndex), DBNull.Value)) {
    Type ColumnType = ColumnInTable.DataType;
    RowInTable.Item(ColumnIndex) = Convert.ChangeType(RowInTable.Item(ColumnIndex), ColumnType);
   }
  }
 }
}

Display TimeSpan without milliseconds

TimeSpan TimeSpan1 = new TimeSpan(-12345678909876L);
Label1.Text = TimeSpan1.ToString;
Label2.Text = new TimeSpan(0, 0, TimeSpan1.TotalSeconds).ToString;

Make an Auto Generated Column in a GridView Invisible by Field Name.

foreach (TableCell GridViewTableCell in e.Row.Cells) {
 if (GridViewTableCell is DataControlFieldCell) {
  DataControlFieldCell GridViewDataCell = GridViewTableCell;
  if (GridViewDataCell.ContainingField is System.Web.UI.WebControls.AutoGeneratedField) {
   AutoGeneratedField DataCellField = GridViewDataCell.ContainingField;
   if (DataCellField.DataField == "FieldName") {
    GridViewTableCell.Visible = false;
   }
  }
 }
}

Find a value in a DataTable and return an associated value.

public object LookUpData(Data.DataTable TheTable, string SearchColumnName, object TheValue, string ResultColumnName)
{
 object ReturnValue = null;
 string RowFilterString = string.Format("Convert([{0}], 'System.String') = '{1}'", SearchColumnName, TheValue.ToString);
 if (TheTable.Columns.Contains(SearchColumnName)) {
  if (TheTable.Columns.Contains(ResultColumnName)) {
   Data.DataView TheDataView = new Data.DataView(TheTable, RowFilterString, "", Data.DataViewRowState.CurrentRows);
   Data.DataTable NewTable = TheDataView.ToTable;
   //Only Return data when there is just 1 result.
   if (NewTable.Rows.Count == 1) {
    ReturnValue = NewTable.Rows(0).Item(ResultColumnName);
   }
   if (object.ReferenceEquals(ReturnValue, DBNull.Value)) {
    ReturnValue = null;
   }
  }
 }
 return ReturnValue;
}

Get row count from ObjectDataSource

public int PublicRowCount = 0;
protected void ObjectDataSource1_Selected(object sender, System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs e)
{
 PublicRowCount = e.ReturnValue.Rows.Count;
}

Display bounds in RangeValidator errors.

protected void RangeValidator_Load(object sender, System.EventArgs e)
{
 sender.ErrorMessage = string.Format("Must be a number from {0} to {1}.", sender.MinimumValue, sender.MaximumValue);
}

Send JavaScript to Browser

ClientScriptManager SendJavaScriptToBrowser = Page.ClientScript;
string JavaScriptText = "alert('Replace this alert with the JavaScript.\\rThe script tags are automatically added for you.')";
SendJavaScriptToBrowser.RegisterClientScriptBlock(SendJavaScriptToBrowser.GetType, Now.ToBinary.ToString, JavaScriptText, true);

Change page color while reloading

protected void Page_Load(object sender, System.EventArgs e)
{
 ClientScriptManager ColorPageOnUnload = Page.ClientScript;
 ColorPageOnUnload.RegisterClientScriptBlock(ColorPageOnUnload.GetType, "ColorPageOnUnload", "window.onbeforeunload = ColorPageOnUnload; function ColorPageOnUnload(){document.body.style.backgroundColor = 'Gray'; document.body.style.opacity = 0.5;}", true);
}

Transpose DataTable (swap rows with columns)

Data.DataTable NewTable = TransposeTable(OldTable);
private Data.DataTable TransposeTable(Data.DataTable InputTable)
{
 Data.DataTable OutputTable = new Data.DataTable();
 OutputTable.Columns.Add(InputTable.Columns(0).ColumnName);
 foreach (Data.DataRow InputRow in InputTable.Rows) {
  string NewColumnName = InputRow.Item(0);
  OutputTable.Columns.Add(NewColumnName);
 }
 for (int RowCount = 1; RowCount <= InputTable.Columns.Count - 1; RowCount++) {
  Data.DataRow NewRow = OutputTable.NewRow;
  NewRow.Item(0) = InputTable.Columns(RowCount).ColumnName;
  for (int ColumnCount = 0; ColumnCount <= InputTable.Rows.Count - 1; ColumnCount++) {
   string ColumnValue = InputTable.Rows(ColumnCount)(RowCount);
   NewRow(ColumnCount + 1) = ColumnValue;
  }
  OutputTable.Rows.Add(NewRow);
 }
 return OutputTable;
}

Show or hide wizard steps with code

protected void Wizard1_Load(object sender, System.EventArgs e)
{
 Generic.List OriginalWizardStepTitles = new Generic.List();
 if (ViewState("OriginalWizardStepTitles") != null) {
  OriginalWizardStepTitles = ViewState("OriginalWizardStepTitles");
 }
 if (OriginalWizardStepTitles.Count == 0) {
  foreach (WizardStep PageWizardStep in Wizard1.WizardSteps) {
   OriginalWizardStepTitles.Add(PageWizardStep.Title);
  }
  ViewState("OriginalWizardStepTitles") = OriginalWizardStepTitles;
 }
}

protected void Wizard1_PreRender(object sender, System.EventArgs e)
{
 Generic.List AllowedWizardStepList = new Generic.List();
 AllowedWizardStepList.Add(Wizard1.WizardSteps.Item(0).Title);
 //Only the steps added here will be visible.
 AllowedWizardStepList.Add("Step 1");
 AllowedWizardStepList.Add("Step 3");
 AllowedWizardStepList.Add(Wizard1.WizardSteps.Item(Wizard1.WizardSteps.Count - 1).Title);
 Generic.List OriginalWizardStepTitles = new Generic.List();
 OriginalWizardStepTitles = ViewState("OriginalWizardStepTitles");
 foreach (WizardStep PageWizardStep in Wizard1.WizardSteps) {
  int PageWizardStepIndex = PageWizardStep.Wizard.WizardSteps.IndexOf(PageWizardStep);
  //Hide all wizard steps.
  PageWizardStep.Title = "";
  //Show a wizard step only if it is the allowed list.
  if (AllowedWizardStepList.Contains(OriginalWizardStepTitles.Item(PageWizardStepIndex))) {
   PageWizardStep.Title = OriginalWizardStepTitles.Item(PageWizardStepIndex);
  }
 }
}

protected void Wizard1_ActiveStepChanged(object sender, System.EventArgs e)
{
 if (string.IsNullOrEmpty(Wizard1.ActiveStep.Title)) {
  Wizard1.ActiveStepIndex += 1;
 }
}

Replace any nulls in a DataRow with default data.

public void ReplaceNulls(Data.DataRow TheRow)
{
 //Replace any row items containg null data with the default data for this item's data type.
 for (int I = 0; I <= TheRow.Table.Columns.Count - 1; I++) {
  Data.DataColumn TableColumn = TheRow.Table.Columns(I);
  Type ColumnType = TableColumn.DataType;
  if (object.ReferenceEquals(TheRow.Item(I), DBNull.Value)) {
   if (ColumnType.FullName == "System.String") {
    TheRow.Item(I) = "";
   } else {
    TheRow.Item(I) = Activator.CreateInstance(ColumnType);
   }
  }
 }
}

Make sure read-only DetailsView fields get passed to database

protected void DetailsView1_ItemUpdating(object sender, System.Web.UI.WebControls.DetailsViewUpdateEventArgs e)
{
 //Making a DetailsView field read only will prevent the user from changing it.
 //This code will make sure that any such fields get passed during the database update.
 foreach (DataControlField DetailsViewDataControlField in sender.Fields) {
  if (DetailsViewDataControlField is BoundField) {
   BoundField DetailsViewBoundField = DetailsViewDataControlField;
   string FieldName = DetailsViewBoundField.DataField;
   if (DetailsViewBoundField.ReadOnly == true) {
    e.NewValues.Item(FieldName) = e.OldValues.Item(FieldName);
   }
  }
 }
}

Check for read-only or hidden fields in DetailsView that are not in the DataKey collection.

protected void DetailsView1_PreRender(object sender, System.EventArgs e)
{
 try {
  //Catch error when an old .NET Framework doesn't have a DetailsView.DataSourceObject available.
  object FrameworkErrorCatcher = sender.DataSourceObject;
 } catch {
  return;
 }
 if (sender.DataSourceObject is ObjectDataSource) {
  ObjectDataSource DetailsViewDataSource = sender.DataSourceObject;
  string SourceUpdateMethodName = DetailsViewDataSource.UpdateMethod;
  if (string.IsNullOrEmpty(SourceUpdateMethodName) == false) {
   foreach (DataControlField DetailsViewDataControlField in sender.Fields) {
    if (DetailsViewDataControlField is BoundField) {
     BoundField DetailsViewBoundField = DetailsViewDataControlField;
     string FieldName = DetailsViewBoundField.DataField;
     if (DetailsViewBoundField.ReadOnly == true | DetailsViewBoundField.Visible == false) {
      int DataKeyIndex = Array.IndexOf(sender.DataKeyNames, FieldName);
      if (DataKeyIndex == -1) {
       throw new ApplicationException(string.Format("Read-only or hidden field {0} is not in the {1} DateKey collection.  This field will not be returned during updates.", FieldName, sender.ID));
      }
     }
    }
   }
  }
 }
}

Trim extra spaces from DetailsView data

protected void DetailsView1_DataBound(object sender, System.EventArgs e)
{
 if (sender.CurrentMode == DetailsViewMode.Edit) {
  foreach (DetailsViewRow TrimDetailsViewRow in sender.Rows) {
   foreach (DataControlFieldCell TrimDataControlFieldCell in TrimDetailsViewRow.Cells) {
    if (TrimDataControlFieldCell.HasControls == true) {
     foreach (Control TrimControl in TrimDataControlFieldCell.Controls) {
      if (TrimControl is TextBox) {
       TextBox TrimTextBox = TrimControl;
       TrimTextBox.Text = Strings.Trim(TrimTextBox.Text);
      }
     }
    }
   }
  }
 }
}

Adjust DetailsView edit TextBox widths to fit data definition

protected void DetailsView1_DataBound(object sender, System.EventArgs e)
{
 if (sender.CurrentMode == DetailsViewMode.Edit) {
  foreach (DetailsViewRow TrimDetailsViewRow in sender.Rows) {
   foreach (DataControlFieldCell TrimDataControlFieldCell in TrimDetailsViewRow.Cells) {
    Int64 MaxColumnWidth = new Int64();
    if (TrimDataControlFieldCell.ContainingField is BoundField) {
     BoundField WidthBoundField = TrimDataControlFieldCell.ContainingField;
     string WidthFieldName = WidthBoundField.DataField;
     if (sender.DataItem is Data.DataRowView) {
      Data.DataRowView WidthDataRowView = sender.DataItem;
      Data.DataView WidthDataView = WidthDataRowView.DataView;
      Data.DataTable WidthDataTable = WidthDataView.Table;
      Data.DataColumn WidthColumn = WidthDataTable.Columns(WidthFieldName);
      MaxColumnWidth = WidthColumn.MaxLength;
     }
    }
    if (TrimDataControlFieldCell.HasControls == true) {
     foreach (Control TrimControl in TrimDataControlFieldCell.Controls) {
      if (TrimControl is TextBox) {
       TextBox TrimTextBox = TrimControl;
       TrimTextBox.Text = Strings.Trim(TrimTextBox.Text);
       if (Information.IsDate(TrimTextBox.Text) == true) {
        MaxColumnWidth = 27;
       }
       if (MaxColumnWidth > 0) {
        if (MaxColumnWidth > 253) {
         TrimTextBox.Width = new WebControls.Unit("97%");
        } else {
         TrimTextBox.Width = new WebControls.Unit(MaxColumnWidth + 2 + "ex");
        }
       }
      }
     }
    }
   }
  }
 }
}

Generic data viewer with filter

Data.DataTable ThisDataTable = new Data.DataTable();
ThisDataTable.ReadXml("C:\\TableData.xml");
//This code requires a DropDownList called ColumnsDropDownList
if (ColumnsDropDownList.Items.Count < 1) {
 foreach (Data.DataColumn ThisColumn in ThisDataTable.Columns) {
  ColumnsDropDownList.Items.Add(ThisColumn.ColumnName);
 }
}
Data.DataView FilteredDataView = ThisDataTable.DefaultView;
//This code requires a TextBox called SearchTextBox
if (!string.IsNullOrEmpty(SearchTextBox.Text)) {
 string FilterText = string.Format("convert([{0}],'System.String') like '%{1}%'", ColumnsDropDownList.SelectedValue, SearchTextBox.Text);
 FilteredDataView = new Data.DataView(ThisDataTable, FilterText, null, Data.DataViewRowState.CurrentRows);
}
GridView1.DataSource = FilteredDataView;
GridView1.DataBind();

Determine if a file is locked.

public static bool IsFileLocked(string FullPathAndFileName)
{

 bool IsLocked = false;
 System.IO.FileStream LockTextFileStream = null;
 try {
  LockTextFileStream = new System.IO.FileStream(FullPathAndFileName, IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.None);
 } catch {
  IsLocked = true;
 } finally {
  if (LockTextFileStream != null) {
   LockTextFileStream.Close();
  }
 }
 return IsLocked;
}

Send a GridView to Excel when a button is clicked.

Add EnableEventValidation="false" to <%@ Page %> tag.

protected void Button1_Click(object sender, System.EventArgs e)
{
 Response.Clear();
 Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
 Response.Charset = "";
 // If you want the option to open the Excel file without saving than
 // comment out the line below
 // Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.ContentType = "application/vnd.xls";
 System.IO.StringWriter stringWrite = new System.IO.StringWriter();
 System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
 GridView1.RenderControl(htmlWrite);
 Response.Write(stringWrite.ToString());
 Response.End();
}

Load an Excel spreadsheet file into a web page GridView

protected void Page_Load(object sender, System.EventArgs e)
{
 string ExcelFile = "C:\\ExcelSpreadsheetFile.xlsx";
 string ExcelConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
 System.Data.OleDb.OleDbConnection DataSource = new System.Data.OleDb.OleDbConnection(ExcelConnection);
 DataSource.Open();
 Data.DataTable ExcelTables = new Data.DataTable();
 ExcelTables = DataSource.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
 dynamic FirstSheetName = ExcelTables.Rows(0)("TABLE_NAME");
 Data.OleDb.OleDbDataAdapter DataAdapter1 = new Data.OleDb.OleDbDataAdapter("Select * from [" + FirstSheetName + "]", ExcelConnection);
 Data.DataTable DataTable1 = new Data.DataTable();
 DataAdapter1.Fill(DataTable1);
 DataAdapter1.Dispose();
 DataSource.Dispose();
 GridView1.DataSource = DataTable1;
 GridView1.DataBind();
}

Convert a Windows path to a URL

public string ConvertWindowsPathToUrl(string WindowsPathAndFilename)
{
 string ReturnValue = WindowsPathAndFilename;
 //Make sure the file really exists.
 if (My.Computer.FileSystem.FileExists(WindowsPathAndFilename) == true) {
  IO.FileInfo WindowsFileInfo = My.Computer.FileSystem.GetFileInfo(WindowsPathAndFilename);
  dynamic WindowsFullFilename = WindowsFileInfo.FullName;
  string ThisPageWindowsPath = Request.PhysicalPath;
  IO.FileInfo ThisPageFileInfo = My.Computer.FileSystem.GetFileInfo(ThisPageWindowsPath);
  string ThisPageFolder = ThisPageFileInfo.Directory.FullName;
  string ThisPageUrl = Page.ResolveClientUrl(Request.CurrentExecutionFilePath);
  string ThisPageUrlFolder = System.Web.VirtualPathUtility.GetDirectory(ThisPageUrl);
  if (WindowsFullFilename.Contains(ThisPageFolder) == true) {
   //Only return a URL if the path to the file is the same as or under the path to this page.
   string UrlText = WindowsFullFilename;
   UrlText = UrlText.Replace(ThisPageFolder + "\\", ThisPageUrlFolder);
   UrlText = UrlText.Replace("\\", "/");
   UrlText = System.Uri.EscapeUriString(UrlText);
   ReturnValue = UrlText;
  }
 }
 return ReturnValue;
}

Custom GridView Pager

        <asp:GridView ID="TheGridView" runat="server" AllowPaging="True" PageSize="1">
            <PagerSettings Position="Top" />
            <PagerTemplate>
                <asp:LinkButton CommandName="Page" CommandArgument="First" ID="FirstLinkButton" runat="server">╟</asp:LinkButton>
                <asp:LinkButton CommandName="Page" CommandArgument="Prev" ID="PrevLinkButton" runat="server">├</asp:LinkButton>
                [Page
                <asp:DropDownList ID="PageDropDownList" runat="server" OnPreRender="PageDropDownList_PreRender" AutoPostBack="True" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged">
                </asp:DropDownList>
                of
                <%= TheGridView.PageCount%>]
                <asp:LinkButton CommandName="Page" CommandArgument="Next" ID="NextLinkButton" runat="server">┤</asp:LinkButton>
                <asp:LinkButton CommandName="Page" CommandArgument="Last" ID="LastLinkButton" runat="server">╢</asp:LinkButton>
                 Records per page: <asp:TextBox ID="PageSizeTextBox" Style="font-family: 'Courier New', Courier, monospace; color: #000000; text-align: center; width: 3em; vertical-align: middle;" runat="server" ToolTip="Type the number of records you want to see at one time, then press Enter." OnPreRender="PageSizeTextBox_PreRender" OnTextChanged="PageSizeTextBox_TextChanged" MaxLength="3"></asp:TextBox>
                 <asp:RangeValidator ID="PageSizeRangeValidator" runat="server" BackColor="Yellow" ControlToValidate="PageSizeTextBox" ErrorMessage="Must be a number from 1 to 999." ForeColor="Red" MaximumValue="999" MinimumValue="1" SetFocusOnError="True" Display="Dynamic" Type="Integer"></asp:RangeValidator>
            </PagerTemplate>
        </asp:GridView>

protected void PageDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
{
 DropDownList PageDropDownList = (DropDownList)sender;
 GridView ThisGridView = (GridView)PageDropDownList.NamingContainer.NamingContainer;
 ThisGridView.PageIndex = PageDropDownList.SelectedIndex;
 ThisGridView.DataBind();
}

protected void PageDropDownList_PreRender(object sender, System.EventArgs e)
{
 DropDownList PageDropDownList = (DropDownList)sender;
 PageDropDownList.Items.Clear();
 GridView ThisGridView = (GridView)PageDropDownList.NamingContainer.NamingContainer;
 for (int I = 1; I <= ThisGridView.PageCount; I++) {
  ListItem PageListItem = new ListItem();
  PageListItem.Text = I.ToString;
  PageListItem.Value = (I - 1).ToString;
  if (ThisGridView.PageIndex + 1 == I) {
   PageListItem.Selected = true;
  }
  PageDropDownList.Items.Add(PageListItem);
 }
}

protected void PageSizeTextBox_PreRender(object sender, System.EventArgs e)
{
 TextBox ThisTextBox = (TextBox)sender;
 GridView ThisGridView = (GridView)ThisTextBox.NamingContainer.NamingContainer;
 ThisTextBox.Text = ThisGridView.PageSize.ToString;
}

protected void PageSizeTextBox_TextChanged(object sender, System.EventArgs e)
{
 TextBox ThisTextBox = (TextBox)sender;
 GridView ThisGridView = (GridView)ThisTextBox.NamingContainer.NamingContainer;
 ThisGridView.PageIndex = 1;
 ThisGridView.PageSize = Convert.ToInt32(ThisTextBox.Text);
 ThisGridView.TopPagerRow.Visible = true;
}

Log program activity

public void LogActivity(string ActivityText, bool IsError = null)
{
 System.DateTime TimeNow = Now;
 ActivityLogRichTextBox.SelectionColor = Color.DarkBlue;
 ActivityLogRichTextBox.AppendText(ControlChars.CrLf + TimeNow.ToString("ddd yyyy-MM-dd hh:mm:ss.fff"));
 ActivityLogRichTextBox.SelectionColor = Color.Black;
 if (IsError != null) {
  if (IsError == true) {
   ActivityLogRichTextBox.SelectionColor = Color.Red;
  }
 }
 ActivityLogRichTextBox.AppendText(" " + ActivityText + ControlChars.CrLf);
 ActivityLogRichTextBox.ScrollToCaret();
 string LastWeeksLogFile = Application.ExecutablePath + ".ActivityLog." + TimeNow.AddDays(1).ToString("ddd") + ".txt";
 if (My.Computer.FileSystem.FileExists(LastWeeksLogFile)) {
  My.Computer.FileSystem.DeleteFile(LastWeeksLogFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently);
 }
 My.Computer.FileSystem.WriteAllText(Application.ExecutablePath + ".ActivityLog." + TimeNow.ToString("ddd") + ".txt", ControlChars.CrLf + TimeNow.ToString("ddd yyyy-MM-dd hh:mm:ss.fff") + " " + ActivityText + ControlChars.CrLf, true);
 Application.DoEvents();
}

Redirect to another page and preserve any passed parameters.

protected void Page_Init(object sender, System.EventArgs e)
{
 //Redirect to another page and preserve any passed parameters.
 string ThisPageUrl = Request.RawUrl;
 string ThisPageFile = IO.Path.GetFileName(Request.Path);
 string RedirectPageFile = "RedirectPage.aspx";
 string RedirectPageUrl = ThisPageUrl.Replace(ThisPageFile, RedirectPageFile);
 Response.Redirect(RedirectPageUrl);
}

Create table from database query

protected Data.DataTable GetDataTableFromDatabase(string ConnectionString, string SelectString)
{
 Data.DataTable QueryResultsDataTable = new Data.DataTable();
 //To get the connection string:  Server Explorer... Data Connections... Select a .dbo database... Press F4... Copy connection string to the clipboard.
 System.Data.SqlClient.SqlDataAdapter DataAdapter = new System.Data.SqlClient.SqlDataAdapter(SelectString, ConnectionString);
 DataAdapter.SelectCommand.CommandTimeout = 100;
 DataAdapter.Fill(QueryResultsDataTable);
 return QueryResultsDataTable;
}

Do not allow future dates in calendar control

protected void Calendar1_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
 if (e.Day.Date > Today) {
  e.Day.IsSelectable = false;
 }
}

A button that can only be clicked once

        <asp:Button 
        ID="Button1" 
        runat="server" 
        onclientclick="this.value='Working...'; this.enabled=false; this.style.opacity=0.4;" 
        Text="Button" />

Send a file via FTP

private void Form1_Load(object sender, System.EventArgs e)
{
 this.Show();
 Application.DoEvents();
 if (My.Computer.FileSystem.DirectoryExists("C:\\Temp\\") == false) {
  My.Computer.FileSystem.CreateDirectory("C:\\Temp");
 }
 My.Computer.FileSystem.WriteAllText("C:\\Temp\\Temp.tmp", "Temp", false);
 FtpUpload("C:\\Temp\\Temp.tmp", "ftp://Example.com/", "Username", "Password");
}

private void FtpUpload(string PathAndFilenameToSendString, string FtpServerUrlString, string FtpUsernameString, string FtpPasswordString)
{
 if (FtpServerUrlString.StartsWith("ftp://", true, null) == false) {
  FtpServerUrlString = "ftp://" + FtpServerUrlString;
 }
 if (FtpServerUrlString.EndsWith("/") == false) {
  FtpServerUrlString += "/";
 }
 System.IO.FileInfo FileToSendInfo = My.Computer.FileSystem.GetFileInfo(PathAndFilenameToSendString);
 if (FileToSendInfo.Exists == false) {
  System.Diagnostics.Debug.WriteLine("File does not exist: " + FileToSendInfo.FullName);
  return;
 }
 FtpServerUrlString += FileToSendInfo.Name;
 System.Net.NetworkCredential FtpServerCredentials = new System.Net.NetworkCredential(FtpUsernameString, FtpPasswordString);
 Net.FtpWebRequest FtpWebRequest = (Net.FtpWebRequest)Net.WebRequest.Create(FtpServerUrlString);
 FtpWebRequest.UsePassive = false;
 FtpWebRequest.Method = Net.WebRequestMethods.Ftp.UploadFile;
 FtpWebRequest.Credentials = FtpServerCredentials;
 System.IO.FileStream FileStreamReader = new System.IO.FileStream(PathAndFilenameToSendString, System.IO.FileMode.Open);
 byte[] FileStreamBuffer = new byte[Convert.ToInt32(FileStreamReader.Length - 1) + 1];
 FileStreamReader.Read(FileStreamBuffer, 0, FileStreamBuffer.Length);
 FileStreamReader.Close();
 FtpWebRequest.ContentLength = FileStreamBuffer.Length;
 System.Diagnostics.Debug.WriteLine("Sending file: " + FtpServerUrlString);
 try {
  System.IO.Stream FileStream = FtpWebRequest.GetRequestStream;
  FileStream.Write(FileStreamBuffer, 0, FileStreamBuffer.Length);
  FileStream.Close();
 } catch (Exception ExceptionError) {
  System.Diagnostics.Debug.WriteLine(ExceptionError.Message);
  return;
 }
 Net.FtpWebResponse FtpServerResponse = (Net.FtpWebResponse)FtpWebRequest.GetResponse;
 System.Diagnostics.Debug.Write("Server reports: " + Strings.Trim(FtpServerResponse.StatusDescription));
 if (FtpServerResponse.StatusCode == System.Net.FtpStatusCode.ClosingData) {
  FileSystem.Kill(PathAndFilenameToSendString);
  System.Diagnostics.Debug.WriteLine("Sent file deleted: " + PathAndFilenameToSendString);
 }
 FtpServerResponse.Close();
}

Break up ViewState

protected void Page_PreInit(object sender, System.EventArgs e)
{
 //MaxPageStateFieldLength can only be set in the PreInit event.
 Page.MaxPageStateFieldLength = 32767;
}

Calculate first and last day of week, month, year

System.DateTime SelectedDate = Today;
System.DateTime FirstDayOfWeekDate = SelectedDate.AddDays(SelectedDate.DayOfWeek * -1);
System.DateTime LastDayOfWeekDate = FirstDayOfWeekDate.AddDays(6);
System.DateTime FirstDayOfMonthDate = new System.DateTime(SelectedDate.Year, SelectedDate.Month, 1);
System.DateTime LastDayOfMonthDate = new System.DateTime(SelectedDate.Year, SelectedDate.Month, System.DateTime.DaysInMonth(SelectedDate.Year, SelectedDate.Month));
System.DateTime FirstDayOfYearDate = new System.DateTime(SelectedDate.Year, 1, 1);
System.DateTime LastDayOfYearDate = new System.DateTime(SelectedDate.Year, 12, System.DateTime.DaysInMonth(SelectedDate.Year, 12));
int DaysInTheYear = new System.DateTime(SelectedDate.Year, 12, System.DateTime.DaysInMonth(SelectedDate.Year, 12)).DayOfYear;

Get authenticated username

System.Security.Principal.IIdentity CurrentUserIdentity = HttpContext.Current.User.Identity;
System.Security.Principal.WindowsIdentity CurrentUserWindowsIdentity = (System.Security.Principal.WindowsIdentity)CurrentUserIdentity;
System.Diagnostics.Debug.Write(CurrentUserWindowsIdentity.Name);

Send an email

private void SendEmail(string FromEmailAddressText, string[] ToEmailAddressesText, string SubjectText, string EmailBodyText, string EmailServerNameText, string[] BccEmailAddressesText = null)
{
 Net.Mail.MailMessage EmailMailMessage = new Net.Mail.MailMessage();
 EmailMailMessage.From = new Net.Mail.MailAddress(FromEmailAddressText);
 foreach (string ToEmailAddressText in ToEmailAddressesText) {
  EmailMailMessage.To.Add(ToEmailAddressText);
 }
 if (BccEmailAddressesText != null) {
  foreach (void BccEmailAddressText_loopVariable in BccEmailAddressesText) {
   BccEmailAddressText = BccEmailAddressText_loopVariable;
   EmailMailMessage.Bcc.Add(BccEmailAddressText);
  }
 }
 EmailMailMessage.Subject = SubjectText;
 EmailMailMessage.Body = EmailBodyText;
 Net.Mail.SmtpClient EmailSmtpClient = new Net.Mail.SmtpClient(EmailServerNameText);
 EmailSmtpClient.UseDefaultCredentials = false;
 EmailSmtpClient.Credentials = new System.Net.NetworkCredential(System.Net.WebUtility.HtmlDecode("Username"), System.Net.WebUtility.HtmlDecode("Password"));
 EmailSmtpClient.Send(EmailMailMessage);
}

Create an array from a column of data in a table

protected void Page_Load(object sender, System.EventArgs e)
{
 Data.DataTable DataTable1 = new Data.DataTable();
 DataTable1.ReadXml("C:\\Data.xml");
 string[] ColumnValues = DataTableColumnValuesToStringArray(DataTable1, "ColumnName");
}

public string[] DataTableColumnValuesToStringArray(Data.DataTable PassedDataTable, string PassedColumnName)
{
 string[] functionReturnValue = null;
 if ((PassedDataTable.Columns.Contains(PassedColumnName) == false) | (PassedDataTable.Rows.Count < 1)) {
  return null;
  return functionReturnValue;
 }
 string[] ReturnValues = new string[PassedDataTable.Rows.Count];
 for (int i = 0; i <= PassedDataTable.Rows.Count - 1; i++) {
  ReturnValues(i) = Convert.ToString(PassedDataTable.Rows(i).Item(PassedColumnName));
 }
 return ReturnValues;
 return functionReturnValue;
}

Get unique values from entire table.

protected void Page_Load(object sender, System.EventArgs e)
{
 Data.DataSet DataSet1 = new Data.DataSet();
 DataSet1.ReadXml("C:\\Temp\\DataTable1.xml");
 Data.DataTable DataTable1 = DataSet1.Tables(0);
 Data.DataTable UniqueValuesInDataTable = GetUniqueTableValues(DataTable1);
}

protected Data.DataTable GetUniqueTableValues(Data.DataTable ValuesDataTable)
{
 Data.DataTable ReturnValuesDataTable = null;
 Data.DataTable UniqueColumnValuesDataTable = new Data.DataTable();
 UniqueColumnValuesDataTable.Columns.Add("UniqueValues");
 foreach (Data.DataColumn ValuesDataColumn in ValuesDataTable.Columns) {
  Data.DataTable UniqueValuesInThisColumnDataTable = ValuesDataTable.DefaultView.ToTable(true, ValuesDataColumn.ColumnName);
  UniqueValuesInThisColumnDataTable.Columns(0).ColumnName = "UniqueValues";
  foreach (Data.DataRow UniqueValuesDataRow in UniqueValuesInThisColumnDataTable.Rows) {
   UniqueColumnValuesDataTable.ImportRow(UniqueValuesDataRow);
  }
 }
 UniqueColumnValuesDataTable.DefaultView.Sort = "UniqueValues";
 ReturnValuesDataTable = UniqueColumnValuesDataTable.DefaultView.ToTable(true, "UniqueValues");
 return ReturnValuesDataTable;
}

Get text of uploaded file without saving to disc

protected void UploadButton_Click(object sender, System.EventArgs e)
{
 if (FileUpload1.FileName > "") {
  dynamic UploadedFileMemoryStream = new IO.MemoryStream(FileUpload1.FileBytes);
  string UploadedFileText = System.Text.Encoding.UTF8.GetString(UploadedFileMemoryStream.ToArray);
 }
}

Evaluate math expression from text

protected void Page_Load(object sender, System.EventArgs e)
{
 double OnePlusOne = EvaluateExpression("1+1");
 double SixMinusTwo = EvaluateExpression("6-2");
 double EightDividedByFour = EvaluateExpression("8/4");
 double FifteenSixteenths = EvaluateExpression("15/16");
 double RemainderOfFiveDividedByTwo = EvaluateExpression("5%2");
 double MultipleExpressions = EvaluateExpression("(1+1)*(6-2)-(8/4)/(15/16)");
 double InvalidOperation = EvaluateExpression("0/0");
}

public double EvaluateExpression(string ExpressionString)
{
 double ReturnValue = null;
 Data.DataTable ComputeDataTable = new Data.DataTable();
 try {
  ReturnValue = Convert.ToDouble(ComputeDataTable.Compute(ExpressionString, null));
  //Can only evaluate using the following arithmetic operations:
  //+ (addition), - (subtraction), * (multiplication), / (division), % (modulus)
 } catch {
 }
 return ReturnValue;
}

Show a folder with a file selected

private void Form1_Load(object sender, System.EventArgs e)
{
 ShowFile("C:\\config.sys");
}

private void ShowFile(string PathAndFilename)
{
 FileInfo FileData = My.Computer.FileSystem.GetFileInfo(PathAndFilename);
 if (FileData.Exists == true) {
  Process.Start("explorer.exe", "/select," + FileData.FullName);
 }
}

Convert integer array to string array

protected void Page_Load(object sender, System.EventArgs e)
{
	int[] IntegerArray = {
		1,
		2,
		3
	};
	string[] TextArray = ToStringArray(IntegerArray);
	string JoinedNumbers = Strings.Join(TextArray, ", ");
}

protected string[] ToStringArray(int[] IntegerArray)
{
	string[] NumbersText = Array.ConvertAll(IntegerArray, new Converter(Convert.ToString));
	return NumbersText;
}

Get Outlook folders and email messages

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class ThisAddIn
{
 private Outlook.Inspectors withEventsField_PublicOutlookInspectors;
 public Outlook.Inspectors PublicOutlookInspectors {
  get { return withEventsField_PublicOutlookInspectors; }
  set {
   if (withEventsField_PublicOutlookInspectors != null) {
    withEventsField_PublicOutlookInspectors.NewInspector -= PublicOutlookInspectors_NewInspector;
   }
   withEventsField_PublicOutlookInspectors = value;
   if (withEventsField_PublicOutlookInspectors != null) {
    withEventsField_PublicOutlookInspectors.NewInspector += PublicOutlookInspectors_NewInspector;
   }
  }

 }
 private void ThisAddIn_Startup(object sender, System.EventArgs e)
 {
  PublicOutlookInspectors = this.Application.Inspectors;
  Outlook.Application OutlookApplication = new Outlook.Application[];
  Outlook._NameSpace OutlookNameSpace = (Outlook._NameSpace)OutlookApplication.GetNamespace("MAPI");
  Outlook.MAPIFolder OutlookMapiFolder = OutlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent;
  //Dim OutlookExplorer As Outlook._Explorer = OutlookMapiFolder.GetExplorer(False)
  OutlookNameSpace.Logon(string.Empty, string.Empty, false, true);
  Outlook.Items OutlookMapiFolderItems = OutlookMapiFolder.Items;
  GetFoldersRecursive(OutlookMapiFolder);
 }

 public void GetFoldersRecursive(Outlook.MAPIFolder OutlookMAPIFolder)
 {
  if (OutlookMAPIFolder.Folders.Count == 0) {
   System.Diagnostics.Debug.WriteLine("Folder: " + OutlookMAPIFolder.FullFolderPath);
   foreach (object OutlookMAPIFolderItem in OutlookMAPIFolder.Items) {
    if ((OutlookMAPIFolderItem) is Outlook.MailItem) {
     System.Diagnostics.Debug.WriteLine("Subject: " + OutlookMAPIFolderItem.Subject);
    }
   }
  } else {
   foreach (Outlook.MAPIFolder OutlookMAPISubFolder in OutlookMAPIFolder.Folders) {
    GetFoldersRecursive(OutlookMAPISubFolder);
   }
  }
 }


 private void ThisAddIn_Shutdown()
 {
 }

 private void PublicOutlookInspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
 {
  Outlook.MailItem OutlookMailItem = Inspector.CurrentItem as Outlook.MailItem;
  if (OutlookMailItem != null) {
   if (OutlookMailItem.EntryID == null) {
    OutlookMailItem.Subject = "This text was added by using code";
    OutlookMailItem.Body = "This text was added by using code";
   }
  }
 }
 public ThisAddIn()
 {
  Shutdown += ThisAddIn_Shutdown;
  Startup += ThisAddIn_Startup;
 }

}

Add an Outlook calender item with code

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class ThisAddIn
{


 public Outlook.Inspectors PublicOutlookInspectors;
 private void ThisAddIn_Startup(object sender, System.EventArgs e)
 {
  NewOutlookAppointmentUsingCreateItem();
 }

 private void NewOutlookAppointmentUsingCreateItem()
 {
  Outlook.Application OutlookApplication = new Outlook.Application[];
  Outlook.AppointmentItem OutlookAppointmentItem = OutlookApplication.CreateItem(Outlook.OlItemType.olAppointmentItem);
  if (OutlookAppointmentItem != null) {
   OutlookAppointmentItem.Recipients.Add("User.Name@Sample.Com");
   OutlookAppointmentItem.Body = "Test Outlook appointment generated by code.";
   OutlookAppointmentItem.Subject = "Test Outlook appointment generated by code.";
   OutlookAppointmentItem.Location = "Test Outlook appointment generated by code.";
   OutlookAppointmentItem.Start = Now.AddHours(1);
   OutlookAppointmentItem.End = Now.AddHours(2);
   OutlookAppointmentItem.Importance = Outlook.OlImportance.olImportanceNormal;
   OutlookAppointmentItem.RequiredAttendees = OutlookAppointmentItem.Organizer;
   OutlookAppointmentItem.Display(true);
   try {
    OutlookAppointmentItem.Save();
    Runtime.InteropServices.Marshal.ReleaseComObject(OutlookAppointmentItem);
   } catch {
   }
  }
 }
 public ThisAddIn()
 {
  Startup += ThisAddIn_Startup;
 }

}

Insert rows in a GridView

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow) {
  Data.DataRowView eRowDataItem = e.Row.DataItem;
  Data.DataRow eRowDataItemRow = eRowDataItem.Row;
  string Comments = "";
  if (!object.ReferenceEquals(eRowDataItemRow.Item("Comments"), DBNull.Value)) {
   Comments = eRowDataItemRow.Item("Comments");
  }
  if (!string.IsNullOrEmpty(Comments)) {
   Table eRowParentTable = e.Row.Parent;
   GridViewRow NewGridViewRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
   TableCell NewTableCell = new TableCell();
   NewTableCell.ColumnSpan = 6;
   NewTableCell.Width = Unit.Percentage(100);
   NewTableCell.Text = Comments;
   NewGridViewRow.Cells.Add(NewTableCell);
   HtmlGenericControl NewSpan = new HtmlGenericControl("span");
   NewSpan.InnerText = Comments;
   NewTableCell.Controls.Add(NewSpan);
   eRowParentTable.Rows.AddAt(eRowParentTable.Rows.Count, NewGridViewRow);
  }
 }
}

Remove Rich Text Formatting from a string

Regex RemoveRtf = new Regex("\\{\\*?\\\\[^{}]+}|[{}]|\\\\\\n?[A-Za-z]+\\n?(?:-?\\d+)?[ ]?");
string TextWithRtf = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Courier New;}}{\\colortbl ;\\red8\\green0\\blue0;}{\\*\\generator Msftedit 5.41.15.1515;}\\viewkind4\\uc1\\pard\\cf1\\highlight0\\f0\\fs20 The quick brown fox jumps over a lazy dog.\\par}";
string TextWithoutRtf = RemoveRtf.Replace(TextWithRtf, "");

Copy all style attributes from a master GridView to another GridView

protected void GridView1_Init(object sender, System.EventArgs e)
{
 GridView ThisGridView = sender;
 ThisGridView.ApplyStyle(MasterGridView.ControlStyle);
}

Highlight row and cell when the mouse hovers over them

<style type="text/css">
    tr:hover
    {
        opacity: 0.7;
        color: DarkRed;
        background-color: White;
    }
    td
    {
        padding-left: 1ex;
        padding-right: 1ex;
    }
    td:hover
    {
        opacity: 1.0;
        background-color: Gold;
    }
</style>

Get a Cyclic Redundancy Check of a value

private string GetCrc(string Value)
{
 byte[] TextBytes = System.Text.Encoding.UTF8.GetBytes(Value);
 System.Security.Cryptography.MD5Cng Md5 = new System.Security.Cryptography.MD5Cng();
 Md5.ComputeHash(TextBytes);
 System.Text.StringBuilder StringBuilderBuffer = new System.Text.StringBuilder();
 foreach (byte HashByte in Md5.Hash) {
  StringBuilderBuffer.Append(HashByte.ToString("X"));
 }
 return StringBuilderBuffer.ToString;
}

Confirm page exit when there is an Update button on the page.

<script type="text/javascript">
        function getElementsByValue(val, src) {
            var tags;
            var matches = [];
            var i = end = 0;
            if (document.getElementsByTagName) {
                if (!src) {
                    src = document;
                } else if (typeof (src) === 'string') {
                    src = document.getElementById(src);
                }
                tags = src.getElementsByTagName('input');
                for (i, end = tags.length; i < end; i++) {
                    if (tags[i].value && tags[i].value == val) {
                        matches.push(tags[i].id);
                        tags[i] = null;
                    }
                }
            }
            return matches;
        }
        var UpdateButtons = getElementsByValue("Update");
        window.onbeforeunload = function () {
            if (UpdateButtons.length > 0) {
                confirm('You were editing, are you saving changes?')
            }
        }
    </script>

Correct picture file extension

private void CorrectPictureExtention(string PictureFile)
{
 FileInfo FileData = My.Computer.FileSystem.GetFileInfo(PictureFile);
 if (FileData.Exists == true) {
  Bitmap PictureBitmap = null;
  try {
   PictureBitmap = Bitmap.FromFile(PictureFile);
  } catch {
  }
  if (PictureBitmap != null) {
   Dictionary GuidDictionary = new Dictionary();
   GuidDictionary.Add("b96b3cab-0728-11d3-9d7b-0000f81ef32e", ".Bmp");
   GuidDictionary.Add("b96b3cac-0728-11d3-9d7b-0000f81ef32e", ".Emf");
   GuidDictionary.Add("b96b3cb0-0728-11d3-9d7b-0000f81ef32e", ".Gif");
   GuidDictionary.Add("b96b3cb5-0728-11d3-9d7b-0000f81ef32e", ".Ico");
   GuidDictionary.Add("b96b3cae-0728-11d3-9d7b-0000f81ef32e", ".Jpg");
   GuidDictionary.Add("b96b3caf-0728-11d3-9d7b-0000f81ef32e", ".Png");
   GuidDictionary.Add("b96b3cb1-0728-11d3-9d7b-0000f81ef32e", ".Tif");
   GuidDictionary.Add("b96b3cad-0728-11d3-9d7b-0000f81ef32e", ".Wmf");
   string ImageType = "";
   GuidDictionary.TryGetValue(PictureBitmap.RawFormat.Guid.ToString, ImageType);
   PictureBitmap.Dispose();
   if (!string.IsNullOrEmpty(ImageType)) {
    if (!string.IsNullOrEmpty(FileData.Extension)) {
     if (FileData.Extension != ImageType) {
      My.Computer.FileSystem.RenameFile(FileData.FullName, FileData.Name.Replace(FileData.Extension, "") + ImageType);
     } else {
      My.Computer.FileSystem.RenameFile(FileData.FullName, FileData.Name + ImageType);
     }
    }
   }
  }
 }
}

Convert the first letter of each word to uppercase in some columns of a gridview

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow) {
  string[] TitleCaseFields = {
   "FieldName1",
   "FieldName2"
  };
  foreach (DataControlFieldCell GridDataControlFieldCell in e.Row.Cells) {
   BoundField GridBoundField = GridDataControlFieldCell.ContainingField;
   string GridDataField = GridBoundField.DataField;
   if (TitleCaseFields.Contains(GridDataField) == true) {
    GridDataControlFieldCell.Text = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Server.HtmlDecode(GridDataControlFieldCell.Text.ToLower));
   }
  }
 }
}

Add a header to a gridview that groups some columns

protected void ReportGridView_DataBound(object sender, System.EventArgs e)
{
 Table ExtraTable = GridView1.Controls(0);
 GridViewRow ExtraGridViewRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
 TableHeaderCell ExtraTableHeaderCell1 = new TableHeaderCell();
 ExtraTableHeaderCell1.Text = "First 2 Columns";
 ExtraTableHeaderCell1.ColumnSpan = 2;
 ExtraGridViewRow.Cells.Add(ExtraTableHeaderCell1);
 TableHeaderCell ExtraTableHeaderCell2 = new TableHeaderCell();
 ExtraTableHeaderCell2.Text = "Next 3 Columns";
 ExtraTableHeaderCell2.ColumnSpan = 3;
 ExtraGridViewRow.Cells.Add(ExtraTableHeaderCell2);
 TableHeaderCell ExtraTableHeaderCell3 = new TableHeaderCell();
 ExtraTableHeaderCell3.Text = "Last 4 Columns";
 ExtraTableHeaderCell3.ColumnSpan = 4;
 ExtraGridViewRow.Cells.Add(ExtraTableHeaderCell3);
}

CSS to display round borders and drop shadow on container

<head runat="server">
    <title></title>
    <style type="text/css">
        .RoundedShadow
        {
            border-color: Yellow;
            border-width: 5px;
            border-style: ridge;
            -webkit-border-radius: 7px;
            border-radius: 7px;
            border-collapse: separate;
            margin: 10px;
            -webkit-box-shadow: -5px -5px 7px #1a1a1a;
            background-clip: padding-box;
            box-shadow: -5px -5px 7px #1a1a1a;
        }
    </style>
</head>

Add aggregate rows to a table

protected Data.DataTable AggregatedTable(Data.DataTable TableToAggregate, string SortFieldName, string[] FieldsToAggregate)
{
 Data.DataTable ReturnTable = new Data.DataView(TableToAggregate, null, SortFieldName, Data.DataViewRowState.CurrentRows).ToTable;
 Data.DataColumn RowNumberColumn = new Data.DataColumn();
 RowNumberColumn.ColumnName = "Row~Number";
 RowNumberColumn.DataType = typeof(int);
 ReturnTable.Columns.Add(RowNumberColumn);
 Generic.List RowsToAddList = new Generic.List();
 do {
  Data.DataRow NewRow = ReturnTable.NewRow;
  ReturnTable.Rows.Add(NewRow);
  break; // TODO: might not be correct. Was : Exit Do
 } while (true);
 string LastMatch = "~";
 int LastRowNumber = new int();
 foreach (Data.DataRow ReturnRow in ReturnTable.Rows) {
  ReturnRow.Item("Row~Number") = ReturnTable.Rows.IndexOf(ReturnRow) * 2;
  LastRowNumber = ReturnRow.Item("Row~Number");
  if (LastMatch != "~") {
   if (LastMatch != ReturnRow.Item(SortFieldName).ToString) {
    Data.DataRow NewRow = ReturnTable.NewRow;
    NewRow.Item("Row~Number") = ReturnRow.Item("Row~Number") - 1;
    NewRow.Item("RowFont") = "Bold";
    if (!object.ReferenceEquals(ReturnTable.Compute("Sum(Grand_Inv_Total)", string.Format("(Exported = 'True') AND (Salesman1 = '{0}')", Server.HtmlEncode(LastMatch))), DBNull.Value)) {
     decimal Exported = ReturnTable.Compute("Sum(Grand_Inv_Total)", string.Format("(Exported = 'True') AND (Salesman1 = '{0}')", LastMatch));
     decimal ExportedPercent = Exported / ReturnTable.Compute("Sum(Grand_Inv_Total)", string.Format("(Salesman1 = '{0}')", LastMatch));
     NewRow.Item("Cust_Name") = "Exported: " + Exported.ToString("c") + Strings.StrDup(3, Strings.ChrW(160)) + ExportedPercent.ToString("p");
    }
    NewRow.Item(SortFieldName) = LastMatch;
    foreach (void AggregateField_loopVariable in FieldsToAggregate) {
     AggregateField = AggregateField_loopVariable;
     string FormatString = string.Format("Sum({0})", AggregateField);
     string FilterString = string.Format("{0} = '{1}'", SortFieldName, LastMatch.Replace("'", "''"));
     NewRow.Item(AggregateField) = ReturnTable.Compute(FormatString, FilterString);
    }
    RowsToAddList.Add(NewRow);
   }
  }
  LastMatch = ReturnRow.Item(SortFieldName).ToString;
 }
 foreach (Data.DataRow RowToAdd in RowsToAddList) {
  ReturnTable.Rows.Add(RowToAdd);
 }
 ReturnTable = new Data.DataView(ReturnTable, "[Row~Number] <> " + LastRowNumber, "Row~Number", Data.DataViewRowState.CurrentRows).ToTable;
 ReturnTable.Columns.Remove("Row~Number");
 return ReturnTable;
}

Prevent iPad from converting dates to telephone number links

<head id="Head1" runat="server">
    <meta name="format-detection" content="telephone=no" />
</head>

Prevent some content from printing

<head>
    <style type="text/css">
        @media print
        {
            .NoPrint
            {
                display: none;
            }
        }
    </style>
</head>
<body>
    <table border="2" class="NoPrint">
        <tr>
            <td>
                This content will not be printed.
            </td>
        </tr>
    </table>
    <br />
    <table border="2">
        <tr>
            <td>
                This content will be printed.
            </td>
        </tr>
    </table>
</body>

Easy password generator

VBMath.Randomize();
byte Numbers = (VBMath.Rnd() * 90) + 10;
string[] Adjectives = {
 "Good",
 "New",
 "First",
 "Last",
 "Long",
 "Great",
 "Little",
 "Own",
 "Other",
 "Old",
 "Right",
 "Big",
 "High",
 "Different",
 "Small",
 "Large",
 "Next",
 "Early",
 "Young",
 "Important",
 "Few",
 "Public",
 "Bad",
 "Same",
 "Able"
};
string[] Nouns = {
 "Times",
 "People",
 "Years",
 "Ways",
 "Days",
 "Things",
 "Men",
 "Worlds",
 "Lives",
 "Hands",
 "Parts",
 "Children",
 "Eyes",
 "Women",
 "Places",
 "Works",
 "Weeks",
 "Cases",
 "Points",
 "Governments",
 "Companies",
 "Numbers",
 "Groups",
 "Problems",
 "Facts"
};
string EasyPassword = Numbers.ToString + Adjectives(Conversion.Int(VBMath.Rnd() * Adjectives.Count)) + Nouns(Conversion.Int(VBMath.Rnd() * Nouns.Count));

Scroll to top and bottom of page

        <span style="font-size: x-small; text-decoration: underline; color: #0000FF; cursor: pointer">
            <a onclick="window.scrollTo(0, document.body.scrollHeight);">Bottom</a></span>


        <span style="font-size: x-small; text-decoration: underline; color: #0000FF; cursor: pointer">
            <a onclick="window.scrollTo(0, 0 - document.body.scrollHeight);">Top</a></span>

Join objects of any type to comma separated string

object[] ObjectArray = {
 0,
 "One",
 2.7,
 Math.PI
};
string[] StringArray = Array.ConvertAll(ObjectArray, ThisValue => ThisValue.ToString);
string JoinedText = Strings.Join(StringArray, ", ");

Countdown while page loads

string PreviousPageTitle = Page.Title;
int TotalIterations = 1000;
DateTime StartTime = Now;
for (int CurrentInteration = 0; CurrentInteration <= TotalIterations; CurrentInteration++) {
 if (CurrentInteration > 0) {
  int RemainingIterations = TotalIterations - CurrentInteration;
  float RemainingProgressPercent = 1 - CurrentInteration / TotalIterations;
  TimeSpan TimePassed = Now - StartTime;
  TimeSpan TimeToEnd = new TimeSpan(TotalIterations * TimePassed.Ticks / CurrentInteration);
  TimeSpan TimeRemaining = TimeToEnd - TimePassed;
  Threading.Thread.Sleep(18);
  Response.Flush();
  Response.Write(string.Format("<script>document.title = '{0} {1} {2}'</script>", RemainingIterations, TimeRemaining.ToString("m':'ss"), RemainingProgressPercent.ToString("p1")));
 }
}
Page.Title = PreviousPageTitle;
Response.Write("<script>document.title = '" + PreviousPageTitle + "'</script>");

Delete files over a week old

if (IsPostBack == false) {
 foreach (IO.FileInfo ActivityFileInfo in new IO.DirectoryInfo(Server.MapPath(".") + "\\ActivityFiles\\").GetFiles("*.txt")) {
  if (DateDiff(DateInterval.Day, ActivityFileInfo.CreationTime, Now) > 6) {
   ActivityFileInfo.Delete();
  }
 }
}

Default to Excel filetypes when uploading a file

<asp:FileUpload ID="FileUpload1" runat="server" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

Select an area of page on button click

<html>
<head runat="server">
    <title>Select Text</title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="SelectDiv">
            <table style="width: 100%;">
                <tr>
                    <td>Text to select.</td>
                </tr>
            </table>
        </div>
        <br />
        <asp:Button ID="SelectDataButton" runat="server" Text="Select Data" OnClientClick="selectText(); return false;" UseSubmitBehavior="False" />
    </form>
    <script type='text/javascript'>
        function selectText() {
            if (document.selection) {
                var div = document.body.createTextRange();
                div.moveToElementText(document.getElementById('SelectDiv'));
                div.select();
            }
            else {
                var div = document.createRange();
                div.setStartBefore(document.getElementById('SelectDiv'));
                div.setEndAfter(document.getElementById('SelectDiv'));
                window.getSelection().addRange(div);
            }
        }
    </script>
</body>
</html>

Epoch functions

long EpochYears = DateDiff(DateInterval.Year, System.DateTime.MinValue, Today);
long EpochQuarters = DateDiff(DateInterval.Quarter, System.DateTime.MinValue, Today);
long EpochMonths = DateDiff(DateInterval.Month, System.DateTime.MinValue, Today);
long EpochDays = DateDiff(DateInterval.Day, System.DateTime.MinValue, Today);
long EpochHours = DateDiff(DateInterval.Hour, System.DateTime.MinValue, Now);
long EpochMinutes = DateDiff(DateInterval.Minute, System.DateTime.MinValue, Now);
long EpochSeconds = DateDiff(DateInterval.Second, System.DateTime.MinValue, Now);