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.

Copy Page Title and URL to Clipboard

Bookmarklet to copy page title and URL to clipboard in Internet Explorer

JavaScript:window.clipboardData.setData("Text",document.title + "\r\n" + location.href);void(0);

Drag this bookmarklet to the bookmarks bar: JavaScript:window.clipboardData.setData("Text",document.title + "\r\n" + location.href);void(0);

Bookmarklet to copy page title and URL to prompt window for copying to clipboard in Chrome

JavaScript:window.prompt("Copy page title and URL",document.title + "\r\n" + location.href);void(0);

Drag this bookmarklet to the bookmarks bar: JavaScript:window.prompt("Copy page title and URL",document.title + "\r\n" + location.href);void(0);

FULL OUTER JOIN Not Working

Problem

FULL OUTER JOIN not returning all records from right table when left table has a Search Condition in the WHERE clause.

-- Full outer join with where clause at bottom
-- Returns all records from MyTable1 where Category is 23.
-- Does not return all records from MyTable2. Only matches with MyTable1.
SELECT t1.[Code],t2.[Code]
FROM [MyTable1] t1
FULL OUTER JOIN [MyTable2] t2
      ON t2.[Code] = t1.[Code]
WHERE t1.[Category] = 23

Solution

Use a Derived Table for the left table. The Search Condition is moved from the WHERE clause to the Derived Table query.

-- Full outer join with derived table, no where clause at bottom
-- Returns all records from MyTable1 where Category is 23.
-- Returns all records from MyTable2.
SELECT t1.[Code],t2.[Code]
FROM ( SELECT * FROM [MyTable1] WHERE [Category] = 23 ) t1
FULL OUTER JOIN [MyTable2] t2
      ON t2.[Code] = t1.[Code]

References

See also SQL Join Types

Team Foundation Server Delete Workspace

Problem

When a new developer uses a computer that another developer used, you may see the error: The working folder is already in use by the workspace on computer

Solution
  1. Make sure there are no pending changes for that user:
    tf status /user:username
  2. Delete the old workspace:
    tf workspace /delete [/server:servername] workspacename[;workspaceowner]

References

"Workspace Command." MSDN – the Microsoft Developer Network. N.p., n.d. Web. 16 Aug. 2013.
<http://msdn.microsoft.com/en-us/library/y901w7se(v=vs.90).aspx>.

Windows Search Filtering

Problem
Need to be able to narrow down search results in Windows 7. Unlike Windows XP, there are no boxes to check.

Solution
Use search filters by clicking on filters in search box:
  1. Open the folder to search.
  2. Click in the search box, and then click a search filter. (Ex: Kind:, Date modified:, Type:, Size:)
  3. Click one of the available options.
Use keywords to refine a search:
  • You may filter on a property that does not appear when you click in the search box by using special keywords.
Keyword Examples

filename:~=backup Files and folders whose names contain "backup"
filename:=backup Files and folders named exactly "backup"
filename:~<backup Files and folders whose names begin with "backup"
filename:~>backup Files and folders whose names end with "backup"
filename:~=backup kind:=document Only files that are considered to be "documents" whose names contain "backup"
filename:~=backup kind:folder Only folders whose names contain "backup"
filename:~=ClassLibrary filename:~=dll.refresh Files whose names contain "classlibrary" and end with "dll.refresh"

References
"Advanced Tips for Searching in Windows." Advanced Tips for Searching in Windows. N.p., n.d. Web. 14 Aug. 2012.
<http://windows.microsoft.com/en-gb/windows7/advanced-tips-for-searching-in-windows>.

SQL Join Types

[INNER] JOIN
All matching pairs of rows are returned. Discards unmatched rows from both tables. Default type of join.

LEFT [ OUTER ] JOIN
Specifies that all rows from the left table not meeting the join condition are included in the result set, and output columns from the other table are set to NULL in addition to all rows returned by the inner join.

RIGHT [OUTER] JOIN
Specifies all rows from the right table not meeting the join condition are included in the result set, and output columns that correspond to the other table are set to NULL, in addition to all rows returned by the inner join.

FULL [ OUTER ] JOIN
Specifies that a row from either the left or right table that does not meet the join condition is included in the result set, and output columns that correspond to the other table are set to NULL. This is in addition to all rows typically returned by the INNER JOIN.

See also FULL OUTER JOIN Not Working

CROSS JOIN
Cross joins return all rows from the left table. Each row from the left table is combined with all rows from the right table.

References

joins, using. "Join Fundamentals." MSDN – Explore Windows, Web, Cloud, and Windows Phone Software Development. N.p., n.d. Web. 13 Aug. 2012.
http://msdn.microsoft.com/en-us/library/ms191517%28v=sql.100%29

"Using Joins." MSDN – Explore Windows, Web, Cloud, and Windows Phone Software Development. N.p., n.d. Web. 13 Aug. 2012.
http://msdn.microsoft.com/en-us/library/ms191472%28v=sql.100%29

"Null Values and Joins." MSDN – Explore Windows, Web, Cloud, and Windows Phone Software Development. N.p., n.d. Web. 13 Aug. 2012.
http://msdn.microsoft.com/en-us/library/ms190409%28v=sql.100%29

How to Force SQL Server Job Step to Fail

Problem

Need to force an operating system job type to fail.

Solution

In a .NET application, set the ExitCode of the Environment object to a value other than zero. C#.NET example:

private static void TestSqlJobOutput()
{
       System.Console.WriteLine("Sample Error Message 1"); // Shows up in SQL Server job history log.
       Environment.ExitCode = 1; // Causes SQL Server job step to fail when application ends.
}

How to Write Output to SQL Server Job History Log

Problem

Need to generate custom output in job history of an operating system job type.

Solution

1) Check this box in SQL Server Management Studio: Job Step Properties / Advanced / Include step output in history

2) Generate output in job's executable. C#.NET example:

private static void TestSqlJobOutput()
{
       System.Console.WriteLine("Sample Error Message 1"); // Shows up in SQL Server job history log.
       Environment.ExitCode = 1; // Causes SQL Server job step to fail when application ends.
}

Windows Event Viewer Filter XML

Windows 7 XML Sample

<QueryList>
       <Query Id="0" Path="Security">
              <Select Path="Security">
                     *[System[(
                           EventID=4624
                           or EventID=4625
                           or EventID=4634
                     )]]
                     and
                     *[EventData[(
                           (
                                  Data[@Name='TargetDomainName'] = 'Abcd'
                                  or Data[@Name='AccountDomain'] = 'XYZ'
                           )
                           and
                           (
                                  Data[@Name='TargetUserName'] != 'U123'
                           )
                     )]]
              </Select>
       </Query>
</QueryList>

References

"Event Viewer - Wikipedia, the free encyclopedia." Wikipedia, the free encyclopedia. N.p., n.d. Web. 19 Oct. 2011.
<http://en.wikipedia.org/wiki/Event_Viewer#Filtering_using_XPath_1.0>.

"Windows Event Viewer CUSTOM XML FILTER | Jamin Quimby Installation & Development Notes." Jamin Quimby .com | Jamin Quimby Installation & Development Notes. N.p., n.d. Web. 19 Oct. 2011.
<http://jaminquimby.com/index.php/microsoft-windows-2008/129-windows-event-viewer-custom-xml-filter>.

"Event Log Hell (finding user logon & logoff) - Ars Technica OpenForum." Ars Technica. N.p., n.d. Web. 19 Oct. 2011.
<http://arstechnica.com/civis/viewtopic.php?f=17&t=1139356>.

Blackberry Tips

Blackberry Browser View Source: alt + RBVS
Note: Tested on Blackberry 8800

Blackberry Reboot: alt + right shift + del
Note: Tested on Blackberry Bold 9700. Takes about 5 seconds for the red light to come on. Another 5 seconds for the screen to change.

Microsoft Outlook Tips

Hack to view full folder path of a message found in Search results
Outlook 2010
1) Double click on the message to open it in its own window.
2) Open the Advanced Find feature in message with CTRL+SHIFT+F
3) Click Browse... next to "Look in" folder name.

Source:
Determine the folder path of a message found in Search results - MSOutlook.info. (2013, December 19).
Retrieved February 6, 2015, from http://www.msoutlook.info/question/846

View Source of HTML Email
Outlook 2010
1) Open message
2) Ribbon Message tab/Move section/Actions/Other Actions/View Source

View Internet Headers
Outlook 2010
1) Open message
2) Ribbon File tab/Info section/Properties

Conditional Formatting of Email in Inbox
This allows you to, for example, have email from your manager show up as bold and red; or, show all email addressed specifically to you as green; etc.
Outlook 2010
1) Ribbon View Tab/Current View section/View Settings/Conditional Formatting
2) Add or modify rules

Updates
2012-09-04 Added "Conditional Formatting of Email in Inbox"
2012-09-06 Added "View Internet Headers"
2015-02-06 Added "Hack to view full folder path of a message found in Search results"