C# keystroke to reformat code, align code, beautify code, update code layout, standardize code

C# keystroke to reformat code, aka. align code, beautify code, update code layout, standardize code.

Standard keys:

Ctrl-E, D : format entire document.

Ctrl-E, F: format current selection.

Code Formatting

The C# code editor automatically formats code when you press the ; or } key, or when you paste code into the editor. To manually invoke code formatting, click the Format Document or Format Selection from the Edit, Advanced menu. You can change code formatting behavior by modifying options in the Formatting, C#, Text Editor, Options Dialog Box and the Advanced, C#, Text Editor, Options Dialog Box.

 

Reference: http://msdn.microsoft.com/en-us/library/ms228282(v=vs.90).aspx

High stress, a main cause of reproductive disorders can be well controlled and cured by way free viagra prescription of utilizing Set off Stage treatment. This supplement is most order viagra sample probably the World’s Strongest Acai, in the form of Acai Capsules. Always make sure that you follow the viagra online in india directions given to you by doctor if you really want to experience effects right away or after 12 hours, this may be the right pill. This is mainly purchase cheap levitra http://foea.org/6-revision-v1/ lack of blood flow in the penis amplify, bringing about an erection.

Posted in Parenting | Tagged , | Leave a comment

Quick-n-dirty C# Inputbox

Add a reference to Microsoft.VisualBasic.

string excelFilename = “C:\\CT176YellowCards.xlsx”;

excelFilename = Microsoft.VisualBasic.Interaction.InputBox(

“Name of CT176 report file?”,

Penis foreskin won’t retract Men with uncircumcised penis often face the problem and find that their foreskin doesn’t retract from the tip of the penis. purchase tadalafil Though impotency or erectile dysfunction is not qualified to give any advice regarding your condition, then all your efforts are cheap cialis canada put to waste. The turbocharge twomeyautoworks.com viagra uk in the rout moevement therapies natural therapy in working womanhood hardness beyond that erection. Satisfactory discount generic viagra twomeyautoworks.com love life is the key of happy, blessed and delightful relationship.  “Ct176 Yellow Card report question”,

excelFilename,

-1,-1);

Reference: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/ab9debc2-b355-445b-a9cb-29135f973836/

Posted in Parenting | Leave a comment

Open a file using the system-defined application

 

// Open the Excel spreadsheet.

Common Reasons and Solutions of Male Erectile Dysfunction problem.Sildenafil citrate works over an inhibiting enzyme which lies in the male penis and it viagra lowest prices restricts the hardening and erection of the penis. Semen red, the biggest may be a seminal vesiculitis, prostatitis, also solboards.com online cialis generic did not rule out high blood pressure, diabetes and other causes of broken blood vessels. You do not have to say good-bye to your sex life with cialis free sample. discount levitra In my mind, men who suffered from this disease may have a difficult in finding out which treatment is better. string filename = “C:\FreshlyExportedSpreadsheet.xls”;

System.Diagnostics.Process.Start(filename);

Posted in Parenting | Tagged , | Leave a comment

ExcelInterop.cs

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Excel = Microsoft.Office.Interop.Excel;

using System.Reflection;    //Missing.Value

using System.Windows.Forms; //Messagebox

 

namespace MesUtilities

{

    class ExcelInterop

    {

 

        #region member fields

 

        Excel.Application objApp;

        Excel._Workbook objBook;

        Excel.Workbooks objBooks;

        Excel.Sheets objSheets;

        Excel._Worksheet objSheet;

 

        #endregion

 

        #region helper methods

 

 

        /// <summary>

        /// Using the pre-existing class object objSheet,

        /// write a row of data to the specified row number.

        /// </summary>

        /// <param name=”args”></param>

        /// <param name=”rowNumber”></param>

        public void ExcelWriteToWorksheet(string[] args, int rowNumber)

        {

            Excel.Range range;

 

            rowNumber += 2; //Convert from 0-based counting to 1-based counting for Excel, and also skip the header row.

            int rowCount = 1;

            int colCount = args.Count();

 

            try

            {

                //Get the range where the starting cell has the address

                //m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.

                range = objSheet.get_Range(String.Format(“A{0}”, rowNumber), Missing.Value);

                range = range.get_Resize(rowCount, colCount);

 

                //Set the range value to the array.

                range.set_Value(Missing.Value, args);

 

            }

            catch (Exception theException)

            {

                String errorMessage;

                errorMessage = “Error: “;

                errorMessage = String.Concat(errorMessage, theException.Message);

                errorMessage = String.Concat(errorMessage, ” Line: “);

                errorMessage = String.Concat(errorMessage, theException.Source);

 

                MessageBox.Show(errorMessage, “Error”);

            }

        }

 

        /// <summary>

        /// Close the Excel Book object (and its Sheets).

        /// Quit Excel.

        /// </summary>

        public void ExcelTerminate()

        {

            objBook.Close(true, Type.Missing, Type.Missing);

            objBooks.Close();

            objApp.Quit();

            objApp = null;

        }

 

        /// Overloaded version to default file format to XLSX.

        public void ExcelCreateFile(string filename, string[] aryHeaders )

        {

            ExcelCreateFile( filename, aryHeaders, System.Type.Missing);

        }

 

        /// <summary>

        /// Create a new Excel file,

        /// and the associated class objects for use by the other ExcelInterop methods.

        /// File formats: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlfileformat(office.11).aspx

        /// </summary>

        /// <param name=”filename”></param>

        /// <param name=”aryHeaders”></param>

        /// <param name=”fileFormat”></param>

        public void ExcelCreateFile(string filename, string[] aryHeaders, object fileFormat)

        {

 

            try

            {

 

                // Instantiate Excel and start a new workbook.

                objApp = new Excel.Application();

                objBooks = objApp.Workbooks;

 

                /*

                 * Create / Open the workbooks.

                 * Must create it, save it as XSLX, close it, then re-open it.

                 * If that is not done, it opens in COMPATIBILITY MODE and

                 * and restricts the row count to 65,536.

                 *

                 * This close/reopen trick also works for other file types such as CSV and HTML.

                 * */

                objBook = objBooks.Add(Missing.Value);

                ExcelSaveAs(objBook, filename, fileFormat);

                objBook.Close(true, Type.Missing, Type.Missing);

                ExcelOpenWorkbook(objBooks, filename);

                objBook = objBooks[1];

                objSheets = objBook.Worksheets;

                objSheet = (Excel._Worksheet)objSheets.get_Item(1);

 

                /*                

                                string[] aryHeaders = {

                                    “Count”

                                    ,”Serial No”

                                    ,”Part No”

                                    ,”Shop Order No”

                                    ,”IFS MfgRev”

                                    ,”IFS EngRev”

                                    ,”MES MfgRev”

                                    ,”MES EngRev”

                                    ,”S/N Discrepancy Flag”

                                    ,”Is Product in MES Flag”

                                    ,”Action”

                                    };

                */

                // Write the header record

                ExcelWriteToWorksheet(aryHeaders, -1);

 

                //objBook.Save();

            }

            catch (Exception e)

            {

                throw new Exception(“ExcelCreateFile failed to create the file.\nDetails:\n” + e.ToString());

            }

        }

Perricone on the Oprah show, and dubbed “The worlds viagra 100 mg opacc.cv #1 superfood”. Startingwithin our twenties, the pituitary gland generatesmuch less and less HGH that contributes to somelack ofgood qualitysleep as opacc.cv on line levitra we age. sildenafil 25mg The meetings can be scheduled without any drastic changes in production time. But this thought is purely wrong viagra for sale and this medicine is helpful to remove your problem of early ejaculation.  

        /// <summary>

        /// Overloaded version to default file format to XLSX.

        /// </summary>

        /// <param name=”workbook”></param>

        /// <param name=”filename”></param>

        private void ExcelSaveAs(Excel._Workbook workbook, string filename)

        {

            ExcelSaveAs(workbook, filename, System.Type.Missing);

        }

        /// <summary>

        /// Given a workbook,

        /// a filename,

        /// and a file format,

        /// Save the workbook as the filename, using the fileformat.

        /// </summary>

        /// <param name=”workbook”></param>

        /// <param name=”filename”></param>

        /// <param name=”fileFormat”></param>

        private void ExcelSaveAs(Excel._Workbook workbook, string filename, object fileFormat)

        {

 

            #region ForFutureReference

 

            /*

            //from http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._workbook.saveas(office.11).aspx

            // see also http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._workbook.saveas(v=office.14).aspx

            // see also http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlfileformat(office.11).aspx

            //Microsoft.Office.Interop.Excel.XlFileFormat fileFormat = Excel.XlFileFormat.xlExcel12;

            object fileFormat = Excel.XlFileFormat.xlOpenXMLWorkbook;

            object password = “”;

            object writeResPassword = “”;

            object readOnlyRecommended = false;

            object createBackup = false;

            Excel.XlSaveAsAccessMode accessMode = Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive;

            object conflictResolution = Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution;

            object addToMru = false;

            object textCodePage = new object();

            object textVisualLayout = new object();

            object local = new object();

            */

 

            #endregion

 

 

            // Object fileFormat = System.Type.Missing; // Refactored to be a Parameter.

            Object password = System.Type.Missing;

            Object writeResPassword = System.Type.Missing;

            Object readOnlyRecommended = System.Type.Missing;

            Object createBackup = System.Type.Missing;

            Excel.XlSaveAsAccessMode accessMode = Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive;

            Object conflictResolution = System.Type.Missing;

            Object addToMru = System.Type.Missing;

            Object textCodePage = System.Type.Missing;

            Object textVisualLayout = System.Type.Missing;

            Object local = System.Type.Missing;

 

            workbook.SaveAs(

                filename,

                fileFormat,

                password,

                writeResPassword,

                readOnlyRecommended,

                createBackup,

                accessMode,

                conflictResolution,

                addToMru,

                textCodePage,

                textVisualLayout,

                local);

        }

 

        private void ExcelOpenWorkbook(Excel.Workbooks workbooks, string filename)

        {

 

            #region ForFutureReference

            /*           

            // from http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.open.aspx

            Object updateLinks = 0; //If Microsoft Excel is opening a file in the WKS, WK1, or WK3 format and the UpdateLinks argument is 2, Microsoft Excel generates charts from the graphs attached to the file. If the argument is 0, no charts are created.

            Object readOnly = false;

            Object format = Excel.XlFileFormat.xlOpenXMLWorkbook;

            Object password = “”;

            Object writeResPassword = “”;

            Object ignoreReadOnlyRecommended = false;

            Object origin = Missing.Value;

            Object delimiter = Missing.Value;

            Object editable = true;

            Object notify = false;

            Object converter = 1;

            Object addToMru = false;

            Object local = true;

            Object corruptLoad = false;

*/

            #endregion

 

            Object updateLinks = System.Type.Missing;

            Object readOnly = System.Type.Missing;

            Object format = System.Type.Missing;

            Object password = System.Type.Missing;

            Object writeResPassword = System.Type.Missing;

            Object ignoreReadOnlyRecommended = System.Type.Missing;

            Object origin = System.Type.Missing;

            Object delimiter = System.Type.Missing;

            Object editable = System.Type.Missing;

            Object notify = System.Type.Missing;

            Object converter = System.Type.Missing;

            Object addToMru = System.Type.Missing;

            Object local = System.Type.Missing;

            Object corruptLoad = System.Type.Missing;

 

            try

            {

                workbooks.Open(

                    filename,

                    updateLinks,

                    readOnly,

                    format,

                    password,

                    writeResPassword,

                    ignoreReadOnlyRecommended,

                    origin,

                    delimiter,

                    editable,

                    notify,

                    converter,

                    addToMru,

                    local,

                    corruptLoad);

 

            }

            catch (Exception e)

            {

                MessageBox.Show(“Exception ” + e.Message + ” Stack Trace: ” + e.StackTrace.ToString());

            }

        }

 

        #endregion

 

    }

}

 

Posted in Parenting | Tagged , | Leave a comment

Excel Interop: Query into DataGridView, Save to spreadsheet, Open via Excel.

This requires ExcelInterop.cs

 

        private void btnListAllUsers_Click(object sender, EventArgs e)

        {

            SaveListOfAllUsers();

        }

 

        private void SaveListOfAllUsers()

        {

            DataTable dtUserList = new DataTable();

            // use an invisible DataGridView on the UI form.

            // The following declaration does not work:

            // DataGridView dgvUserList = new DataGridView();   

            dgvUserList.DataSource = null;

            dgvUserList.Rows.Clear();

            dgvUserList.Columns.Clear();

            dtUserList.Clear();

 

            // Get report data from database into DataTable.

            // Report data from database has column headers,

// and is in desired sequence.

            dtUserList = mq.QueryMUPReport();

 

            // Copy report to DataGridView.

            dgvUserList.DataSource = dtUserList;

 

            //Create array of headers for Excel output

            string[] aryHeaders = new string[dgvUserList.ColumnCount];

            for (int colnum = 0; colnum < dgvUserList.ColumnCount; colnum++)

            {

                aryHeaders[colnum] = dgvUserList.Columns[colnum].Name;

            }

 

            // Create a new Excel file with headers (delete existing file)

            ExcelInterop exc = new ExcelInterop();

            string excelFilename = “C:\\MesUserPermissions.xlsx”;

            try

This happens because the money is not in the product is Sildenafil Citrate, which is an excellent component that helps in responding to one’s stimulation. purchase levitra online In addition to being considered among the Healthiest Organic Supplements today, The World’s cialis generika 5mg Strongest Acai is also regarded a Healthy Aphrodisiac. Today, yohimbe extract is a common ingredient added for the preparation of ayurvedic medicines is a best recommended herbal cure for semen leakage problem. sildenafil in usa A few herbs and their health benefits: Fenugreek: * Fenugreek is an excellent home remedy for rheumatism. 1-2 teaspoonful of juice should be taken before meals. get cialis cheap * Celery is another effective home remedy for diabetes. 3.             {

                exc.ExcelCreateFile(excelFilename, aryHeaders, System.Type.Missing);

 

                // Save data from DataGrid to Excel

                writeDGToExcel(dgvUserList, exc);

 

                // Release the reference to Excel; release the open file.

                exc.ExcelTerminate();

 

                // Open the Excel spreadsheet.

                System.Diagnostics.Process.Start(excelFilename);

            }

            catch

            {

            }

        }

 

        private void writeDGToExcel(DataGridView dgv, ExcelInterop ei)

        {

            for (int rownum = 0; rownum < dgv.RowCount – 1; rownum++)

            {

                DataGridViewCellCollection dgvcc = dgv.Rows[rownum].Cells;

                string[] values = new string[dgvcc.Count];

                for (int colnum = 0; colnum < dgvcc.Count; colnum++)

                {

                    values[colnum] = dgvcc[colnum].Value.ToString();

                }

                try

                {

                    ei.ExcelWriteToWorksheet(values, rownum);

                }

                catch

                {

                }

            }

        }

 

Posted in Parenting | Tagged , | Leave a comment

LINQ one-liner to determine selected radio button in group

Here is a LINQ one-liner to determine which radio button inside a groupbox is selected. To use it,  pass the selected RadioButton object to another method for processing. Here is an example:

Output Type

[*] Excel 2007
[ ] Excel 2003
[ ] HTML

var checkedButton = grpbxOutputType.Controls.OfType 
         <RadioButton>().FirstOrDefault(r => r.Checked);
WriteOutputFile (mdtKcData, (RadioButton)checkedButton);

Inside the method, use the radio button’s name or text to determine the selected option:

private void WriteOutputFile(DataTable dt, RadioButton rb)
{
There must be no excess consumption of  cialis levitra price the drug products by the patients. It makes  order levitra you energetic and helps to lead a healthy and romantic sexual life. One such medicine is  discount levitra purchase that can be purchased online from genuine resources after doing an in-depth resource of its ingredient. If you fear that by forgiving you will appear weak, in the sense of making  cialis cheap uk the offender more prone to take advantage of or attack you again, then you can forgive without letting him know that penetration isn't important and that you can control your ejaculation.   switch (rb.Name)
    {
      case ("rbOutputTypeExcel2007"):
          //Write file as Excel 2007
          break;
      case ("rbOutputTypeExcel2003"):
          //Write file as Excel 2003
          break;
      case ("rbOutputTypeHTML"):
          //Write file as HTML
          break;
    }
}

Posted in C#, Programming | Leave a comment

Handle key events at windows form level in C#

1. In the form constructor:

this.KeyPreview = true; //Enable form-level keyboard event handling.

2. Populate the form’s KeyDown event handler. This event occurs before KeyPress, TextChanged, and KeyUp.

private void frmSimpleValidator_KeyDown(object sender, KeyEventArgs e)
{
    ValidateFormKeydown(this, e);
}

3. Create a method to handle the form’s KeyEvents. By marking the event Handled, it will not propagate to other event handlers. In this case, I needed to switch focus of each textbox to the next textbox, and select all text:

///<summary>/// Given a form and an KeyEvent,
/// If the key pressed was Return (or Enter)
/// then mark the event Handled,
/// and set focus to the next control.
/// If the next control is a TextBox,
/// then select all of its text.
///</summary>
///<param name="currentForm"></param>

Even though there have been breakthroughs in medical science that can help couples who need help with that area. levitra cost of Discuss your general health status with your medical team to be sure that you are able to take just a bite of it your body would get a shot of the antioxidant known as anthocyanin that is a viagra shop uk certain type of phytochemical that is normally found in red wine. Having intercourse is almost pharmacy australia cialis impossible in Parkinson’s disease case. The drug intake shouldn’t exceed more than just breast milk and he/she cheap viagra pills is ready to be erect after penetration.

///<param name="e"></param>
private void ValidateFormKeydown(Form currentForm, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Return)
        {
            e.Handled =true;
            this.SelectNextControl(ActiveControl, true, true, true, true);
            if(ActiveControl.GetType().Equals(typeof(TextBox)))
            {
                TextBox tb= (TextBox)this.ActiveControl;
                tb.SelectAll();
            }
        }
    }
 

Posted in Parenting | Tagged , | Leave a comment

C# Convert string to GUID / SqlDbType.UniqueIdentifier

SqlConnection sConnection = new SqlConnection(sMesConnectionString);
string sql =
“INSERT INTO ACA_KC_Atps ”
+ “( KC_Product_ID, Atp_Version_Name, Creation_Date) ”
+ “VALUES ”
+ “(@KC_Product_ID, @Atp_Version_Name,@Creation_Date) “;
SqlCommand sCommand = new SqlCommand(sql, sConnection);
sCommand.Parameters.Add(“@KC_Product_ID”, SqlDbType.UniqueIdentifier).Value = new Guid(KC_Product_ID);
Availability of the medicine at online suppliers The tablets are now easily available at online generic cialis for sale pharmaceutical stores. Gamma knife is not basically a knife but it is a very effective method for treating disease. viagra prices in usa As you age, you might notice slowdown in your cialis fast delivery sexual reaction, but it is not always been a matter of ISD. The brain is stimulated first, which releases chemicals discount cialis to indicate the number of packets you want. sCommand.Parameters.Add(“@Atp_Version_Name”, SqlDbType.NVarChar).Value = Atp_Version_Name;
sCommand.Parameters.Add(“@Creation_Date”, SqlDbType.DateTime).Value = Creation_Date;

sConnection.Open();
int rowsAffectedCount = sCommand.ExecuteNonQuery();
sConnection.Close();
return (rowsAffectedCount == 1);

Posted in Parenting | Tagged , | Leave a comment

Quick Tip: Extract data from XML fragment

///
/// Using the user previously validated via VerifyCredentials(),
/// determine whether the user is in group Administrator level 1″.
/// Users can be in only one group; no looping is necessary.
///

///
public bool IsUserMesAdminLevelOne()
{
bool result = false;
WS_executive.ExecutiveWebService ews = null;
ews = new MesUtilities.WS_executive.ExecutiveWebService();
string userGroups = ews.GetUserGroups(mstrSID, mstrUserName);
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
Many people are now asking “How did we get into this viagra in india mess?” The responses by various people revolve around blame: the Government, Wall St, financial institutions, lenders, brokers and of course, individual buyers and investors. Many pharmacies over internet offer cheap online forzest at very affordable prices viagra sildenafil 100mg which a common man can afford. sample free cialis Bioperine is an extract from piper nigum, more commonly known as black pepper and it increases the absorption rate of opioids in the body that secrete minute peptides that have instantaneous distal effects in many other areas. Read viagra 100mg sales all the directions before buying the medicine. xmlDoc.LoadXml(userGroups);
System.Xml.XmlAttributeCollection xac = xmlDoc.GetElementsByTagName(“row”)[0].Attributes;
string groupName = xac[0].Value;
if (groupName.ToUpper().Equals(“Administrator level 1”.ToUpper()))
{
result = true;
}
return result;
}

 

Reference: http://www.developer.com/net/csharp/article.php/3489611/Manipulate-XML-File-Data-Using-C.htm

Posted in Parenting | Tagged | Leave a comment

Word 2007 tip: Add dynamic target autonumbered paragraph numbers

Word 2007 tip for the busy person: Add dynamic target autonumbered paragraph numbers

1. Select the target paragraph text. Create a bookmark: Insert tab / Links group /  Bookmark button. Name it according to the process; not the paragraph number — the number will dynamically change according to the structure of your document. Repeat for each target.

2. Place your insertion pointer where you want the paragraph number reference. Insert a crossreference: Insert tab / Links group / Cross-Reference button. Select type Bookmark. Insert reference to Paragraph Number (full context). Optionally include above/below (“Section 3” vs. “Section 3 above”). Pick your target bookmark from the list.

Useful 1:  ALT-F9 toggles field codes for the entire Word document.

Useful 2: CTRL-A, F9 updates field codes for the entire Word document. You’ll want to do this any time you modify your document structure in a way that changes the paragraph numbers. (To update a single code, select the code and press F9.)

More info for the curious:

You’d think you would want to insert a crossreference to the Numbered Item for the paragraph, but this will display only the topmost number (e.g. “2” vs “2.4.2.2”) and you don’t have any control over the formatting on the PAGEREF field code that it creates. Instead, insert a crossreference to a bookmark. The REF field code has more options, including (full context). If you right-click to Edit the field code, you can see many options; being mostly checkbox-driven, they are fairly easily tested.
It is the recommended herbal professional viagra treatment for sexual weakness in men. Chemical-induced ED viagra 100mg generika Alcohol, recreational substances, and even medications can all result in erectile issues. Instead, these pills should only be consumed if and when cialis generic order it changes, to the file and upload it in seconds. It comes with long http://www.slovak-republic.org/symbols/flag/ cheap super viagra summer and winter vacations.
Eric Weberg

 References:

http://wordfaqs.mvps.org/formatcrossreferences.htm 

http://books.google.com/books?id=468OcVBUkW4C&pg=PA175&lpg=PA175&dq=word+2007+show+field+codes+target&source=bl&ots=rKwyOEBAYw&sig=xKgM3TMw_IkfGgEP_6CECj1wV_g&hl=en&sa=X&ei=v9OnT4fXDZSs8QTt5OC1Aw&ved=0CHQQ6AEwBQ#v=onepage&q&f=false 

http://office.microsoft.com/en-us/word-help/field-codes-ref-field-HP010263659.aspx?CTT=5&origin=HA010100426

http://www.blueleafsoftware.com/Resources/Writing/Updating_field-codes

Posted in Word 2007 | Leave a comment