Thursday, July 11, 2013

Difference Between For loop and For each loop

For Loop:
It’s preferred when you know how many iteration you want. It is used to executes a block of statements for as long as a specified condition is true.

General Syntax:
for(Initialization; Test Condition; Increment)
{
       Statement;
}
Example: To add the number from 1 to 10 by using for loop and sum the number by series of 1+2+3+...+10.
using System;
using System.Collections.Generic;
using System.Text;
namespace for_loop
{
class Program
{
static void Main(string[] args)
{
  int[] arry = new int[] {1,2,3,4,5,6,7,8,9,10 };
    int s = 0;
    for (int i = 0; i < arry.Length; i++)
   {
        s = s+ arry[i];
   }
  Console.WriteLine("Sum is: {0}",s);
  Console.ReadKey();
}
}
}
Output : Sum is:55

For Each Loop:
It operates on collections of items, for instance arrays or other built-in list types. It does not use an integer index. Instead, it is used on a collection and returns each element in order. In the foreach-statement, you do not need to specify the loop bounds minimum or maximum. It traverse whole collection.

General Syntax:
foreach( Datatype item in items )
{
       Statement;
}
Example: To add the number from 1 to 10 by using foreach loop and sum the number by series of 1+2+3+...+10.
using System;
using System.Collections.Generic;
using System.Text;
namespace for_loop
{
class Program
{
static void Main(string[] args)
{
    int[] arry = new int[] {1,2,3,4,5,6,7,8,9,10 };
    int s = 0;
    foreach (int i in arry)
     {
        s = s+ i;
     }
  Console.WriteLine("Sum is: {0}",s);
  Console.ReadKey();
}
}
}
Output : Sum is:55
Conclusion:
Both the concepts are same only. For each is used for traversing items in a collection. It usually maintain no explicit counter and no use of index. They essentially say "do this to everything in this set", rather than "do this x times".
For loop is classified as an iteration statement. The statements in the for loop repeat continuously for a specific number of times. It as counter and integer index (ex: a[i], i represent the index value and change it by increment operation on each iteration).

Wednesday, July 10, 2013

LINQ with DML Queries

This Post is a continuation of LINQ.
Here the following concepts are explain about LINQ with DML Queries.
DML
Data Manipulation Language (DML) statements are used for managing data within schema objects. They are:
  • Select
  • Insert
  • Update
  • Delete

Select

The SELECT statement returns a result set of records from one or more tables. The SELECT statement has many optional clauses: WHERE, ORDER BY, GROUP BY
For Example:

  • A Table name as tbl_Student.
  • This table contain the following columns: StudentID, Firstname, Lastname, Location, Email.

LINQ SELECT Statement with WHERE Clause:

DataClasses1DataContext db = new DataClasses1DataContext();
var student =
      from stud in db.tbl_Students
      where db.Location == "Pondy"
      select stud;

LINQ SELECT Statement with ORDER BY:

DataClasses1DataContext db = new DataClasses1DataContext();
var student =
      from stud in db.tbl_Students
      orderby stud.Location
      select stud;

LINQ SELECT Statement with GROUP BY:

DataClasses1DataContext db = new DataClasses1DataContext();
var student =
      group s by s.tbl_Students into g
      where g.count() >= 1
      select new
      {
          g.Key,
          LocationCount = g.Count()
      };

Insert

To execute a SQL Insert, just add objects to the object model you have created, and call SubmitChanges on the DataContext.
The following example, Let insert  a new Student detail into tbl_Student table. This table contain the following columns: StudentID, Firstname, Lastname, Location & Email.

LINQ INSERT Statement:

DataClasses1DataContext db = new DataClasses1DataContext();
tbl_Student ts = new tbl_Student();
      ts.StudentID = textBox1.Text;
      ts.Firstname = textBox2.Text;
      ts.Lastname = textBox3.Text;
      ts.Location = textBox4.Text;
      ts.Email = textBox5.Text;
      db.tbl_Students.InsertOnSubmit(ts);
      db.SubmitChanges();
MessageBox.Show("Value inserted Successfully");

Update

To Update a database entry, first retrieve the item and edit it directly in the object model. After you have modified the object, call SubmitChanges on the DataContext to update the database.
The following example, Let retrieve a Student detail from tbl_Student table who are all from Location Pondy. Then change Location = “Pondy” to “Puducherry”. Finally SubmitChanges is called to send the changes to database.

LINQ UPDATE Statement:

DataClasses1DataContext db = new DataClasses1DataContext();
var Loc = from s in db.tbl_Student
      where Loc.Location.Contains(”Pondy”)
      select Loc;
foreach (var student in Loc)
{
   if (student.Location == "Pondy")
   {
        student.Location = "Puducherry";
   }
}
db.SubmitChanges();

Delete

To Delete an item, remove the item from the collection to which it belongs, and then call SubmitChanges on the DataContext to commit the change.
The following example, delete a Student detail from tbl_Student table who are all from Location 'Chennai'. Finally SubmitChanges is called to send the changes to database.

LINQ DELETE Statement:

DataClasses1DataContext db = new DataClasses1DataContext();
var delLoc = from s in db.tbl_Student
      where s.Location == "Chennai"
      select s;
   if (delLoc.Count() > 0)
   {
        db.tbl_Student.DeleteOnSubmit(delLoc.First());
        db.SubmitChanges();
   }

Tuesday, July 9, 2013

LINQ–Language Integrated Query

Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
UnderstandingLINQ

LINQ Providers:
  • LINQ to SQL
  • LINQ to XML
  • LINQ to Dataset
  • LINQ to Objects
LINQ to SQL:
LINQ to SQL is a component of .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language.
By using LINQ to SQL, you can use the LINQ technology to access SQL databases just as you would access an in-memory collection.
Step 1: The Below picture will explain how to add LINQ to SQL in your project
  • Open Visual Studio and goto New Project and select the Windows Form Application.
  • In Solution Explorer, right click the application name -> Add -> New item.
1

Step 2: After open the "Add New Item Wizard" select the LINQ to SQL classes file in Data Category.

2

Step 3: The Object Relational Designer allows you to visualize data classes in your code. By click Server Explorer to add the table.

3

Step 4: Connect Database using Server Explorer at Right side or click the link enable text.

4

Step 5: Connect to Database using Server Explorer.

5 1.Default DataSource is SQL Server(Sqlclient).

2.Type the server name.

3.Select authentication type based on sql server

4.Select the Database.

5.(Optional) Verify the connection using Test Connection.

6.Press OK to make a connection with database and our project.

Step 6: Drag the table from server explorer to Dataclasses file.

7

Step 7: Double click the Form in solution explorer and place a Datagridview control from Toolbox to form. Write the below code in Form Load event.
LINQ with SELECT Statement and without Where Clause

namespace linq_example
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
       
//Create DataContext object by using LINQ file DataClasses.
{
            DataClasses1DataContext db = new DataClasses1DataContext();
//Linq query using IQueryable for Select statement query.
             IQueryable<tbl_Student> student =
                from stud in db.tbl_Students
                select stud;
//set Datasource to DataGridView for bind the data.
            dataGridView1.DataSource = student;
        }
    }
}

The Above code used the concept of linq to sql with Select statment and bind the data into datagridview.

OUTPUT:
output
For Download Source Code: Click Here

Monday, July 8, 2013

ASP.NET 4.0 Providers

Several ASP.NET application services rely on a provider to manage storing and retrieving data from a data source. Each provider is specific to the data source. ASP.NET includes a SQL Server provider for the following ASP.NET features:

  • Membership (the SqlMembershipProvider class).
  • Role management (the SqlRoleProvider class).
  • Profile (the SqlProfileProvider class).
  • Web Parts personalization (the SqlPersonalizationProvider class).
  • Web events (the SqlWebEventProvider class).

The above features are we need to define in asp.net 'Web.config' file.

Web.config is the main settings and configuration file for an ASP.NET web application. The file is an XML document that defines configuration information regarding the web application.This file stores the information about how the web application will act. The web.config file contains information that controls module loading, security configuration, session state configuration, and application language and compilation settings. Web.config files can also contain application specific items such as database connection strings.

<?xml version="1.0"?>
<configuration>
<connectionstrings>
<add name="ApplicationServices"
connectionstring="data source=localhost;Integrated Security=True;Initial Catalog=aspnetdb" providername="System.Data.SqlClient" />
</connectionstrings>

<system.web>
<compilation debug="false" targetframework="4.0" />

<authentication mode="[Windows|Forms|Passport|None]">
</authentication>

<membership defaultprovider="name of membership provider what you've created.">
<providers>"part for membership provider properties." </providers>
</membership>

<profile>
<providers>"part for profile provider properties." </providers>
</profile>

<rolemanager enabled="false">
<providers>"part for role provider properties." </providers>
</rolemanager>
</system.web>

<system.webserver>
<modules runallmanagedmodulesforallrequests="true" />
</system.webserver>
</configuration>

Configuring SQL Server Provider by Web.config file.

SQL Membership Provider:

ASP.NET membership gives you a built-in way to validate and store user credentials. ASP.NET membership therefore helps you manage user authentication in your Web sites. You can use ASP.NET membership with ASP.NET forms authentication by using with the ASP.NET login controls to create a complete system for authenticating users.

ASP.NET membership supports facilities for:

  • Create a new users and passwords.
  • Storing membership information (user names, passwords, and supporting data)
  • Authenticating users who visit your site.
  • Managing passwords, which includes creating, changing, and resetting them .
<membership defaultProvider="AspSqlMembershipProvider">
<providers>
<add name="AspSqlMembershipProvider"
          type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="datasource connection name"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          requiresUniqueEmail="false"
          maxInvalidPasswordAttempts="5"
          minRequiredPasswordLength="6"
          minRequiredNonalphanumericCharacters="0"
          passwordAttemptWindow="10"
          applicationName="/" />
</providers>
</membership>

SQL Role Provider:

ASP.NET role management helps you to manage authorization, allowing you to specify which resources various users in your application are allowed to access. Role management lets you treat groups of users as a unit by assigning users to roles such as manager, sales, member, and so on. The primary purpose of establishing roles is to give you an easy way to manage access rules for groups of users. You create users and then assign the users to roles (in Windows, to groups). A typical use is to then create a set of pages that you want to restrict to certain users.

<roleManager defaultProvider="AspSqlRoleProvider" enabled="true">
      <providers>
        <clear />
        <add connectionStringName="ApplicationServices"
             applicationName="/"
             name="AspSqlRoleProvider"
             type="System.Web.Security.SqlRoleProvider" />
      </providers>
    </roleManager>

ASP.NET SQL Server Registration Tool (Aspnet_regsql.exe)

The ASP.NET SQL Server registration tool (Aspnet_regsql.exe) is used to create a Microsoft SQL Server database that is used by the SQL Server providers in ASP.NET. The tool is also used to add or remove options from an existing database.

You can run Aspnet_regsql.exe without any command-line arguments to run a wizard that will walk you through specifying connection information for your SQL Server installation, and installing or removing the database elements for the membership, role management, profile, Web Parts personalization, and health monitoring features.

goto [ c: -> windows folder -> Microsoft.NET folder -> Framework folder -> folder with version like v 4.0, v3.5 and select the file “aspnet_regsql.exe” ]

step 1: After double click the "aspnet_regsql.exe" file, the below

1

step 2: Click Next to continue the wizard. And select the "Configure SQL server application services"

2

step 3: Click Next to continue the wizard. And select the “Server and Database.”

3

step 4: View the Setting summary details.

4

step 5: By click finish to Complete the configuration.

5