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:


Linq Example 45 -SequenceEqual

11:51 PM
Linq Query:

//EqualAll
            string[] str1 = { "a", "b", "c" };
            string[] str2 = { "a", "b", "c" };

            bool IsEqual = str1.SequenceEqual(str2);
            Console.WriteLine(IsEqual);

            string[] str3 = { "a", "b", "c" };
            string[] str4 = { "b", "c", "a" };

            bool IsEqual1 = str3.SequenceEqual(str4);
            Console.WriteLine(IsEqual1);

//


Output:

True
False

Explanation:


Both the arrays must be equal in sequence.

Linq Example 44 - Concat

11:48 PM
Linq Query:

//Concat
            string[] str1 = { "a", "b", "c"};
            string[] str2 = { "d", "e", "f" };

           var allstr = str1.Concat(str2);

           foreach (var t in allstr)
           {
               Console.WriteLine(t);
           }

//

Output:
a
b
c
d
e
f

Linq Example 43 - Aggregate Seed

11:46 PM
Linq Query:

//Aggregate Seed

            double startBalance = 100.0;

            int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };

            double endBalance =
                attemptedWithdrawals.Aggregate(startBalance, (Curbalance, nextWithdrawal) =>
                        ((nextWithdrawal <= Curbalance) ? (Curbalance - nextWithdrawal) : Curbalance));

            Console.WriteLine("Ending balance: {0}", endBalance);

//
Output: 
Ending balance: 20

Explanation:


This one is quite Tricky.

We start From startBalance which is 100.

Next we try to attempt to withdraw some amount from this 100. Our attemp amount is in attemptedWithdrawals array.

First We attempt to Withdraw 20 . As ( 20 < 100 ) is true we Approve the Withdraw and now Our Balance is 100-20 = 80.

Next We attempt to Withdraw 10 . As ( 10 < 80 ) is true we Approve the Withdraw and now Our Balance is 80-10 = 70.

Next We attempt to Withdraw 40 . As ( 40 < 70 ) is true we Approve the Withdraw and now Our Balance is 70-40 = 30.

Next We attempt to Withdraw 50 . As ( 50 is not less than 30 ) we wont Approve the Withdraw and now Our Balance is same as before = 30.

Next We attempt to Withdraw 10 . As ( 10 < 30 ) is true we Approve the Withdraw and now Our Balance is 30-10 = 20.

Next We attempt to Withdraw 70 . As ( 70 is not less than 20 ) we wont Approve the Withdraw and now Our Balance is same as before = 20.

Next We attempt to Withdraw 30 . As ( 30 is not less than 20 ) we wont Approve the Withdraw and now Our Balance is same as before = 20.

So the Final Balance is 20 stored in endBalance.

Linq Example 42 - Aggregate

11:38 PM
Linq Query:

//Aggregate

            double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
            double product = doubles.Aggregate((CurrentValue, NextValue) => CurrentValue  * NextValue);            

            Console.WriteLine("Total product of all numbers: {0}", product);

//

Output:
Total product of all numbers: 88.33081

Linq Example 41 - Average Projection

11:27 PM
Linq Query:

//Average Projection

            string[] words = { "GodOfWar", "CallOfDuty", "AssasinCreed" };

            double avgWordLeng = words.Average(w => w.Length);

            Console.WriteLine("Average word Length is {0} characters long.", avgWordLeng);

//

Output:
Average word Length is 10 characters long.

Linq Example 40 - Average

11:25 PM
Linq Query:

//Average

            int[] myNumbers = { 5, 8, 6, 2, 1, 9, 4, 6 };

            double avg = myNumbers.Average();

            Console.WriteLine(avg);

//

Output:
5.125

Linq Example 39 - Max Projection

11:20 PM
Linq Query:

//
            string[] words = { "GodOfWar", "CallOfDuty", "AssasinCreed" };

            int LargestWord = words.Max(w => w.Length);

            Console.WriteLine("The largest word is {0} characters long.", LargestWord);

//


Output:
The largest word is 12 characters long.

Linq Example 38 - Max

11:18 PM
Linq Query:

//Max

            int[] myNumbers = { 5,8,6,2,1,9,4,6 };
            
            int Max = myNumbers.Max();

            Console.WriteLine(Max);

//


Output:
9

Linq Example 37 - Min Projection

11:14 PM
Linq Query:

// Min Projection

            string[] words = { "GodOfWar", "CallOfDuty", "AssasinCreed" };

            int shortestWord = words.Min(w => w.Length);

            Console.WriteLine("The shortest word is {0} characters long.", shortestWord);

//

Output:

The shortest word is 8 characters long.

Linq Example 36 - Min

2:29 AM
Linq Query:

//Minimum
            int[] intNumbers = { 1, 2, 3, 55, 99, 74, 102,0 };

            int min = intNumbers.Min();

            Console.WriteLine(min);

//

Output:
0

Linq Example 35 - Sum Projection

2:25 AM
Linq Query:

//Sum Projection
            string[] s = { "abc", "abcd", "ab", "a" };

            int totalChars = s.Sum(n => n.Length);

            Console.WriteLine(totalChars);

//

Output:

10

Linq Example 34 - Sum

2:24 AM
Linq Query:

//Sum
            int[] intNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int sum = intNumbers.Sum();
            Console.WriteLine(sum);

//

Output:
55

Linq Example 33 - Count Conditional

1:36 AM
Linq Query:

//Count Conditional
            int[] intNumbers = { 1, 2, 3, 55, 99, 74, 102 };

            int total = intNumbers.Count(n => n < 10 ); //Total 3 Items which are less then 10

            Console.WriteLine(total);

//

Output:
 3 

 Total 3 Items which are less then 10

Linq Example 32 - Count

12:27 AM
Linq Query:

//count
            int[] intNumbers = { 1, 2, 3, 55, 99, 74, 102 };

            int total = intNumbers.Count(); //Total 7 Items

            Console.WriteLine(total);

//

Output:
7

Linq Example 31 - All

11:54 PM
Linq Query:

//all
            int[] intNumbers = { 1, 2, 3, 55, 99, 74, 102 };

            bool blnLessThan200 = intNumbers.All(n => n <= 200);

            Console.WriteLine(blnLessThan200);

//

Output:
True
It will simply check if all the elements in array are less than 200.

Linq Example 30 - Any

11:50 PM
Linq Query: 

 //Any
            int[] intNumbers = { 1, 2, 3, 55, 99, 74, 102 };

            bool bln100to200 = intNumbers.Any(n => (n <= 200 && n >= 100));

            Console.WriteLine(bln100to200);

//

Output:
True
As you can see we want to find if any number is between 100 and 200. All the number except 102 are below 100. so our query return true as it find 102 that satisfy the condition.

Linq Example 29 - Repeat

11:33 PM
Linq Query:

//Repeat
            var Repeated = Enumerable.Repeat(4, 3); //Repeats 4 three times
            foreach (var t in Repeated)
            {

                Console.WriteLine(t);

            }



Output:
4
4
4

Linq Example 28 - Range

11:32 PM
Linq Query:

//Range
            var evenOddNumbers = 
                from n in Enumerable.Range(1,30)
                select new { Number=n, IsEven = (n % 2 ==0) ? "Even": "Odd"  };

            foreach (var t in evenOddNumbers)
            {
              
   Console.WriteLine(" Number:  {0}  IsEven : {1}", t.Number, t.IsEven); 

            }


Output:

Number:  1  IsEven : Odd
 Number:  2  IsEven : Even
 Number:  3  IsEven : Odd
 Number:  4  IsEven : Even
 Number:  5  IsEven : Odd
 Number:  6  IsEven : Even
 Number:  7  IsEven : Odd
 Number:  8  IsEven : Even
 Number:  9  IsEven : Odd
 Number:  10  IsEven : Even
 Number:  11  IsEven : Odd
 Number:  12  IsEven : Even
 Number:  13  IsEven : Odd
 Number:  14  IsEven : Even
 Number:  15  IsEven : Odd
 Number:  16  IsEven : Even
 Number:  17  IsEven : Odd
 Number:  18  IsEven : Even
 Number:  19  IsEven : Odd
 Number:  20  IsEven : Even
 Number:  21  IsEven : Odd
 Number:  22  IsEven : Even
 Number:  23  IsEven : Odd
 Number:  24  IsEven : Even
 Number:  25  IsEven : Odd
 Number:  26  IsEven : Even
 Number:  27  IsEven : Odd
 Number:  28  IsEven : Even
 Number:  29  IsEven : Odd
 Number:  30  IsEven : Even

Linq Example 27 - Element At

11:29 PM
Linq Query:

//Element At
            int[] intNums = { 1, 2, 3, 4 };

            var myNums = intNums.ElementAt(2); //means strating from 0 then 1 and then 2.

            Console.WriteLine(myNums);

//

Output:

3

Linq Example 26 - FirstOrDefault With Condition

11:26 PM
Linq Query:

int[] intNums = { 1, 2, 3, 4 };

            var myNums = intNums.FirstOrDefault(s => s == 5);

            Console.WriteLine(myNums);
            

           //Output will be 0 [Not Found]


Output:
0

Linq Example 25 - FirstOrDefault

11:22 PM
Linq Query:

int[] intNums = { };

            var myNums = intNums.FirstOrDefault();
            Console.WriteLine(myNums);

            //Output 0

Output:
0

Linq Example 24 - First With Condition

11:20 PM
Linq Query:

            //First Condition
            string[] strDays = { "Monday", "SaturDay", "Monday", "Friday", "TuesDay", "SaturDay" };

            var day = strDays.First(s => s.StartsWith("S"));
            Console.WriteLine(day);
 
            //

Output:
SaturDay

Linq Example 23 - First

11:10 PM
Linq Query:

        //First
        string[] strDays = { "Monday", "SaturDay", "Monday", "Friday", "TuesDay", "SaturDay" };
        
        var day = strDays.First();
        Console.WriteLine(day);

        //


Output:
Monday

Linq Example 22 - Of Type

11:06 PM
Linq Query:

//of type
            object[] myCollection = { "",5,"a",3.66,7,"y",2.89,"y",null,6};
            //Now i only want integer values from this collection of object
            
            var myInts = myCollection.OfType();

            foreach (var t in myInts)
            {
                Console.WriteLine(t);
            }


Output:


5
7
6

Linq Example 21 - To Dictionary

11:02 PM
Linq Query: 

//To Dictionary
            var scoreRecords = new[] { new {Name = "Alice", Score = 50},
                                new {Name = "Bob"  , Score = 40},
                                new {Name = "Cathy", Score = 45}
                            };

            var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);

            Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);


Output:

Bob's score: { Name = Bob, Score = 40 }

Linq Example 20 - ToList

10:53 PM
Linq Query:

//list
            int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            var Sorted =
                from s in Numbers
                orderby s descending
                select s;

            List  SortedArrayList = Sorted.ToList();

            foreach (int t in SortedArrayList)
            {
                Console.WriteLine(t);
            }


Output:


10
9
8
7
6
5
4
3
2
1

Linq Example 19 - ToArray

10:52 PM
Linq Query:

//To Array
            int[] Numbers= {1,2,3,4,5,6,7,8,9,10};

            var Sorted =
                from s in Numbers
                orderby s descending
                select s;

            int[] SortedArray = Sorted.ToArray();

            foreach (int t in SortedArray)
            {
                Console.WriteLine(t);
            }


Output:

10
9
8
7
6
5
4
3
2
1

Linq Example 18 - Except

10:50 PM
Linq Query:

//Except
            string[] s1 = { "a", "b", "c", "d", "e", "f" };
            string[] s2 = { "d", "e", "f", "g", "h", "i" };
            

            var s3 = s1.Except(s2);

            foreach (var t in s3)
            {
                Console.WriteLine(t);
            } 


Output:


a
b
c

All the value of s1 except values of s2 which are in s1 will be copied to s3.

Linq Example 17 - Intersect

10:47 PM

Linq Query:

//Intersect
            string[] s1 = { "a", "b", "c", "d", "e", "f" };
            string[] s2 = { "d", "e", "f", "g", "h", "i" };
            // d,e,f common

            var intersect_s3 = s1.Intersect(s2);

            foreach (var t in intersect_s3)
            {
                Console.WriteLine(t);
            }


Output:


d
e
f

It will list out the common values in both the array.

Linq Example 16 - Union

10:44 PM
Linq Query:

//Union
            string[] s1 = {"a","b","c","d","e","f"};
            string[] s2 = { "d","e","f","g","h","i"};
            // d,e,f repeats

            var union_s3 = s1.Union(s2);

            foreach (var t in union_s3)
            {
                Console.WriteLine(t);
            }


Output:


a
b
c
d
e
f
g
h
i

Here Repeating d,e,f will not be in union_s3 .  It's equivalent to sql union.

Linq Example 15-Distinct

4:57 AM
Linq Query:

//Distinct
            string[] strDays = { "Monday", "SaturDay", "Monday","Friday","TuesDay","SaturDay" };
            //Repeated Days" Monday,SaturDay

            var days = strDays.Distinct();
            foreach (var t in days)
            {
                Console.WriteLine(t.ToString());
            }


Output:
Monday
SaturDay
Friday
TuesDay

Linq Example 14-Group By Simple

4:53 AM
Linq Query:

//Group By

var emp1 = new { empno = 1, Department = "IT", Place="London"};
var emp2 = new { empno = 2, Department = "Computer", Place = "Paris" };
var emp3 = new { empno = 3, Department = "IT", Place = "Paris" };
var emp4 = new { empno = 4, Department = "Computer", Place = "Washington" };
var emp5 = new { empno = 5, Department = "Mechanical", Place = "Washington" };
var emp6 = new { empno = 6, Department = "Mechanical" , Place="Paris"};

var employees = new[] { emp1,emp2,emp3,emp4,emp5,emp6}; //Arrary of 6 Employees
//Finding Total Numbers of Employees in Each Department

var groups =
 from myEmp in employees
               group myEmp by myEmp.Department;

            foreach (var grp in groups)
            {
                Console.WriteLine("{0} : {1} ", grp.Key, grp.Count());
            }

            //Finding Total Numbers of Employees in Each Place
            var groups_Place =
                from myEmp in employees
                group myEmp by myEmp.Place;
            foreach (var grp in groups_Place)
            {
                Console.WriteLine("{0} : {1} ", grp.Key, grp.Count());
            }


Output For Qeury 1 :

IT : 2
Computer : 2
Mechanical : 2


Output For Qeury 2 :

London : 1
Paris : 3
Washington : 2





Linq Example 13 - Reverse

4:44 AM
Linq Query:

   //Reverse
            string[] alphabets = { "h", "b", "m", "q", "v", "p", "a", "c" };
            var reversed = alphabets.Reverse();

            foreach (var t in reversed)
            {
                Console.WriteLine(t.ToString());
            }




Output:

c
a
p
v
q
m
b
h




Linq Example 12 : Order by

4:40 AM
Linq Query:

//Order By
            string[] alphabets = { "h", "b", "m", "q", "v", "p", "a", "c" };

            //ascending
            var sorted =
                from s in alphabets
                orderby s    //by default ascending
                select s;

            foreach (var t in sorted)
            {
                Console.WriteLine(t.ToString());
            }


Output:


a
b
c
h
m
p
q
v


Now Descending Order by :

//desending
            var dsorted =
                from s in alphabets
                orderby s descending 
                select s;

            foreach (var t in dsorted)
            {
                Console.WriteLine(t.ToString());
            }


Output:

v
q
p
m
h
c
b
a


Linq Example 11 : Skip While

4:33 AM
Linq Query:

int[] numbers = { 5, 4, 1, 3, 1, 1, 1, 1, 1, 1 };
            
            var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);

            Console.WriteLine("All elements starting from first element divisible by 3:");
            foreach (var n in allButFirst3Numbers)
            {
                Console.WriteLine(n);
            }


Output:

3
1
1
1
1
1
1

Explanation: 
  • The only number here divisble by 3 is 3 at position four in numbers.
  • We will start from 5  and skip it as it is no divisible by 3.
  • Next skip 4,1 
  • Now its 3. we will add it to allButFirst3Numbers.. 
  • Now from now on all the number will be added to the allButFirst3Numbers.. As the name SkipWhile suggest.. we will skip until a number that is divisible by 3 is encountered. after that all the numbers will be added regardless of the condition.


Linq Example 10 - TakeWhile

4:03 AM
Linq Query:

//TakeWhile Example
            int[] myNumbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,0,1,2 };
            var numbslessthan6 = myNumbers.TakeWhile(n => n < 6);

            foreach (var t in numbslessthan6)
            {
                Console.WriteLine(t.ToString());
            }

Output:

0
1
2
3
4
5


  • Its like using a break in for loop.. here it will loop through all the myNumbers and if the number is less than 6 than its added to numbslessthan6.


  • Whenever a number greater than 6 in encountered the loop breaks even if there are number less than 6 after the current number which is greater than 6


Example:

for (int i = 0; i < myNumbers.Length; i++)
            {
                if (i < 6)
                {
                    Console.WriteLine(i.ToString());
                }
                else
                {
                    break;
                }
            }

Output:
 0
 1
 2
 3
 4
 5

Linq Example 9 : Skip Nested

3:52 AM
Linq Query:

//Skip Nested
            int[] myNumbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            var oddNumbers =
             (   from n in myNumbers
                let IsOdd = (bool)(n % 2 != 0)
                let IsEven = !IsOdd
                select new { n, IsOdd, IsEven }).Skip(2); //Skipping First Two [0,1 will be skipped]


            foreach (var t in oddNumbers)
            {
                Console.WriteLine("number : {0} , IsOdd : {1}, IsEven : {2}", t.n, t.IsOdd, t.IsEven);
            }



Output: 


number : 2 , IsOdd : False, IsEven : True
number : 3 , IsOdd : True, IsEven : False
number : 4 , IsOdd : False, IsEven : True
number : 5 , IsOdd : True, IsEven : False
number : 6 , IsOdd : False, IsEven : True
number : 7 , IsOdd : True, IsEven : False
number : 8 , IsOdd : False, IsEven : True
number : 9 , IsOdd : True, IsEven : False
number : 10 , IsOdd : False, IsEven : True
 Here 0,1 will not be added to "oddNumbers" list as we are skipping the First Two.

Linq Example 8 : Take Nested

3:44 AM
Linq Query:

//Nested Take  
            int[] Numbers1 = { 0, 2, 4, 6, 8 };
            int[] Numbers2 = { 1, 3, 5, 7, 9 };

            var myPair =
                (from n1 in Numbers1
                from n2 in Numbers2
                where n1 > n2
                select new { n1, n2 }).Take(3); //Nested Take - Taking only First Three Pair

            foreach (var t in myPair)
            {
                Console.WriteLine(t.n1.ToString() + " - " + t.n2.ToString());
            }


Output:


2 - 1
4 - 1
4 - 3



Linq Example 7 : Take

3:35 AM
Linq Query: 

//Take Example
            string[] strAlphabets = { "a","b","c","d","e","f"};

            var strFirstFour = strAlphabets.Take(4);

            foreach (var t in strFirstFour)
            {
                Console.WriteLine(t.ToString());
            }


Output:

a
b
c
d
It simply Take First 4 strings from strAlphabets .

Linq Example 6 - Compound From

3:29 AM
Linq Query:

int[] myNumbers = { 0, 11, 22, 33, 44, 55, 66, 77, 88, 99, 119, 129, 139, 149, 159 };
            //Query to find only even numbers that are smaller then 100

            var FinalNumbers =
                from evenNums in myNumbers
                where evenNums % 2 == 0 && evenNums < 100
                select evenNums;

            foreach (var t in FinalNumbers)
            {
                Console.WriteLine(t.ToString());
            }

Output:

0
22
44
66
88



Linq Example 5 : Using Let with Linq

3:25 AM
The use is easily understandable from the below query:

Linq Query:

//using Let in linq
            int[] myNumbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            var oddNumbers =
                from n in myNumbers
                let IsOdd = (bool)(n % 2 != 0)
                let IsEven = !IsOdd 
                select new { n, IsOdd,IsEven };


            foreach (var t in oddNumbers)
            {
                Console.WriteLine("number : {0} , IsOdd : {1}, IsEven : {2}", t.n, t.IsOdd, t.IsEven);
            }


Output: 

number : 0 , IsOdd : False, IsEven : True
number : 1 , IsOdd : True, IsEven : False
number : 2 , IsOdd : False, IsEven : True
number : 3 , IsOdd : True, IsEven : False
number : 4 , IsOdd : False, IsEven : True
number : 5 , IsOdd : True, IsEven : False
number : 6 , IsOdd : False, IsEven : True
number : 7 , IsOdd : True, IsEven : False
number : 8 , IsOdd : False, IsEven : True
number : 9 , IsOdd : True, IsEven : False
number : 10 , IsOdd : False, IsEven : True

Linq Example 4- SelectMany Compund From

5:18 AM
Linq Query:

//SelectMany Compound From 1
            int[] Numbers1 = { 0, 2, 4, 6, 8 };
            int[] Numbers2 = { 1, 3, 5, 7, 9 };

            var myPair =
                from n1 in Numbers1
                from n2 in Numbers2
                where n1 > n2
                select new { n1, n2 };

            foreach (var t in myPair)
            {
                Console.WriteLine(t.n1.ToString() +" - " + t.n2.ToString());
            }



Explanation:

What we are basically doing is that ,first we compute (Number1 X Number2) pairs.
we will have 25 pairs (5*5).

For example: (0,1),(0,3),(0,2) ... and so on..

Now i want to find in which pair the first element is greater than the second.
That 's what this query does it finds the pair ( out of this 25 ) which satisfy the condition.

Output:
2 - 1
4 - 1
4 - 3
6 - 1
6 - 3
6 - 5
8 - 1
8 - 3
8 - 5
8 - 7
2 - 1
4 - 1
4 - 3
6 - 1
6 - 3
6 - 5
8 - 1
8 - 3
8 - 5
8 - 7

We can do the same this with for loops .. see the code below which is equivalent to above linq query.

Without Linq:

for (int i = 0; i < Numbers1.Length; i++)
            {
                for (int j = 0; j < Numbers2.Length; j++)
                {
                    if (Numbers1[i] > Numbers2[j])
                    {
                        Console.WriteLine(Numbers1[i] + " - " + Numbers2[j]);
                    }
                }
            }



This above code will give the Same output as the linq query.

Linq Example 3- Select Filtered

5:09 AM
In this example we will use filter (where in sql).

Linq Query:

//Select Filtered.
            int[] myNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            var evenNumbers =
                from s in myNumbers
                where s % 2 == 0
                select s;

            foreach( var t in evenNumbers)
            {
                Console.WriteLine(t.ToString());
            }


Explanation:

We have an Array of Integer containing 10 number from 1 to 10. Now i only want those number which are divisible by 2, means even numbers.

Notice the Where in above query.

Output:

2
4
6
8
10


Linq Example 2 : Example 2- Anonymous Types

5:03 AM
In this example we will use Anonymous Types in Linq..

Let's See the Example:

string[] strWords =  { "oNe", "TwO", "tHrEe" };

            var words =
                from w in strWords
                select new { Upper = w.ToUpper(), Lower = w.ToLower() };

            foreach (var t in words)
            {
                Console.WriteLine(t.Lower + "  " + t.Upper);
            }




We are converting each string in strWords to its Lower and Upper Case and storing it to a new datatype with Two Properties :

1 . Lower
2.  Upper

It's Just like a structure and with each string in strWords we are creating a object of this structure containing the Lower and Upper Case of the respected strWords.

Output:

one  ONE
two  TWO
three  THREE

Linq Example 1 : A Simple Search

4:58 AM
Let's Say i have the following list of people's name:

"William H. Gates III"
"Warren Edward Buffet"
"Paul Gardner Allen"
"Sultan Hassanal Bolkiah"
"King Fahd Bin Abdulaziz Alsaud"
"Sheikh Zayed Bin Sultan Al Nahyan"
"Steven Anthony Ballmer"
"Amir Jaber Al-Ahmed Al-Jaber Al sabah"
"Phillip F. Anschutz"
"Michael Dell"

Now i want to search this name from a perticular word

In this example we will be searching for "Gates" Means our answer will be : "William H. Gates III"

Linq Qeury:

string[] strData = { "William H. Gates III", "Warren Edward Buffet", "Paul Gardner Allen", "Sultan Hassanal Bolkiah", "King Fahd Bin Abdulaziz Alsaud", "Sheikh Zayed Bin Sultan Al Nahyan", "Steven Anthony Ballmer", "Amir Jaber Al-Ahmed Al-Jaber Al sabah", "Phillip F. Anschutz", "Michael Dell" };
                
            var ans =
                from s in strData
                where s.Contains("Gates")
                select s;

            string strFound = "";
            foreach (var t in ans)
            {
                strFound += t.ToString() + Environment.NewLine ;
            }


Now After the above code the value of strFound will be : "William H. Gates III"


SameThing without linq can be done using following code:

string[] strData = { "William H. Gates III", "Warren Edward Buffet", "Paul Gardner Allen", "Sultan Hassanal Bolkiah", "King Fahd Bin Abdulaziz Alsaud", "Sheikh Zayed Bin Sultan Al Nahyan", "Steven Anthony Ballmer", "Amir Jaber Al-Ahmed Al-Jaber Al sabah", "Phillip F. Anschutz", "Michael Dell" };
                
            //without link
            strFound = "";
            foreach (string str in strData)
            {
                if (str.Contains("Gates"))
                {
                    strFound += str;
                }
            }



A simple Class for Moving Controls At Runtime

2:02 AM
Here Is The Class:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace MoveControl
{
   sealed class clsMoveControl
    {
        public enum Direction
        {
            Any,
            Horizontal,
            Vertical
        }

        public static void StartMoving(Control cntrl)
        {
            StartMoving(cntrl, Direction.Any);
        }

        public static void StartMoving(Control cntrl, Direction dir)
        {
            StartMoving(cntrl, cntrl, dir);
        }

        public static void StartMoving(Control cntrl, Control container, Direction dir)
        {
            bool Dragging = false;
            Point DragStart = Point.Empty;
            cntrl.MouseDown += delegate(object sender, MouseEventArgs e)
            {
                Dragging = true;
                DragStart = new Point(e.X, e.Y);
                cntrl.Capture = true;
            };
            cntrl.MouseUp += delegate(object sender, MouseEventArgs e)
            {
                Dragging = false;
                cntrl.Capture = false;
            };
            cntrl.MouseMove += delegate(object sender, MouseEventArgs e)
            {
                if (Dragging)
                {
                    if (dir != Direction.Vertical)
                        container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
                    if (dir != Direction.Horizontal)
                        container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
                }
            };
        }
    }
}



How to Use Example :

1. Create a simple project .
2. On the load event of the form write the following coding

clsMoveControl.StartMoving(this);

This will make the form movable by clicking anywhare on the form and dragging it.
The same can be done for other controls like:

clsMoveControl.StartMoving(Button1);
 clsMoveControl.StartMoving(Panel1);
 
See it Live:

Trimming a String Arrary

1:39 AM

Let's Say i have following array:

string[] myArray = new string[6];
            myArray[0] = "a";
            myArray[1] = "b";
            myArray[2] = " ";  //space
            myArray[3] = "c";
            myArray[4] = ""; //null
            myArray[5] = "d";
   


I want to remove the space and null parts from the array.
so after trimming the array should be like this:

            myArray[0] = "a";
            myArray[1] = "b";
            myArray[2] = "c";
            myArray[3] = "d";



Code:

public string[] TrimStringArray(string[] strArray)
        {
            
            int c = 0;
            foreach (string str in strArray)
            {
                if (str != "" && str != null)
                {
                    c++;
                }
            }

            string[] tempArrary = new string[c];
            int j=0;
            for (int i = 0; i < strArray.Length; i++)
            {
                if( strArray[i] != null && strArray[i] != "")
                {
                    tempArrary[j] = strArray[i];
                    j++;
                }
            }

            return tempArrary;
        }
   

Examle:
myArray = TrimStringArray(myArray);

What is Linq? Basic Introduction.

1:56 AM
Linq = "Language Integrated Query"

LINQ defines a set of method names (called standard query operators, or standard sequence operators), along with translation rules from so-called query expressions to expressions using these method names, lambda expressions and anonymous types.

LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

LINQ was released as a part of .NET Framework 3.5 on November 19, 2007.

LINQ Providers:

1. LINQ to Objects
2. LINQ to XML
3. LINQ to SQL
4. LINQ to DataSets
5. Other Providers

Example:

string[] strData = { "William H. Gates III", "Warren Edward Buffet", "Paul Gardner Allen", "Sultan Hassanal Bolkiah", "King Fahd Bin Abdulaziz Alsaud", "Sheikh Zayed Bin Sultan Al Nahyan", "Steven Anthony Ballmer", "Amir Jaber Al-Ahmed Al-Jaber Al sabah", "Phillip F. Anschutz", "Michael Dell" };
                
            var ans =
                from s in strData
                where s.Contains("Gates")
                select s;

            string strFound = "";
            foreach (var t in ans)
            {
                strFound += t.ToString() + Environment.NewLine ;
            }


As you can see we have a string array containing the Names. i want to a particular name containing string "Gates".

At the End strFound string will contain "William H. Gates III" as it is the only name containing the string "Gates"

Simple Wallpaper Changer

2:15 AM
Just a small Application i made to change wallpapers automatically at regular interval.

Screen:


I works fine with Windows XP and  windows 7 .

Well, i wont go to deep in code here is the complete project. enjoy.

Download: Wallpaper Changer

MultiPicBox control [With SlidShow]

12:18 AM
Once i was working with the Microsoft's PictureBox control. I noticed the each time i want to change the image i will have to create an Image object and Load my Image into and Assign it to PictureBox . And if i want to see the old pic (before assigning to new) i will have to again do the same.

So i thought why not make a control which support Multiple Pictures and a Slidshow Option..(with interval option).

Here are some pics of  the Control:



Properties:


AutoPreview               : Will automatically start the slideshow if enabled.
AutoResizeImages     : will automatically fit images to picture box if enabled.
ImageLimit                 : How many images should be there in control.
ImagesArrary             : Arrary of images to be displayed.
Interval                       : the interval time for the slidshow

Download Control:
Multipicbox

See it Live:


Listing All the Installed Softwares in Computer using .Net

5:26 AM
We will be Accomplishing using the Windows Registry.

Main Registry to work here is : "SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products"

Just Write Down The Following Code the Form's Loading Event (Form Contains No Control):

C#.NET

private void Form1_Load(object sender, EventArgs e)
        {
            string SoftwareKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products";
            RegistryKey rk = default(RegistryKey);
            rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);
            //string skname = null;
            string sname = string.Empty;

            ListView ListView1 = new ListView();
            this.Controls.Add(ListView1);
            ListView1.Dock = DockStyle.Fill;

            ListView1.View = View.Details;
            ListView1.Columns.Add("Installed Software");
            
            foreach (string skname in rk.GetSubKeyNames())
            {
                
                try
                {
                    sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName").ToString();
                    ListView1.Items.Add(sname);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);


        }


VB.NET
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim SoftwareKey As String = "SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products"
        Dim rk As RegistryKey
        rk = Registry.LocalMachine.OpenSubKey(SoftwareKey)
        Dim skname As String
        Dim sname As String = String.Empty

        Dim ListView1 As New ListView
        Me.Controls.Add(ListView1)
        ListView1.Dock = DockStyle.Fill

        ListView1.View = View.Details
        ListView1.Columns.Add("Installed Software")

        For Each skname In rk.GetSubKeyNames
            Try
                sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName")
                ListView1.Items.Add(sname)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Next

        ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)

    End Sub



Output:


Downloads:


vb.net : Download
c#.net : Download