Archive

Posts Tagged ‘C# Snippets’

C#: Use exit code from application in Windows batch file (script)

That’s pretty easy stuff if you know it already.

Take a look on example (TestApp.exe):

  static int Main(string[] args)
        {
            int myCodeNumber = 1;

            // Return some code number
            return myCodeNumber;
        }

and here it is how to catch it in Windows batch file (test.bat):

REM Run app which will return some code number
TestApp.exe

REM If returned code is not == 1 then "do something" else continue to NEXT section
if %errorlevel% NEQ 1 GOTO :NEXT
DO SOMETHING HERE

:NEXT
Categories: C#, C# Snippets Tags: ,

C#: Reading embedded XML file

Snippet:

Assembly assembly = Assembly.GetExecutingAssembly();

string filePath = assembly.GetName().Name + ".filename.xml";

using (Stream stream = assembly.GetManifestResourceStream(filePath))
{
    if (stream != null)
    {
      // do something with Stream from file
    }
}
Categories: C#, C# Snippets, WinForms Tags:

C#: Get all inner exceptions messages

Very often InnerException of Exception has some valuable details what happens. Quite often InnerException has an InnerException so more error messages to investigate. 

Theoretically there can be unlimited number of Inner Exceptions so below are 2 small snippets to get all messages from them. Both snippets do the same but first in a “while method”, second in recursive way.

        /// <summary>
        /// Gets all inner exceptions messages.
        /// </summary>
        /// <param name="ex">The exception</param>
        /// <returns>Messages from all inner exceptions.</returns>
        public static string GetInnerExceptionMessages(Exception ex)
        {
            Exception inner = ex.InnerException;
            string messages = String.Empty;

            while (inner != null)
            {
                messages += inner.Message;

                if (!messages.EndsWith("."))
                {
                    messages += ".";
                }

                inner = inner.InnerException;
            }

            return messages;
        }

And another method as recursive function from:
http://stackoverflow.com

public string GetInnerException(Exception ex)
{
     if (ex.InnerException != null)

     {
        return string.Format("{0} > {1} ", ex.InnerException.Message,GetInnerException(ex.InnerException));
     }

   return string.Empty;
}
Categories: C# Snippets Tags: ,

C#: WinForms – How to change DataGridView cells color or other attributes

We can use for this _CellFormatting event. See below example:

private void DataGridView1_CellFormatting(object sender,
                        DataGridViewCellFormattingEventArgs e)
{
    DataGridView gv = (DataGridView)sender;

    if (gv.Columns[e.ColumnIndex].Name == "ColumnName")
    {
        // If cell has a value and contains char '-'
        if (e.Value != null && e.Value.ToString().Contains("-"))
        { // Change cell text color to red
            e.CellStyle.ForeColor = Color.Red;
            //e.CellStyle.Font = new Font("Arial", 10, FontStyle.Bold);
        }
    }
}
Categories: WinForms Tags: ,

C#: WinForms – How to expand dynamically width of ToolStripProgressBar to fill entire free space in StatusStrip

I often would like to have ProgressBar (hidden and shown only while some background application work is doing) in my StatusStrip. My expectation is the ProgressBar should always fill entire available free space in StatusStrip, when form is Maximizing, Resizing etc. This kind of behaviour can’t be set in Visual Studio Designer with control properties settings. Below is my solution to solve this problem. If you know better, simplest way then please let me know by your comment :)

// Method to calculate suitable ToolStripProgressBar width
private int CalculateControlSizeInStatusStrip(StatusStrip statusStrip,
                         Control statusProgressBar)
{
    int width = statusStrip.ClientSize.Width;
    int gripWidth = 20;

    if (statusStrip.Items.Count > 1)
    {   // Calculate width for progress bar if more controls
        // on StatusStrip
        for (int i = 0; i < statusStrip.Items.Count - 1; i++)
        {
            // width calculation
            width -= statusStrip.Items[i].Width;
        }
    }

    return width - gripWidth;
}

on your StatusStrip Resize event:

private void statusStripMain_Resize(object sender, EventArgs e)
{
    // Expand dynamically width of ToolStripProgressBar to
    // fill entire free space in StatusStrip
    toolStripStatusProgressBarMainTask.ProgressBar.Width = CalculateControlSizeInStatusStrip((StatusStrip)sender, toolStripStatusProgressBarMainTask);
}
Categories: WinForms Tags: ,

C#: WinForms – How to use DataTable as DataGridView datasource and DataTable column with HeaderText property

I did something like that today so I thought to share. Example of use DataTable with DataGridView control. In addition HeaderText property of DataGridView is assigned based on DataTable DataColumn.Caption property value.

using System.Data;
using System;

private DataTable myDataTable = new DataTable();

DataColumn getNewColumn(string columnName, string columnCaption
                        , string columnType)
{
    // Create a new column to be used in the DataTable
    DataColumn dc =
        new DataColumn(columnName, System.Type.GetType(columnType));

    // Column caption can be used later for HeaderText prop
    // in DataGridView
    dc.Caption = columnCaption;

    return dc;
}

void CreateNewRow(string[] rowData)
{
    // Create a DataRow based on the DataTable
    DataRow dr = myDataTable.NewRow();

    // Add values to the DataRow columns
    int i = 0;
    foreach (string fieldData in rowData)
    {
                if (i < dataTable.Columns.Count)
                    // assign by index
                    dr[i] = fieldData;
                else
                    break;

                i++;
    }

    // Add the row to the DataTable
    myDataTable.Rows.Add(dr);
}

private void FillDataGridViewFromTextFile(string filename)
{
    // Clear last results from DataGridView
    if (DataGridView1.RowCount > 0)
        myDataTable.Rows.Clear();

    if (myDataTable.Columns.Count == 0)
    { // if DataTable is not constructed than Add Columns
      // to the datatable
        myDataTable.Columns.Add(getNewColumn("ComputerName"
                                            , "Computer name"
                                            , "System.String"));
    }

    // Load data from text file into DataTable
    using (System.IO.StreamReader reader
            = new System.IO.StreamReader(filename))
    {
        string line = "";

        while ((line = reader.ReadLine()) != null)
        {
            if (!String.IsNullOrEmpty(line))
            {
                // add row data to "columns array"
                string[] rowData = new string[] { line };

                // add new row to DataTable
                CreateNewRow(rowData);
            }
        }
    }

    // Assign DataTable to DataGridView
    DataGridView1.DataSource = myDataTable;

    // Copy DataTable columns Caption property
    // to DataGridView HeaderText property
    foreach (DataColumn dc in myDataTable.Columns)
    {
        DataGridView1.Columns[dc.ColumnName].HeaderText = dc.Caption;
    }
}

P.S. To get all the data OUT of the gridview and back INTO a datatable

DateTable tbl = Gridview1.DataSource as DataTable;
Categories: WinForms Tags: ,

C#: Fill a string with repeating characters

//For example, make a string with 32 “a” chars.

string test = new string('a', 32 );
Categories: C# Snippets Tags:

C#: Insert NULL values into SQL Server database

To insert into database NULL value from C# code we can’t use just simple declaration for empty string like string textToInsert = “”; This will insert into database just empty string instead NULL value.

To handle this case you have to use special SQL type: System.Data.SqlTypes.SqlString.Null

Dummy example (do nothing special but shows the way) below:

using (SqlConnection cn = new SqlConnection(connectionString))
{
    string sqlText = "stored_procedure_name";
    using (SqlCommand cmd = new SqlCommand(sqlText, cn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@TaskType", SqlDbType.NVarChar, 255).Value = System.Data.SqlTypes.SqlString.Null;

        try
        {
            cn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (SqlException sqlEx)
        {
        }

    }
}

System.Data.SqlTypes namespace has all SQL Server types so if you need to insert NULL value then use suitable one for your column data type.

C#: Get the first date of week for specified date

Source:
http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week

If you have similiar solution than test it for 2009-02-01 (sunday) date (yyyy-mm-dd). Correct result should be 2009-01-26.

Extension method:

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
                diff += 7;
        }

        return dt.AddDays(-1 * diff).Date;
    }
}

Example of use

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
Categories: C# Snippets Tags:

C#: How to add programatically meta tag to ASP.NET page

// Example: add meta tag with refresh command
    protected void Page_Load(object sender, EventArgs e)
    {
        string strCurrentURL = "http://localhost/test";

        // Add meta tag with refresh command
        string strRefreshSeconds = "3"; // how many seconds

        HtmlMeta metaTags = new HtmlMeta();
        metaTags.HttpEquiv = "refresh";
        metaTags.ID = "EnterHereSomeUniqueName";
        metaTags.Content = strRefreshSeconds + ";URL=" + strCurrentURL;
        Header.Controls.Add(metaTags);
    }
Categories: ASP.NET Tags: ,