Wednesday 4 July 2012

ADO.NET

ADO.Net is ActiveX Data Objects using .Net Technology. It is a data provider model
which is used to connect different data source such as Sql Server, MySql Database, Oracle,
Oledb, ODBC data sources. But here we use Sql Server database at backend for storing records
to the database.
Use the following namespace in C#.net program for accessing the Sql Server classes.
using System.Data;
using System.Data.SqlClient;
If you are not using these namespaces in your program. Then you cannot use the Sql Server database classes and methods for establishing connection and cannot interact with Database.
After that make a connection.There are some connection string parameters that are used for
 making connection and transection between front-end (Windows Form) to back-end
(Sql Server Database) of application.These are listed below:
    Parameters
Description

Initial Catalog : Database Name.
Data Source : Identifies the server, Could be local machine, Machine domain name.
Integrated  security    : Set the SSPI Connection with User's Windows Login.
 Intergrated Security is secure when you are on single machine doing
 development.
User ID : Name of the user configured in SQL Server.
Password : Password matching the SQL Server User ID.

Here is the Sql Command used for establishing connection.
SqlConnection con = new SqlConnection("Data source = local; Initial Catalog = Northwind;
User Id = root; Password = Password");
The purpose of creating a connection object is so you can enable other ADO.NET code to work
with a database.
The Sequece of operation occruing in whole sqlconnection life time are as follows:
1. Instantiate the Sqlconnection.
2. Open the Connection.
3. Pass the connection to other ADO.NET objects.
4. Perform the actions (database operations such as insert, select to delete to the database)
     with the other ADO.NET objects.
5. Close the connection.
Here is the simple program for inserting data to the sql database table :
using System;
using System.Data;
using System.Data.SqlClient; // here is the namespace for the ms sql server database.
class Sqlclass
  {
        static void Main()
        { // Instantiate the Connection
           SqlConnection con = new SqlConnection("Data Source = local;
           Initial Catalog = Northwind; User Id = root");
           SqlDataReader rdr = null;
            try
                {           // Open the connection
                  con.open();
                          // Pass the connection to command object
                 SqlCommand cmd = new SqlCommand("Select * from table1", con);
                         //Use the connection
                        // get query results
                  rdr = cmd.ExecuteReader();
                                 //print the each record of the table
                          while(rdr.Read())
                             {
                               Console.WriteLine(rdr[0]);
                               }
                       }
                       finally
                       {
                           // close the reader
                        if(rdr!=null)
                       {
                          rdr.Close();
                         }
                        if(con!=null )
                           {
                                 // close the connection
                             con.Close();
                             }
                        }
                      }
                 }

Friday 2 March 2012

C# Timer Control in Windows Form

C# Timer Control in Windows Form.


Timer Control in C# is a control which generate events on timing of clock intervals in seconds, milliseconds and nanoseconds. This is the only control which is used to generate events automatically after a specified period of time (in seconds or minutes as user wants). Timer control has six properties in which interval property is used to set the interval of time in seconds, milliseconds etc. If a user assign the value of 1000 to interval property then the timer control generate event after one second. Here 1000 is equal to 1 second.

Let's take a example of Timer control in Windows Digital Clock.
1. Open Visual Studio 2010 IDE.
2. Select C# Windows Form Application.
3. After that, add three labels to your windows form, and assign the value 0 to text property of label control.
4. Add a Timer control from Toolbox. Set Enable property of Timer control to True and set value 1000 to         Interval property of Timer control in Properties tab.
5. Double Click on Timer control to create back end code where source code will be added to control for       completing the task.
6. When you double click on Timer control, a new window appears in front of you in IDE. Add this source
    code to that window and press F5 key or select run option in IDE to run the program.

Here the Source Code of Digital Clock:

      private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            label3.Text = Convert.ToString(Convert.ToInt32(label3.Text) + 1);
            if (label3.Text == "60")
            {
                label2.Text = Convert.ToString(Convert.ToInt32(label2.Text) + 1);
                label3.Text = "0";
                if (label2.Text == "60")
                {
                    label1.Text = Convert.ToString(Convert.ToInt32(label1.Text) + 1);
                    label2.Text = "00";
                    if (label1.Text == "24")
                    {
                        label3.Text = "00";
                        label2.Text = "00";
                        label1.Text = "00";
                    }
                }


            }

7. The first line of code shows that Timer control is enabled. Because if Timer control is disabled then Timer
    control cannot work.
8. Second line shows that label3 text (which is in string format) should be incremented, So to assign + 1
    value to label3 text we have converted label text to int format and after that again converts it into string
    format and stores incremented value into label3.Text.
9. You will see text on the label3 ( which is 0 ) increment after every one second. Like 1, 2, 3 and so on
     upto 60.Here label3 we have taken it as seconds in clock.
10. When the text of label3 reaches upto 59, then the text in label2 will be 1 and increment after every
       interval. Here label2 is for minutes and label1 is for hours in clock.

Here you have seen how can we use Timer control. Hope you enjoy it....

directory2009.com/add-url

Friday 10 February 2012

C# Data types

In C#.net language there are 4 types of data types and 2 of which are common because of their using in programming. These 2 commonly used data types are int and float. Now, int types are categorized into two forms these are signed and unsigned. Signed data types are those data types which can store negative value as well as positive value, but Unsigned data types can store only positive values.
The values range of the different data types as follows.

Types AliasAllowed Values
sbyteSystem.SByte-128 to 127
byteSystem.Byte0 to 255
shortSystem.Int16-32,768 to 32,767
ushortSystem.UInt160 to 65,535
intSystem.Int32-2,147,483,648 to 2,147,483,648
uintSystem.UInt320 to 4,294,967,295
longSystem.Int64-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulongSystem.UInt640 to 18,446,744,073,709,551,615

Here in the table s stands for signed data types and u stands for unsigned data types.

Now, we also need to store floating point values, for that we need float data types. There are basically three types of floating point data types and these are: float, double and decimal. Here the values range table of floating point data types:

TypesAlias For App. max range App. min range
floatSystem.Single1.5 x 10-45 3.4 x 1038
doubleSystem.Double 5.0 x 10-324 1.7 x 10308
decimalSystem.Decimal1.0 x 10-287.9 x 1028

  
Here three other simple types are available. These are:
              
TypesAlias forAllowed Values
charSystem.Char0 to 65,535
boolSystem.Booleantakes only true or false
stringSystem.Stringtakes only number or sequence
 of characters like "Microsoft"


C# data types are similar to Java but with little difference. 

Wednesday 8 February 2012

.NET 4.0

.NET 4.0 (2010) is the new framework after release of 3.5 (2007) version. In .NET 4.0 we get Parallel Linq and Task Parallel Library. In Linq you are working with objects. Linq query operations on three distinct actions:
a) obtain the data source.
b) create the query
c) execute the query.

Here is the Example of Linq Query in C#.Net:

class IntroToLINQ
{        
    static void Main()
    {
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

        // 2. Query creation.
        // numQuery is an IEnumerable<int>
        var numQuery =
            from num in numbers
            where (num % 2) == 0
            select num;

        // 3. Query execution.
        foreach (int num in numQuery)
        {
            Console.Write("{0,1} ", num);
        }
    }
}

Parallel Linq is basically for speeds up the execution of LINQ to Objects queries by executing the query delegates in parallel on multi-core computers

You can get further reading for Linq topics in (LINQ to Sql).

Now, We start about what is TPL Task Parallel Library.
Task Parallel Library is the set of public type of API's in System.Threading and System.Threading.Tasks namespaces in .Net 4. By using TPL developers can be more productive in the field of development of applications by using parallelism and concurrency to applications. By using TPL technique applications can handles the partitioning of work.the scheduling of threads on the ThreadPool, state management. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

Here, the example of  simple parallel.For Loop

namespace MultiplyMatrices
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Concurrent;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    class Program
    {
        #region Sequential_Loop
        static void MultiplyMatricesSequential(double[,] matA, double[,] matB,
                                                double[,] result)
        {
            int matACols = matA.GetLength(1);
            int matBCols = matB.GetLength(1);
            int matARows = matA.GetLength(0);

            for (int i = 0; i < matARows; i++)
            {
                for (int j = 0; j < matBCols; j++)
                {
                    for (int k = 0; k < matACols; k++)
                    {
                        result[i, j] += matA[i, k] * matB[k, j];
                    }
                }
            }
        }
        #endregion

        #region Parallel_Loop

        static void MultiplyMatricesParallel(double[,] matA, double[,] matB, double[,] result)
        {
            int matACols = matA.GetLength(1);
            int matBCols = matB.GetLength(1);
            int matARows = matA.GetLength(0);

            // A basic matrix multiplication.
            // Parallelize the outer loop to partition the source array by rows.
            Parallel.For(0, matARows, i =>
            {
                for (int j = 0; j < matBCols; j++)
                {
                    // Use a temporary to improve parallel performance.
                    double temp = 0;
                    for (int k = 0; k < matACols; k++)
                    {
                        temp += matA[i, k] * matB[k, j];
                    }
                    result[i, j] = temp;
                }
            }); // Parallel.For
        }

        #endregion


        #region Main
        static void Main(string[] args)
        {
            // Set up matrices. Use small values to better view 
            // result matrix. Increase the counts to see greater 
            // speedup in the parallel loop vs. the sequential loop.
            int colCount = 180;
            int rowCount = 2000;
            int colCount2 = 270;
            double[,] m1 = InitializeMatrix(rowCount, colCount);
            double[,] m2 = InitializeMatrix(colCount, colCount2);
            double[,] result = new double[rowCount, colCount2];

            // First do the sequential version.
            Console.WriteLine("Executing sequential loop...");
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            MultiplyMatricesSequential(m1, m2, result);
            stopwatch.Stop();
            Console.WriteLine("Sequential loop time in milliseconds: {0}", stopwatch.ElapsedMilliseconds);

            // For the skeptics.
            OfferToPrint(rowCount, colCount2, result);

            // Reset timer and results matrix. 
            stopwatch.Reset();
            result = new double[rowCount, colCount2];

            // Do the parallel loop.
            Console.WriteLine("Executing parallel loop...");
            stopwatch.Start();
            MultiplyMatricesParallel(m1, m2, result);
            stopwatch.Stop();
            Console.WriteLine("Parallel loop time in milliseconds: {0}", stopwatch.ElapsedMilliseconds);
            OfferToPrint(rowCount, colCount2, result);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }


        #endregion

        #region Helper_Methods

        static double[,] InitializeMatrix(int rows, int cols)
        {
            double[,] matrix = new double[rows, cols];

            Random r = new Random();
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    matrix[i, j] = r.Next(100);
                }
            }
            return matrix;
        }

        private static void OfferToPrint(int rowCount, int colCount, double[,] matrix)
        {
            Console.WriteLine("Computation complete. Print results? y/n");
            char c = Console.ReadKey().KeyChar;
            if (c == 'y' || c == 'Y')
            {
                Console.WindowWidth = 180;
                Console.WriteLine();
                for (int x = 0; x < rowCount; x++)
                {
                    Console.WriteLine("ROW {0}: ", x);
                    for (int y = 0; y < colCount; y++)
                    {
                        Console.Write("{0:#.##} ", matrix[x, y]);
                    }
                    Console.WriteLine();
                }

            }
        }

        #endregion
    }

}