Boxing and Unboxing

1:25 AM

Boxing Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.  Refer MSDN

Boxing will take Variable from Stack (Value types) and store it into Heap (Object type)

Boxing is implicit. There is no need to type cast the value type to Object Type.

Example:



String mystr = "Welcome to C# boxing";

Object myObj = mystr;  // Implicit conversion of String to Object




Unboxing:  It's the reverse of boxing. It needs to be done explicitly by user.

Example:



String mystr = "Welcome to C# boxing";

Object myObj = mystr;  // Implicit conversion of String to Object

String mystr2 = (String) myObj; // Explicit conversion from Object to String




Automatic ListView Grouping

3:49 AM

Lets say you have lots of data your listview. Now you want to Group This data According to a Perticular Subitems.

For Example:

Suppose i have some books data in my ListView.
this listview items contains Author name and Books Title.

And there are 2000 Books in list view.

Now i want to group the data in listview according to the Authors.

Now lets say there are 50 Unique Authors , meaning we will have to create 50 Groups in listview.

this seem hectic, and i dont know if there is any inbuilt function to automatically group this items, but i have created mine To automatically do the above.

Hope it becomes usefull to someone.

Code:

public void GroupListView(ListView lstV, int SubItemIndex)
        {
            bool flag = true;

            foreach (ListViewItem l in lstV.Items)
            {
                string strmyGroupname = l.SubItems[SubItemIndex].Text;

                foreach (ListViewGroup lvg in lstV.Groups)
                {
                    if (lvg.Name == strmyGroupname)
                    {
                        l.Group = lvg;
                        flag = false;
                    }
                }

                if (flag == true)
                {
                    ListViewGroup lstGrp = new ListViewGroup(strmyGroupname, strmyGroupname);
                    lstV.Groups.Add(lstGrp);
                    l.Group = lstGrp;
                }

                flag = true;


            }
        }

How To Use The Code:

Lets say the author's sub item's index is 1 and listview name is LstBooks

then call the function like:
GroupListView(LstBooks,1);


Vb.net Version:

Public Sub GroupListView(ByVal lstV As ListView, ByVal SubItemIndex As Int16)
        Dim flag As Boolean = True
        For Each l As ListViewItem In lstV.Items

            Dim strmyGroupname As String = l.SubItems(SubItemIndex).Text

            For Each lvg As ListViewGroup In lstV.Groups

                If lvg.Name = strmyGroupname Then
                    l.Group = lvg
                    flag = False
                End If

            Next

            If flag = True Then
                Dim lstGrp As New ListViewGroup(strmyGroupname, strmyGroupname)
                lstV.Groups.Add(lstGrp)
                l.Group = lstGrp
            End If

            flag = True

        Next
    End Sub

Output:



Auto Increment Invoice Number For Vb.net

12:10 AM
Let's say you have some invoice numbers which contains Alphabets as well as numeric number.
And you want to increment it one by one.

For Example:

if Invoice number is "AZ99999999" then Next Invoice Number will be "BA00000001"

Notice here that , the invoice number's lenght is 10 Characters out of which first 2 are Alphabets and the rest (8) are Numeric. invoice number can be of any digit with any combination of numerics and alphabets.

The function can be changed to your need very easily. but here i will demonstate for the above example.

Function:
Public Function IncrementInvoice(ByVal strInvoiceNumber As String) As String

        If strInvoiceNumber.Length <> 10 Then
            Return "Error"
        End If

        Dim strAlphaPart(1) As Char
        strAlphaPart(0) = strInvoiceNumber(0)
        strAlphaPart(1) = strInvoiceNumber(1)

        Dim IntPart As Int64
        IntPart = strInvoiceNumber.Substring(2, 8)


        If IntPart = 99999999 Then
            If strAlphaPart(1) = "Z" Then
                strAlphaPart(0) = Chr(Asc(strAlphaPart(0)) + 1)
                strAlphaPart(1) = "A"

                IntPart = 1

                Return strAlphaPart(0) & strAlphaPart(1) & IntPart.ToString.PadLeft(8, "0")
            Else
                strAlphaPart(1) = Chr(Asc(strAlphaPart(1)) + 1)
            End If

        Else
            IntPart += 1
            Return strAlphaPart(0) & strAlphaPart(1) & IntPart.ToString.PadLeft(8, "0")
        End If

    End Function



Output:
'outputs example:
strTemp = IncrementInvoice("AA99999998") 'Output will be: "AA99999999"
strTemp = IncrementInvoice("AA00000005") 'Output will be: "AA00000006"
strTemp = IncrementInvoice("AZ00000007") 'Output will be: "AZ00000008"
strTemp = IncrementInvoice("AZ99999999") 'Output will be: "BA00000001"



Linq To Sql - Example 1 : Where -1

1:44 AM
Linq Query:

//Where -1
            NorthWindDataContext NwDC = new NorthWindDataContext();

            var cust =
                from c in NwDC.Customers
                where c.City.StartsWith("L")
                select c;
            foreach (var t in cust)
            {
                Console.WriteLine("Name: {0} , City : {1} ", t.ContactName, t.City);
            }

//


Output:

Name: Thomas Hardy , City : London
Name: Christina Berglund , City : Luleå
Name: Victoria Ashworth , City : London
Name: Elizabeth Brown , City : London
Name: Ann Devon , City : London
Name: Martine Rancé , City : Lille
Name: Lino Rodriguez , City : Lisboa
Name: Alexander Feuer , City : Leipzig
Name: Simon Crowther , City : London
Name: Isabel de Castro , City : Lisboa
Name: Hari Kumar , City : London
Name: Art Braunschweiger , City : Lander
Name: Mary Saveley , City : Lyon

Sql Equivalent Query:

SELECT  ContactName
      , City
FROM    dbo.Customers
WHERE   city LIKE 'L%'


Output:

Thomas Hardy      London
Christina Berglund    Luleå
Victoria Ashworth    London
Elizabeth Brown     London
Ann Devon     London
Martine Rancé     Lille
Lino Rodriguez     Lisboa
Alexander Feuer     Leipzig
Simon Crowther     London
Isabel de Castro     Lisboa
Hari Kumar        London
Art Braunschweiger       Lander
Mary Saveley        Lyon


Explanation: We are simply listing all the Customer who are living in the city name Staring With 'L' letter.

For How to Setup Database and Linq to Sql Class Please follow the instructions here: Setting Up Linq to Sql Class

Linq To Sql Introduction and Creating NorthWind Database

4:20 AM
LINQ to SQL provides a runtime infrastructure for managing relational data as objects without losing the ability to query. Your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically.



Advantages L2S offers:


No magic strings, like you have in SQL queries
Intellisense
Compile check when database changes
Faster development
Unit of work pattern (context)
Auto-generated domain objects that are usable small projects
Lazy loading.
Learning to write linq queries/lambdas is a must learn for .NET developers.


Regarding performance:
Most likely the performance is not going to be a problem in most solutions. To pre-optimize is an anti-pattern. If you later see that some areas of the application are to slow, you can analyze these parts, and in some cases even swap some linq queries with stored procedures or ADO.NET.
In many cases the lazy loading feature can speed up performance, or at least simplify the code a lot.


Regarding debuging:
In my opinion debuging Linq2Sql is much easier than both stored procedures and ADO.NET. I recommend that you take a look at Linq2Sql Debug Visualizer, which enables you to see the query, and even trigger an execute to see the result when debugging.
You can also configure the context to write all sql queries to the console window, more information here


Regarding another layer:
Linq2Sql can be seen as another layer, but it is a purely data access layer. Stored procedures is also another layer of code, and I have seen many cases where part of the business logic has been implemented into stored procedures. This is much worse in my opinion because you are then splitting the business layer into two places, and it will be harder for developers to get a clear view of the business domain.




For Linq to Sql Session we will be working on Sql 's Northwind Database. 


Creating The Northwind Database:
You can Download The database from here: NorthWind  


The Complete backup of Northwind database:  Northwind

Now Next thing is to Create a New LINQ to SQL Data Model.
For all the Next Examples you will need This Class.

1. Create a  New Project Name is LinqToSqlExample.
2. Now Go To Project  -> Add New Item and Add a Linq To Sql File and Name it NorthWind.


3. You will see a screen like below.


Now we will add a Data Connection as shown in above figure in left pane.



Select Add Connection.. And you will see below screen.





Press ok and you will see below screen.




And now our class is created . we will be using this in our next examples.

Dataset To Excel Export Function

2:38 AM
The Function:

Public Sub ExportDatasetToExcel(ByVal ds As DataSet, ByVal strExcelFile As String)

        Dim conn As New OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0; Data Source='{0}';" & "Extended Properties='Excel 8.0;HDR=YES;'", strExcelFile))
        conn.Open()

        Dim strTableQ(ds.Tables.Count) As String

        Dim i As Integer = 0

        'making table query
        For i = 0 To ds.Tables.Count - 1

            strTableQ(i) = "CREATE TABLE [" & ds.Tables(i).TableName & "]("

            Dim j As Integer = 0
            For j = 0 To ds.Tables(i).Columns.Count - 1
                Dim dCol As DataColumn
                dCol = ds.Tables(i).Columns(j)
                strTableQ(i) &= " [" & dCol.ColumnName & "] varchar(255) , "
            Next
            strTableQ(i) = strTableQ(i).Substring(0, strTableQ(i).Length - 2)
            strTableQ(i) &= ")"

            Dim cmd As New OleDbCommand(strTableQ(i), conn)
            cmd.ExecuteNonQuery()

        Next

        'making insert query
        Dim strInsertQ(ds.Tables.Count - 1) As String
        For i = 0 To ds.Tables.Count - 1
            strInsertQ(i) = "Insert Into " & ds.Tables(i).TableName & " Values ("
            For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
                strInsertQ(i) &= "@" & ds.Tables(i).Columns(k).ColumnName & " , "
            Next
            strInsertQ(i) = strInsertQ(i).Substring(0, strInsertQ(i).Length - 2)
            strInsertQ(i) &= ")"
        Next

        'Now inserting data
        For i = 0 To ds.Tables.Count - 1
            For j As Integer = 0 To ds.Tables(i).Rows.Count - 1
                Dim cmd As New OleDbCommand(strInsertQ(i), conn)
                For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
                    cmd.Parameters.AddWithValue("@" & ds.Tables(i).Columns(k).ColumnName.ToString(), ds.Tables(i).Rows(j)(k).ToString())
                Next
                cmd.ExecuteNonQuery()
                cmd.Parameters.Clear()

            Next
        Next
    End Sub



Let's say i have my.xls in D drive. i want to export a Dataset Name dsFinal to this excel file.
Use:

ExportDatasetToExcel(dsFinal, "d:\\my.xls")

Listing Running Processes in c#.net

1:42 AM
1. Add List box on a Forms.
2. Now add a reference to System.Diagnostics
Code:



Process[] curProcesses = Process.GetProcesses();

            foreach (Process p in curProcesses)
            {
                listBox1.Items.Add(p.ProcessName);
            }


Output: