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;
}
}
}
Detect When Network Goes Up or Down
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;
}
Subscribe to:
Posts (Atom)