Windows Phone Developers

Thursday, September 22, 2011

Threading in .NET/C# - How to get Thread Details

How to Execute a process in separate thread in VB.NET/C#

This was one of my favorites - Threading; but somehow I ignored for long. Now let us delve into it

Let us execute some small piece of code (a definite loop) through normal method and with the help of threading. Normal methid

private void ThreadExampleSync()
        {
            for (int iCnt = 0; iCnt < 3; iCnt++)
            {
                for (int j = 0; j < 100; j++)
                {

                    for (int j1 = 0; j1 < 9000000; j1++)
                    {

                    }
                }
                Console.WriteLine("Iteration {0} is executed by {1} at {2}", iCnt.ToString(), Thread.CurrentThread.ManagedThreadId.ToString(), DateTime.Now.ToString());
            }
        }
When we move to threading let us take the looping part into a separate method and call the method using different Threads
private void ThreadExampleAsync()
        {
            for (int iCnt = 0; iCnt < 3; iCnt++)
            {
                var t1 = new Thread(ExecuteTasks);
                t1.Start(iCnt);
            }
        }


        private  static void ExecuteTasks(object iInput)
        {
            for (int j = 0; j < 100; j++)
            {

                for (int j1 = 0; j1 < 9000000; j1++)
                {
                    //nothing

                }
            }
            Console.WriteLine("Iteration {0} is executed by {1} at {2}", iInput.ToString(), Thread.CurrentThread.ManagedThreadId.ToString(), DateTime.Now.ToString());
        }

Since we are calling new thread for each iteration - ExecuteTasks gets executed by different threads as shown below

The time taken when we use different threads is faster than the synchronous way. However, care must be taken in Threading to avoid excess memory usage/leakages Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Tuesday, September 20, 2011

Argument 1: cannot convert from 'method group' to 'System.Threading.ThreadStart'

The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' has some invalid arguments

These errors occur when the Method that is called has parameters other than object. The compiler expects the signature to take object

var t1 = new Thread(ExecuteTasks);

will throw an error if the method signature is like this

private  static void ExecuteTasks(int iInput)

The following one is acceptable

private  static void ExecuteTasks(object iInput)
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Friday, September 16, 2011

VB.NET / C# - How to Check if OS is 64-Bit or 32-Bit

The following snippet gives a hint :

        private void GetOSConfig()
        {
            string sProcess;
            if (Environment.Is64BitOperatingSystem  == true )
            {
                sProcess = "64 Bit";
            }
            {
                sProcess = "32 Bit";
            }
            Console.WriteLine("OS is {0}", sProcess  );
        } Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Pass Multiple/Variable Parameters to a Function/Method in C#/.NET

C#/VB.NET Function with dynamic parameters / How to make a function accept infinite number of arguments

Normally a method has a definite number of parameters and they are passed from the calling method. What if you are not sure of the number of parameters or want to be flexible in that. A Simple example can be a Adding machine - which adds any numbers sent .

It is possible to achieve that with params keyword -

private void AddAsManyNumbersAsUCan(params int[] numbers)

{

int iTotal = 0;

foreach (int i1 in numbers)

{

iTotal += i1;

}

Console.WriteLine("Sum of {0} numbers added to {1}",numbers.Length ,iTotal);

}

The above method accepts any number of arguments (provided they are of the same type). The method can be called like:

AddAsManyNumbersAsUCan();

AddAsManyNumbersAsUCan(1,2,3);

AddAsManyNumbersAsUCan(100,-1,23,2121,4562);
Will give the following output




You can change the type of the parameter to a generic one - List etc to have a broader use 
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Thursday, September 15, 2011

VB.NET FindControl in Windows forms application

How to loop through windows form controls by name (C# / VB.NET)

ASP.NET dev have the advantage of FindControl, which does this work quite easily. For Windows forms developers the need to loop through the controls using ForEach in the control collection or can use the Find method as shown below:

foreach (Control ctl in Controls.Find("textBox" + i, false))

{

string stext = ctl.Text ;

};


Here we have used ControlCollection Controls.Find method to refer a Textbox and get the value Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

String Comparison (case sensitive and case-insensitive) in C#/VB.NET

How to IgnoreCase in C#/VB.NET String Comparison

Whether you like or not, life revolves around comparison . Here let us see how to compare two strings using Equals method.

Equals method takes two arguments - the string to be compared and the comparison type (Case Sensitive or Insensitive)

The following snippet gives a hint of both:


        private static void StringCompExample()
        {
            string s1 = "MulTIpleCASE";
            string s2 = "MultipleCase";

            bool compare_result = false;

            //case sensitive comparison
            compare_result = s1.Equals(s2);
            Console.WriteLine(compare_result.ToString ());
           
            //case insensitive comparison
            compare_result = s1.Equals(s2, StringComparison.InvariantCultureIgnoreCase);
            Console.WriteLine(compare_result.ToString());
           
        }
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Remove Alternate/Extra Text (Text within Parenthesis) using VB.NET/C#

How to Remove Text within Brackets/ Braces using VB.NET/C#

Regular expressions come handy when we have this kind of requirement. Regex.Replace method can be used remove the unwanted text

        private static void RemoveTextWithinParens()
        {
            string pattern = @"\([^\(\)]+\)";
            string interesting_string = "SOMETHING (#2) and some more rhing (#3 inside braces)";
            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = rgx.Matches(interesting_string);
            string removed_String = rgx.Replace(interesting_string, "");
        }

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Wednesday, September 7, 2011

How to Convert Textboxes to Array/List in VB.NET/C#

Array of Textboxes using VB.NET/C# / Loop through Textboxes in VB.NET

Here is a simple code that loops through all the controls on a Windows form and Appends the Array/List with the values

Sub GetTextBoxValues()

        Dim arTextBoxVal() As String
        Dim arTBCnt As Integer = 0
        Dim ListTB As New List(Of String)

        For Each ctlText In Me.Controls
            If TypeOf ctlText Is TextBox Then
                ReDim Preserve arTextBoxVal(arTBCnt)
                arTextBoxVal(arTBCnt) = DirectCast(ctlText, TextBox).Text
                ListTB.Add(DirectCast(ctlText, TextBox).Text)
                arTBCnt += 1
            End If
        Next

    End Sub
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to create DataTable on the fly and add Rows (data) using VB.NET/C#

How to Populate DataGridView on the fly using VB.NET

Not all data come from a database table; at times we need to create in on the fly.

Here is a situation that warrants that - we create a datatable and then create appropriate data columns

Dim oDataTable As New DataTable("BookingInfo")
        
        oDataTable.Columns.Add(New DataColumn("PassengerName"))
        oDataTable.Columns.Add(New DataColumn("JourneyDate"))
      ...
  

Then data row is created and added to the table

oDR = oDataTable.NewRow
        oDR("PassengerName") = "Dhuvaraga Prasath Mohanram"
        oDR("JourneyDate") = Now.ToString()
        oDR("Source") = "Chennai"
        oDR("Destination") = "Nellore"

        oDataTable.Rows.Add(oDR)

This can be continued till all rows are added;

DataGridView is then bound to the datatable using DataSource property

DataGridView_BookingInfo.DataSource = oDataTable
        DataGridView_BookingInfo.AutoResizeColumns()

Which gives you the screen below


Sub CreateOnTheFlyDataTable()

        Dim oDataTable As New DataTable("BookingInfo")
        Dim oDR As DataRow

        oDataTable.Columns.Add(New DataColumn("PassengerName"))
        oDataTable.Columns.Add(New DataColumn("JourneyDate"))
        oDataTable.Columns.Add(New DataColumn("Source"))
        oDataTable.Columns.Add(New DataColumn("Destination"))

        oDR = oDataTable.NewRow
        oDR("PassengerName") = "Dhuvaraga Prasath Mohanram"
        oDR("JourneyDate") = Now.ToString()
        oDR("Source") = "Chennai"
        oDR("Destination") = "Nellore"

        oDataTable.Rows.Add(oDR)

        DataGridView_BookingInfo.DataSource = oDataTable
        DataGridView_BookingInfo.AutoResizeColumns()

    End Sub
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon