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);