How to Re-Enable Create Unit Tests Context Menu In Visual Studio 2012

To re-enable the Create Unit Tests… menu, go to Tools->Customize… to launch the Customize dialog. At the Customize dialog, go to the Commands tab, select the Context menu radio button and choose Editor Context Menus | Code Window.

You will realized that the menu item is actually available in the context menu. 🙂 The VS developers were kind enough to leave it there for us. *HeHe* Click on the Create Unit Tests… menu item and click either Move Up or Move Down. [Note: My screenshot is showing Create Unit Test in singular because I had previously tried to rename it]. Then click Close.

Restart Visual Studio 2012 and whalla! The context menu will be available!

 
Note: This apparently does not work in Visual Studio 2013.
 
Alternative is to use this Visual Studio Extension: Unit Test Generator
 

Get CSS/JS Intellisense In ASP.NET WebForms Using Visual Studio 2013

In Visual Studio 2013, CSS files that are included in your project/solution will now automatically be parsed and all HTML documents will gain CSS class intellisense.

But:

ASPX and other WebForm files using the legacy editor do not benefit from this implementation in VS 2013, but may adopt the new system in future releases.

But you can still use this feature as follows:

  1. right click on the “default.aspx” file in the Solution Explorer
  2. “open with”
  3. select “HTML Editor”
  4. “ok”

Source

 

Navigate To Feature In Visual Studio 2012/2013

Visual Studio’s Navigate to feature allows you to find and navigate to a specific element in your solution. Once you press the Ctrl+, combination and start typing your query*, Visual Studio will display all found elements matching your query, regardless of their type and location. To navigate to a certain element, either select it with cursor keys and press Enter or double click the element.

gte_vs[1]

Best Way To Clone An Object In .NET

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
    /// <summary>
    /// Perform a deep Copy of the object.
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }

        // Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}

In case you prefer to use the new extension methods of C# 3.0, change the method to have the following signature

public static T Clone<T>(this T source)
{
   //...
}

References:
http://stackoverflow.com/questions/78536/deep-cloning-objects/78612#78612
http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects

How To Retain Leading Zeros (0) In CSV Files

When adding a value with a leading zero. for example 05710. Add additional quotes and equals:
"=""05710"""

With the CSV file resembling this:

a,b,c,d,e,f,"=""05710""",h,i

Sources:
http://social.msdn.microsoft.com/Forums/en-US/aae07b39-865f-4c68-a07f-7cad2dfd6733/how-do-i-open-csv-using-excel-without-deleting-leading-zeros?forum=isvvba
http://nebula-rnd.com/blog/tech/2009/07/excel-csv1.html

Other Improved Ways To Export Data To Excel

 /// <summary>
        /// Exports to excel. 
        /// http://www.codeproject.com/Articles/9380/Export-a-DataSet-to-Microsoft-Excel-without-the-us
        /// http://bytes.com/topic/c-sharp/answers/497730-streamwriter-export-excel
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <exception cref="System.Exception"></exception>
        public void ExportToExcel(DataSet source, string fileName)
        {

            //get response, set content type.
            HttpResponse response = HttpContext.Current.Response;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" +
            fileName + "\"");
            response.Clear();
            System.IO.StreamWriter excelDoc;
            excelDoc = new System.IO.StreamWriter(response.OutputStream);


            /// excelDoc = new System.IO.StreamWriter(fileName);
            const string startExcelXML = "<xml version>\r\n<Workbook " +
                  "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                  " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                  "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                  "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                  "office:spreadsheet\">\r\n <Styles>\r\n " +
                  "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                  "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                  "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                  "\r\n <Protection/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                  "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                  "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                  " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                  "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                  "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                  "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                  "</Styles>\r\n ";
            const string endExcelXML = "</Workbook>";

            int rowCount = 0;
            int sheetCount = 1;
            /*
           <xml version>
           <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
           xmlns:o="urn:schemas-microsoft-com:office:office"
           xmlns:x="urn:schemas-microsoft-com:office:excel"
           xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
           <Styles>
           <Style ss:ID="Default" ss:Name="Normal">
             <Alignment ss:Vertical="Bottom"/>
             <Borders/>
             <Font/>
             <Interior/>
             <NumberFormat/>
             <Protection/>
           </Style>
           <Style ss:ID="BoldColumn">
             <Font x:Family="Swiss" ss:Bold="1"/>
           </Style>
           <Style ss:ID="StringLiteral">
             <NumberFormat ss:Format="@"/>
           </Style>
           <Style ss:ID="Decimal">
             <NumberFormat ss:Format="0.0000"/>
           </Style>
           <Style ss:ID="Integer">
             <NumberFormat ss:Format="0"/>
           </Style>
           <Style ss:ID="DateLiteral">
             <NumberFormat ss:Format="mm/dd/yyyy;@"/>
           </Style>
           </Styles>
           <Worksheet ss:Name="Sheet1">
           </Worksheet>
           </Workbook>
           */
            excelDoc.Write(startExcelXML);
            excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
            excelDoc.Write("<Table>");
            excelDoc.Write("<Row>");
            for (int x = 0; x < source.Tables[0].Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in source.Tables[0].Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < source.Tables[0].Columns.Count; y++)
                {
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                    {
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            excelDoc.Write(endExcelXML);


            //flush and finish response
            excelDoc.Flush();
            excelDoc.Close();
            response.End();
        }

And to call it:


 /// <summary>
        /// Handles the Click event of the lbtnExportToExcel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbtnExportToExcel_Click(object sender, EventArgs e)
        {
            CommunicationsFilter filter = new CommunicationsFilter();

            filter = FilterControl.GetSearchFilter();
            int totalRowCount;
            List<SubscriberData> subData = CommDataManager.GetSubscribers(filter, 0, out totalRowCount);


            DataSet ds = new DataSet(); ds.Tables.Add(ConvertSubscriberDataToDataView(subData).ToTable());
            //ExportToExcel(ds, "MobileAlertsExport.xls");           

           

           
        }




  /// <summary>
        /// Converts the subscriber data to data view.
        /// </summary>
        /// <param name="subcriberData">The subcriber data.</param>
        /// <returns></returns>
        private DataView ConvertSubscriberDataToDataView(List<SubscriberData> subcriberData)
        {
            DataTable dt = new DataTable();

            // Define column headers
            dt.Columns.Add("First Name");
            dt.Columns.Add("Middle Initial");
            dt.Columns.Add("Last Name");
            dt.Columns.Add("Account Number");
            dt.Columns.Add("OPCO Abbrv Name");
            dt.Columns.Add("OPCO Full Name");
            dt.Columns.Add("Email");

            foreach (SubscriberData subscriber in subcriberData)
            {
                DataRow dr = dt.NewRow();

                dr["First Name"] = subscriber.FirstName;
                dr["Middle Initial"] = subscriber.MiddleInitial;
                dr["Last Name"] = subscriber.LastName;
                dr["Account Number"] = subscriber.SubscriberAccount.AccountNumberCheckDigit;
                dr["OPCO Abbrv Name"] = subscriber.OpCo.AbbreviatedName;
                dr["OPCO Full Name"] = subscriber.OpCo.FullName;
                dr["Email"] = subscriber.Email;

                dt.Rows.Add(dr);
            }

            //Load the datatable into a Dataview to accomodate easy sorting
            DataView dv = new DataView(dt);
            return dv;
        }

And for an even more native xlsx output check out http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm# which uses DocumentFormat.OpenXML.dll