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

MySql Query To Get Important Column Properties of A Table

10:57 PM
MySql Query :

SELECT  COLUMN_NAME
      , DATA_TYPE
      , CHARACTER_MAXIMUM_LENGTH
      , NUMERIC_PRECISION
      , NUMERIC_SCALE
      , EXTRA
      , COLUMN_KEY
      , COLUMN_DEFAULT
      , IS_NULLABLE
      , COLUMN_COMMENT
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   table_name = 'YourTableName'
        AND TABLE_SCHEMA = 'YourDatabaseName'


Example OutPut:





MySql Query To List All The Tables in Perticular Database

10:46 PM
MySql  Query:
 
SELECT  TABLE_NAME
FROM    INFORMATION_SCHEMA.TABLES
WHERE   TABLE_SCHEMA = 'test'
 


Example OutPut:


Understanding StopWatch Class in c#

2:59 AM
Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Startmethod, then eventually call the Stop method, and then you check elapsed time using the Elapsed property. (From MSDN)


Let say i want to find out Total Time a Process has been Running. 
Like
1. How many Minutes or Second it took to insert 1000 record in Database?
2. How many time it took to update the Database ? etc ..


I provide a very Basic Example with a Console Application ..


The Stopwatch Class has two Primary Methods 1. Start() 2. Stop() and One Property that is Elapsed .


The Code:





using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace StopWatchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Console.WriteLine("Stop Watch Start....\n");
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine(i + "\n");
            }
            sw.Stop();
            Console.WriteLine("Stop Watch Stopped:");
            Console.WriteLine("Total Time: {0}", sw.Elapsed);
            Console.ReadLine();
        }
    }
}


As You can See I have started our Stopwatch Just Before My loop has started.
Now the Loop will Do its work ..
After That As Soon As we are out sw.Stop has been Called.

I have Just Recorded The Timing The Loop Took To Complete.

The Output Will Look SomeThing Like These:


Embeding Firefox Brower (Gecko Engine) in C# using GeckoFX

11:19 PM
Ever Thought if it was possible to not WebBrower control and use the Firefox Browser in your c# window Application...??

Yes ,, It is possible using GeckoFx wrapper class for  C#.net and vb also.

You will need the Followings:

1. GeckoFx Wrapper [Download]
2. Xul Runner [Download] (Download the zip file from here)

How to:

1.   Now Extract Skybound.GeckoFX.bin.v1.9.1.0.zip (First download).
      You will find Skybound.Gecko.dll and that's what we need.
2.   Now create a Project and name is GeckoFxcsharpBorwer or anything you like.
3.   Now  add the reference of the above dll and also add that to your toolbox.
4.   Now Exctract the Second downloaded file (xulrunner-1.9.1.2.en-US.win32.zip). and you will find xulrunner . This is the path to xulrunner runtime.
5.   Create a Form Layout Like The Figure Below:


Now The Coding Part:

Our Form's Constructor:(Providing the Path to XulRunner Runtime)

public Form1()
        {
            InitializeComponent();
            Skybound.Gecko.Xpcom.Initialize("Path To the xulrunner directory [Extracted from the Second Downloaded File]"); // for example "c:\\xulrunner\\"
        }

Form's Load Event:

private void Form1_Load(object sender, EventArgs e)
        {
            geckoWebBrowser1.Navigate("www.google.com");
        }

Stop Button click Event:


private void btnStop_Click(object sender, EventArgs e)
        {
            geckoWebBrowser1.Stop();
        }



Refresh Button Click Event:


private void btnRefresh_Click(object sender, EventArgs e)
        {
            geckoWebBrowser1.Refresh();
        }



Save Page Button Click Event:


private void btnSavePage_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = " Html File | *.html";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                geckoWebBrowser1.SaveDocument(sfd.FileName);
            }
        }


And Now Finally the Output:


That's All.

Complete Project : GeckoNet

ps: You can easily Add an Addressbar and other stuff

Parsing Comma Delemeted String in Sql

9:46 PM
I will just go with the Example as its Self Exclamatory.

Sql Query:
declare @string varchar(500)
set @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

declare @pos INT
declare @piece varchar(500)

-- Need to tack a delimiter onto the end of the input string if one doesn’t exist
if right(rtrim(@string),1) <> ','
 set @string = @string  + ','

set @pos =  patindex('%,%' , @string)
while @pos <> 0
begin
 set @piece = left(@string, @pos - 1)
 
 -- You have a piece of data, so insert it, print it, do whatever you want to with it.
 print cast(@piece as varchar(500))

 set @string = stuff(@string, 1, @pos, '')
 set @pos =  patindex('%,%' , @string)
end

Output:






A stored Procedure to Count Numbers of Rows in Table

9:33 PM
This a simple Stored procedure to count the total numbers of rows in each table of your Database.
I assume you have Northwind database installed.

The Stored Procedure
IF EXISTS ( SELECT  *
            FROM    sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[sp_GetRowsCountForAllTables]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[sp_GetRowsCountForAllTables]
GO

CREATE PROCEDURE sp_GetRowsCountForAllTables
    @DBName VARCHAR(128) = NULL
AS 
    SET nocount ON
    IF @DBName IS NULL 
        SET @DBName = DB_NAME()

    CREATE TABLE #a
        (
          TableName VARCHAR(128)
        , norows INT NULL
        , id INT IDENTITY(1, 1)
        )
 
    DECLARE @id INT
      , @maxID INT
      , @TableName VARCHAR(128)
      , @FKName VARCHAR(128)
      , @cmd NVARCHAR(1000)
      , @rc INT
      , @spcmd VARCHAR(1000)
 
    SET @cmd = 'exec ' + @DBName + '..sp_executesql N''insert #a (TableName) 
   select TABLE_NAME from information_schema.tables
   where TABLE_TYPE = ''''BASE TABLE'''' ''
  '
    EXEC (@cmd)
 
    SELECT  @id = 0
          , @maxID = MAX(id)
    FROM    #a
 
    WHILE @id < @maxID 
        BEGIN
            SELECT  @id = MIN(id)
            FROM    #a
            WHERE   id > @id
  
            SELECT  @TableName = TableName
            FROM    #a
            WHERE   id = @id
  
            SET @cmd = 'exec ' + @DBName
                + '..sp_executesql N''update #a set norows = (select rows from sysindexes where indid in (0,1) and id = object_id('''''
                + @TableName + '''''))'
            SET @cmd = @cmd + ' where #a.id = ' + CONVERT(VARCHAR(10), @id)
                + ''''
  
            EXEC  (@cmd)
            IF @rc <> 0
                OR @@error <> 0 
                BEGIN
                    RAISERROR('failed %s',16,-1,@TableName)
                    RETURN
                END
        END

    SELECT  *
    FROM    #a ORDER BY norows desc

    DROP TABLE #a
GO

The Output:

EXEC sp_GetRowsCountForAllTables



Finding Duplicates in a Table 's Column

3:36 AM
I assume You have Northwind Database.

I will be using The Employee Table.


As Show in the figure there are 6 Selected cells which are the Duplicates( Just assume it)
I want to find this number ( i mean 6.)

The query for the above is:

SELECT  Title
      , COUNT(Title) AS NumOccurrences
FROM    dbo.Employees
GROUP BY Title
HAVING  ( COUNT(Title) > 1 )

SELECT  *
FROM    dbo.Employees

Finding Total Number of Rows, Columns in a Database and Tables Sizes

3:24 AM
Here is the Script:

USE Northwind 
GO
CREATE TABLE #temp
    (
      table_name SYSNAME
    , row_count INT
    , reserved_size VARCHAR(50)
    , data_size VARCHAR(50)
    , index_size VARCHAR(50)
    , unused_size VARCHAR(50)
    )

SET NOCOUNT ON

INSERT  #temp
        EXEC sp_msforeachtable 'sp_spaceused ''?'''
SELECT  a.table_name
      , a.row_count
      , COUNT(*) AS col_count
      , a.data_size
FROM    #temp a
        INNER JOIN information_schema.columns b ON a.table_name COLLATE database_default = b.table_name COLLATE database_default
GROUP BY a.table_name
      , a.row_count
      , a.data_size
ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS INTEGER) DESC

DROP TABLE #temp


Output:


Check if a Perticular Database exist or not

3:13 AM

This is simple sql query:
USE master
Go


IF EXISTS ( SELECT  name
            FROM    sys.databases
            WHERE   name = 'MyDataBase' ) 
    PRINT 'Exists'
ELSE 
    PRINT 'Does Not Exists'

.Net Framework 3.0 Vs 3.5 Vs 4.0 (.Net FrameWork Comparisions)

12:09 AM


NET Framework 3.0 consists of four major new components:

  • Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. See WPF SDK for developer articles and documentation on WPF.
  • Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
  • Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
  • Windows CardSpace, formerly code-named InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.


Changes in 3.5 since 3.0

  • New language features in C# 3.0 and VB.NET 9.0 compiler
  • Adds support for expression trees and lambda methods
  • Extension methods
  • Expression trees to represent high-level source code at runtime.
  • Anonymous types with static type inference
  • Language Integrated Query (LINQ) along with its various providers
  • LINQ to Objects
  • LINQ to XML
  • LINQ to SQL
  • Paging support for ADO.NET
  • ADO.NET synchronization API to synchronize local caches and server side datastores
  • Asynchronous network I/O API.
  • Peer-to-peer networking stack, including a managed PNRP resolver
  • Managed wrappers for Windows Management Instrumentation and Active Directory APIs
  • Enhanced WCF and WF runtimes, which let WCF work with POX and JSON data, and also expose WF workflows as WCF services. WCF services can be made stateful using the WF persistence model.
  • Support for HTTP pipelining and syndication feeds.
  • ASP.NET AJAX is included.


Key focuses for 4.0  release are:

  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as statement lambdas, implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).

Source: wikipedia.org

Encryption and Decryption Functions In Vb.net

11:00 PM
Imports:

Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Text


Encryption:

Public Function Encrypt(ByVal plainText As String) As String

        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"

        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256

        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)


        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()

        symmetricKey.Mode = CipherMode.CBC

        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function

Decryption

Public Function Decrypt(ByVal cipherText As String) As String
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"

        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        ' Convert strings defining encryption key characteristics into byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        ' Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)

        ' First, we must create a password, from which the key will be 
        ' derived. This password will be generated from the specified 
        ' passphrase and salt value. The password will be created using
        ' the specified hash algorithm. Password creation can be done in
        ' several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)

        ' Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()

        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC

        ' Generate decryptor from the existing key bytes and initialization 
        ' vector. Key size will be defined based on the number of the key 
        ' bytes.
        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)

        ' Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New MemoryStream(cipherTextBytes)

        ' Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)

        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}

        ' Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)

        ' Close both streams.
        memoryStream.Close()
        cryptoStream.Close()

        ' Convert decrypted data into a string. 
        ' Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

        ' Return decrypted string.   
        Return plainText
    End Function


Example:
Dim strEncryptedText  As String
strEncryptedText  =  Encrypt("yourEncryptionText")

Dim strDecrptedText As String
strDecrptedText = Decrypt(strEncryptedText)


You can easily set the passphrase, saltvalue and bits to your liking..

For More Info Go to:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx


Fill free to Comment ..

A Function to Concat String Array Values by Specified Delimiter

2:13 AM
Let 's Say I have Following Array:

string[] st = new string[5];
            st[0] = "Animation";
            st[1] = "Action";
            st[2] = "Romance";
            st[3] = "Drame";
            st[4] = "Comedy";

Now I want to Merge all of it with ',' Delimiter Like Below:

Output :   Animation,Action,Romance,Drame,Comedy

Here is the Function For the Above
public string GetAllStringsFromArrary(string[] strArray,string strDelimeter)
        {
            string strFinal = string.Empty;

            for (int i = 0; i < strArray.Length ; i++)
            {
                strFinal += strArray[i];

                if (i != strArray.Length - 1)
                {
                    strFinal += strDelimeter;
                }
            }
            return strFinal;
            

        }
We will Call it Like This:
string str = GetAllStringsFromArrary( st,",");

Reading Tags From Mp3 Files

1:54 AM
In this post i will show you how to read the Tags like Album,Artist,Song Title,Year etc from mp3 , avi , ogg, Asf, Divx, png etc..

You will need Taglib - Sharp Library for this purpose .

Download the Library : http://download.banshee.fm/taglib-sharp/

you will find taglib-sharp.dll That's what we need.

1. Create a project . Name it something like TagReader
2. Add reference to the taglib-sharp.dll
3. Make a Form look something like  below figure.





Most of the Coding is Understandable so i will put the Whole form's coding.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TagLib;

namespace TagReadermp3
{
    public partial class frmTagReader : Form
    {
        public frmTagReader()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Mp3 Files | *.mp3";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                lblFile.Text = ofd.FileName;
            }

        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            TagLib.File mp3 = TagLib.File.Create(lblFile.Text);
            lblAlbum.Text = mp3.Tag.Album;
            lblAritst.Text = GetAllStringsFromArrary(mp3.Tag.AlbumArtists,",");   // Tag.AlbumAritst is a string array 
            lblBitsPerMinute.Text = mp3.Tag.BeatsPerMinute.ToString();
            lblComposers.Text = GetAllStringsFromArrary(mp3.Tag.Composers,",");
            lblCopyright.Text = mp3.Tag.Copyright;
            lblGenre.Text = GetAllStringsFromArrary(mp3.Tag.Genres,",");
            lblTitle.Text = mp3.Tag.Title;
            lblTrack.Text = mp3.Tag.Track.ToString();
            lblYear.Text = mp3.Tag.Year.ToString();
            lblLength.Text  = mp3.Properties.Duration.ToString();
        }

        public string GetAllStringsFromArrary(string[] strArray,string strDelimeter)
        {
            string strFinal = string.Empty;

            for (int i = 0; i < strArray.Length ; i++)
            {
                strFinal += strArray[i];

                if (i != strArray.Length - 1)
                {
                    strFinal += strDelimeter;
                }
            }
            return strFinal;
            

        }
    }
}

**New Length field added
Here is the Link to Complete Project : Tag Reader (Updated)
TagReader (old)

A Simple Gmail Client

3:42 AM
In This Post I will Guide u To making a Simple Gmail Client  to send Your Emails using Gmail Account Using Vb.net

 Let me Show You how final Result will Look Like:





1. For Sending Mail Through Vb.net. This Client Uses  "Imports System.Net.Mail".
    So First Import it to your Code





Imports System.Net.Mail

2. Layout All the Controls As Shown In the Above Figure

3. There is Progress Bar after the send Button. I have used Backgroud Worker To Send the Mail. So that When Mail Sending is in Progress the Screen Wont Stop Working.

4. Now Here is the Complete Code

First Define This In your Form

Dim msg As New MailMessage 
 Dim i As Integer 

Form's Load Event

Me.ProgressBar1.MarqueeAnimationSpeed = 0

Write This to Send Button's Click Event
msg.To.Add(Me.txtto.Text) 
        msg.From = New MailAddress(Me.txtuser.Text) 
        msg.Subject = Me.txtsubject.Text 
        msg.Body = Me.txtbody.Text 
        '' for attachment 
        For i = 0 To Me.ListBox1.Items.Count - 1 
            msg.Attachments.Add(New Attachment(Me.ListBox1.Items(i).ToString)) 
        Next 
        Me.Button1.Enabled = False 
        Me.Button1.Text = "Sendign.." 
        Me.ProgressBar1.Visible = True 
        Me.ProgressBar1.MarqueeAnimationSpeed = 100 
        Me.BackgroundWorker1.RunWorkerAsync()  


Attach Button's Click Event ( Button beside the listbox)
Dim d As New OpenFileDialog 
        d.ShowDialog() 
        Me.ListBox1.Items.Add(d.FileName.ToString()) 
        Me.ListBox1.Visible = True  


Now its the Back Ground Worker ...
Background worker's Do work Event:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
        
        Dim i As Integer = 0 
        Dim smtp As New SmtpClient 
        smtp.Host = "smtp.gmail.com" 
        smtp.EnableSsl = True 
        smtp.Port = 587 
        smtp.Timeout = 300000 
        smtp.Credentials = New Net.NetworkCredential(Me.txtuser.Text, Me.txtpass.Text) 
        'Dim ms As MailMessage 
        'ms = e.Argument 
        Try 
            '  Label5.Text = "Sending Message......." 
            'Me.Button1.Text = "Sending...." 
            ' Me.Button1.Enabled = False 
            'Me.BackgroundWorker1.ReportProgress(i,  
            smtp.Send(msg) 
            e.Result = "Done" 
        Catch ex As Exception 
            'Label5.Text = "Sending Failed........" 
            MessageBox.Show(ex.ToString()) 
        End Try  

Background Worker's Run work Completed Event:
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted 
        ' Label5.Text = "Message Sending Complete" 
        Me.ProgressBar1.MarqueeAnimationSpeed = 0 
        Me.Button1.Text = "Send" 
        Me.Button1.Enabled = True 
        MessageBox.Show("Sent") 
    End Sub  

And It's Done.

For Complete Project Email me at sandeepparekh9@gmail.com