CSC - Technical Notes

A personal repository of technical notes. - CSC

Credential Manager Command Line

Problem
Need to be able to change all of my stored network passwords at once.

Solution
Credential Manager Command Line utility.

References
Cmdkey
https://technet.microsoft.com/en-us/library/cc754243.aspx

Soft Reset on Windows Phone 8X by HTC

Soft Reset on Windows Phone 8X by HTC Model PM23220

Unable to remove/insert battery.

To perform reset,
1) Press and hold the Volume Down and Power keys for 10 seconds.
2) Device should restart.

Excel Alternating Rows Conditional Formatting Example

Problem
Need to format groups of matching rows with alternating colors.

Solution
Use a formula with conditional formatting.

1) Decide which column will be the "key column".
2) Sort sheet by key column.
3) Define a new Conditional Formatting column
  • Put "1" in column header row
  • Put formula in second row. Example: "=IF(A2=A1,D1,D1*-1)" where "A" is key column and "D" is Conditional Formatting column.
  • Copy formula into each row of column.

4) Define Conditional Formatting for alternating rows
  • Select all active cells in sheet
  • Click Conditional Formatting/New Rule...
  • Select Rule Type "Use a formula to determine which cells to format".
  • In "Format values where this formula is true:", define the Conditional Formatting column where = 1: Example: "=$D1=1" where "D" is Conditional Formatting column.



  • Click Format...
  • Select Fill tab, pick color, click OK, click OK.


Array Sort C# Example

Example: How to sort an array of DirectoryInfo objects by Delegate and by Lambda Expression


// Get array of directories
DirectoryInfo tempTopDirectory = new DirectoryInfo("C:\\Temp1");
DirectoryInfo[] tempSubdirectories = tempTopDirectory.GetDirectories();

// Sort directories array by Name using delegate
Array.Sort(tempSubdirectories, delegate(DirectoryInfo x, DirectoryInfo y) { return x.Name.CompareTo(y.Name); });

// Sort directories array by Name using lambda expression
Array.Sort(tempSubdirectories, (x, y) => x.Name.CompareTo(y.Name));

How to sort directories in descending order


// Sort descending by comparing "y" to "x" instead of "x" to "y".
Array.Sort(tempSubdirectories, (x, y) => y.Name.CompareTo(x.Name));

How to sort directories by creation date


// Sort by creation date time
Array.Sort(tempSubdirectories, (x, y) => x.CreationTime.CompareTo(y.CreationTime));

References

Array.Sort(T) Method (T[], Comparison(T)) (System)
http://msdn.microsoft.com/en-us/library/cxt053xf(v=vs.110).aspx

Lambda Expressions (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/bb397687.aspx

.NET Framework Cryptography Notes

.NET Framework Cryptography Model

http://msdn.microsoft.com/en-us/library/0ss79b2x(v=vs.110).aspx

Quotes from web page:

Choosing an Algorithm

You can select an algorithm for different reasons: for example, for data integrity, for data privacy, or to generate a key. Symmetric and hash algorithms are intended for protecting data for either integrity reasons (protect from change) or privacy reasons (protect from viewing). Hash algorithms are used primarily for data integrity.

Here is a list of recommended algorithms by application:

AesCryptoServiceProvider vs AesManaged

Aes is inherited by two classes: AesCryptoServiceProvider and AesManaged. The AesCryptoServiceProvider class is a wrapper around the Windows Cryptography API (CAPI) implementation of Aes, whereas the AesManaged class is written entirely in managed code. There is also a third type of implementation, Cryptography Next Generation (CNG), in addition to the managed and CAPI implementations. An example of a CNG algorithm is ECDiffieHellmanCng. CNG algorithms are available on Windows Vista and later.

You can choose which implementation is best for you. The managed implementations are available on all platforms that support the .NET Framework. The CAPI implementations are available on older operating systems, and are no longer being developed. CNG is the very latest implementation where new development will take place. However, the managed implementations are not certified by the Federal Information Processing Standards (FIPS), and may be slower than the wrapper classes.

Cryptographic Services

http://msdn.microsoft.com/en-us/library/92f9ye3s(v=vs.110).aspx

Transfer DataTable with HTTP Response

Problem
Need a simple way to transfer data with an HTTP web request/response.

Solution
Convert a DataTable to XML, transfer with HTTP, convert XML back to DataTable.

Note: This was tested with .NET 4

SimpleDataTableExport.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleDataTableExport.aspx.cs" Inherits="SimpleDataTableExport" %>

SimpleDataTableExport.aspx.cs
using System;
using System.Data;
using System.Xml;

/// <summary>
/// Simple web page to export a DataTable through an HTTP response.
/// </summary>
public partial class SimpleDataTableExport : System.Web.UI.Page
{
       protected void Page_Load(object sender, EventArgs e)
       {
              // Start response
              Response.ClearHeaders();
              Response.ClearContent();

              DataTable dataTable = null;
              try
              {
                     dataTable = GetDataTable();
              }
              catch (Exception ex)
              {
                     dataTable = null;
                     Response.StatusCode = 500;
                     Response.StatusDescription = ex.Message;
                     Response.Write(String.Format("Error message: {0}", ex.Message));
              }
              finally
              {
                     if (dataTable != null)
                     {
                           // DataTable is converted to XML and sent to the output stream.
                           XmlWriter xmlWriter = XmlWriter.Create(Response.OutputStream);
                           dataTable.WriteXml(xmlWriter, XmlWriteMode.WriteSchema);
                     }
              }

              // Complete response
              Response.Flush();
              ApplicationInstance.CompleteRequest();
       }

       private DataTable GetDataTable()
       {
              // Validate input parameters passed in query string.
              if (String.IsNullOrEmpty(Request.QueryString["parm01"]))
              {
                     throw new ApplicationException("Required parameter 'parm01' is missing.");
              }

              // Generate DataTable
              DataTable table = new DataTable("MyDataTable");
              table.Columns.Add("Column01");
              table.Columns.Add("Column02");
              DataRow row = table.NewRow();
              row["Column01"] = String.Format("'parm01' is {0}", Request.QueryString["parm01"]);
              row["Column02"] = "Value for Column02";
              table.Rows.Add(row);

              return table;
       }
}

Console application to import DataTable

using System;
using System.Data;
using System.Net;
using System.Xml;

namespace SimpleDataTableImport
{
       /// <summary>
       /// Simple Console Application to import a DataTable through an HTTP request.
       /// </summary>
       class Program
       {
              static void Main(string[] args)
              {

                     DataTable dataTable = new DataTable();
                     string errorMessage = null;

                     HttpWebRequest httpWebRequest;
                     HttpWebResponse httpWebResponse = null;
                     try
                     {
                           httpWebRequest = WebRequest.Create("http://localhost/SimpleDataTableExport.aspx?parm01=helloworld") as HttpWebRequest;
                           httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                           XmlReader xmlReader = XmlReader.Create(httpWebResponse.GetResponseStream());
                           dataTable.ReadXml(xmlReader);
                     }
                     catch (WebException webEx)
                     {
                           httpWebResponse = webEx.Response as HttpWebResponse;
                           errorMessage = String.Format("{0} - {1}", Convert.ToInt32(httpWebResponse.StatusCode).ToString(), httpWebResponse.StatusDescription);
                     }
                     catch (Exception ex)
                     {
                           errorMessage = ex.Message;
                     }
                     if (httpWebResponse != null)
                     {
                           httpWebResponse.Close();
                     }
                     if (errorMessage != null)
                     {
                           Console.WriteLine(errorMessage);
                     }

                     // Display DataTable
                     foreach (DataColumn column in dataTable.Columns)
                     {
                           Console.WriteLine(column.ColumnName);
                     }
                     foreach (DataRow row in dataTable.Rows)
                     {
                           Console.WriteLine(String.Format("{0},{1}", row["Column01"], row["Column02"]));
                     }

                     Console.ReadLine();
              }
       }
}

Results

Debug Classic ASP in Visual Studio

Note: This was tested in VS2010 and IIS 7.5.

In IIS:
  • Set up Classic ASP website in IIS.
  • Set Classic ASP application to allow ASP debugging:
    • Click on application
    • Double-click IIS/ASP
    • Open Debugging Properties
    • Enable Server-side Debugging = True
    • Click Apply
In Visual Studio:
  • Add breakpoints in server-side code of Classic ASP.
  • Start debugging:
    • Debug Menu/Attach to Process/Available Processes
    • Select w3wp.exe
    • Click Attach

HashSet to Comma Delimited String

HashSet Coding Example: A HashSet is a collection that contains no duplicate elements.

Note: Tested in .NET 4.0.

       HashSet<string> myHashSet = new HashSet<string>();
       myHashSet.Add("A");
       myHashSet.Add("B");
       myHashSet.Add("B");
       myHashSet.Add("B");
       myHashSet.Add("B");
       myHashSet.Add("X");
       myHashSet.Add("Z");
       myHashSet.Add("B");
       myHashSet.Add("A");
       string commaDelimitedString = String.Join<string>(",", myHashSet);
       // commaDelimitedString is equal to "A,B,X,Z"

References
"HashSet(T) Class (System.Collections.Generic)." MSDN – the Microsoft Developer Network. N.p., n.d. Web. 16 Oct. 2013. <http://msdn.microsoft.com/en-us/library/bb359438(v=vs.100).aspx>.

SQL Server Management Studio Settings

Miscellaneous, useful settings in SSMS.

Note: This was tested in SSMS 2012.

Assign custom colors to database servers. These colors are used on the status bar.
  1. Connect to Server
  2. Options >>
  3. Connection Properties tab
  4. Use custom color:

Change what is displayed in Tab Text (Example: Remove text that is redundant with status bar.)
  1. Tools/Options/Text Editor/Editor Tab and Status Bar/Tab Text
  2. Include database name (False)
  3. Include file name (True)
  4. Include login name (False)
  5. Include server name (False)

Copy column headers with query results
  1. Tools/Options/Query Results/SQL Server/Results to Grid
  2. Check "Include column headers when copying or saving the results"

Customize Context Menu of SSMS

Problem
Need to customize context menus (also known as shortcut menus) in SQL Server Management Studio.

Solution

Note: This was tested in SSMS 2012.

Use the same technique that is used for Visual Studio. See Customize Context Menu of Visual Studio | CSC - Technical Notes for detailed instructions.