In this blog you will find ASP.NET 3.5 articles and some code samples. These code samples are created by me and should be working. Thanks for visiting my blog! Happy Dot Netting

Thursday, January 22, 2009

LINQ to SQL - Inner Join

LINQ to SQL query to perform inner join on tables Product and ProductDocument on productID as primary key

protected void Page_Load(object sender, EventArgs e)
    {
        MydbDataContext db1 = new MydbDataContext();
        //LINQ to SQL query to perform inner join on tables Product and ProductDocument on productID as primary key
        var query = db1.Products.Join(db1.ProductDocuments, p => p.ProductID, m => m.ProductID, (c, m) => new {c.ProductID,m.DocumentID,c.Name });
        GridView1.DataSource = query;
        GridView1.DataBind();
    }



Wednesday, January 14, 2009

LINQ To SQL - Handling Database Paging

You can handle database paging through LINQ to SQL by using two methods 
Skip()—Enables you to skip a certain number of records.
Take()—Enables you to take a certain number of records.
Example is shown as below:
Add a Class file to project which would be added to APP_CODE folder.
For performing paging through LINQ to SQL, you would need to create a partial class Products having methods to select the records, record count and handle paging. This is shown below
Note: Please use required namespace as shown in picture for this code to work. 

Public partial class Products
{
    // Select method - selects all rows from product table
    public static IEnumerable Select()
    {
        MydbDataContext db1 = new MydbDataContext();
        return db1.Products;
    }
    
    //Select Paged Method - handles paging 
    public static IEnumerable SelectPaged(int startrowindex, int maximumrows)
    {
        return Select().Skip(startrowindex).Take(maximumrows);
    }
    
    //Count Method - return count
    public static int selectcount()
    {
        MydbDataContext db1 = new MydbDataContext();
        return db1.Products.Count();
    }
  }


Now add a gridview on defaulf.aspx. Allow paging and set page size = 5
Add an object data source. Set Enable paging = True, SelectMethod = SelectPaged and SelectCountMethod = selectcount, TypeName = Products. (You may perform this activity through wizard)


Set datasource of gridview = object data source. Execute the project to view the results. 5 rows would be visible in one page. You may click on link below to navigate to next five records. 

LINQ to SQL - Performing LIKE SQL queries

This blog would teach you to perform the equivalent of a LIKE Select with LINQ to SQL in several ways. 
First, you can use String methods such as Length, Substring, Contains, StartsWith, EndsWith, IndexOf, Insert, Remove, Replace, Trim, ToLower, ToUpper, LastIndexOf, PadRight, and PadLeft with LINQ to SQL queries
Alternatively, more flexible way to make LIKE queries is to use the System.Data.Linq.SqlClient.SqlMethods.Like() method.

This blog is an extension of my previous blog**. I have added five queries here which would give to insight about how to perform LIKE queries. Description of query is mentioned right above each query

  
protected void Page_Load(object sender, EventArgs e)
    {
        // ***Performing Like queries***
        // Query all rows where name starts with A
        //var query = db1.Products.Where(p => p.Name.StartsWith("A"));
        // Query all rows where name ends with p
        //var query = db1.Products.Where(p => p.Name.EndsWith("p"));
        // Query all rows where name contains p
        //var query = db1.Products.Where(p => p.Name.Contains("p"));
        // Query all rows where name lenght is 10
        //var query = db1.Products.Where(p => p.Name.Length == 10);

        // Query with SQL like method - This is more flexible as you can as many wildcards patterns as you need
        // For using Like method you would need to add System.Data.Linq.SqlClient;
        var query = db1.Products.Where(p => SqlMethods.Like(p.Name,"A%"));

        
        GridView1.DataSource = query;
        GridView1.DataBind();
    }

**Last blog Link http://myaspdotnet35.blogspot.com/2009/01/linq-to-sql-select-example.html
This will guide you how to prepare for this blog.
 



LINQ to SQL - Performing Select Queries

This blog is a extension of my last blog* and would describe how you can make select queries with LINQ to SQL. I have added four queries here which would give to insight about how to select a particular row or Column or if there is any condition. Description of query is mentioned right above each query

protected void Page_Load(object sender, EventArgs e)
    {
        MydbDataContext db1 = new MydbDataContext();
        // ***Query to view all columns and rows ****
        //var query = db1.Products.Select(p => p);

        // ***Query to view all columns and rows order by product number****
        //var query = db1.Products.Select(p => p).OrderBy(p => p.ProductNumber);

        // ***Query to view two columns and a particular row where productid = 4***
        // var query = db1.Products.Where(p => p.ProductID == 4).Select(p => new { p.ProductID, p.ModifiedDate });

        // ***Query to view two columns and rows where p.ReorderPoint = 600 and p.SafetyStockLevel = 1000***
        //var query = db1.Products.Where(p => p
.ReorderPoint = 600 && p.SafetyStockLevel = 1000 ).Select(p => new { p.ProductID, p.ModifiedDate });

        GridView1.DataSource = query;
        GridView1.DataBind();
    }

* Last blog Link http://myaspdotnet35.blogspot.com/2009/01/linq-to-sql-select-example.html
This will guide you how to prepare for this blog. 

Available below is a snap from code to view code with color coding. 

Friday, January 9, 2009

LINQ to SQL - Select Example

Select example of LINQ to SQL ( Example uses ASP.NET 3.5, AdventureWorks 2005 Database, C# as assumes that you know basic ASP.NET)

1. Create a new project/website in Visual C#. 
2. Add a LINQ To SQL class to your project
3. Drop the products table from database into designer surface. As you drag a new class in to surface explorer, strongly typed datacontext class is generated. 
4. Navigate back to default.aspx and drag and drop a gridview.
5. Now add following code on Page_Load event. 
6. Complie and execute.

   protected void Page_Load(object sender, EventArgs e)
    {
        MydbDataContext db1 = new MydbDataContext();
        var query = db1.Products.Where(p => p.ProductID == 4).Select(p => new { p.ProductID, p.ModifiedDate });
        GridView1.DataSource = query ;
        GridView1.DataBind();
    }

LINQ to SQL Query explanation: This LINQ to SQL query would select two column values from Product table where ProductID is 4

Here’s the output would look like

LINQ to SQL - Introduction

LINQ to SQL is feature intorduced in ASP.NET 3.5. Features intorduced in ASP.NET 3.5 to support LINQ to SQL

1. Automatic properties

Automatic properties provide you with a shorthand method for defining a new property. Why are automatic properties relevant to LINQ to SQL? When working with LINQ to SQL, you often use classes to represent nothing more than the list of columns you want to retrieve from the database (the shape of the data) like the select list in a SQL query. In those cases, you just want to do the minimum amount of work possible to create a list of properties, and automatic properties allow you to do this.

2. Initializers

3. Type Inference

When you take advantage of type inference, you allow the C# or VB.NET compiler to determine the type of a variable at compile time. No performance impact results from using type inference (the variable is not late bound). The compiler does all the work of figuring out the data type at compile time.

Here’s an example of how you use type inference with C#:

var message = “Hello World!”;

And here is how you would use type inference with VB.NET:

Dim message = “Hello World!”

4. Anonymous Types

Anonymous types are useful when you need a transient, fleeting type and you don’t want to do the work to create a class.

Here’s an example of creating an anonymous type in C#:

var customer = new {FirstName = “Stephen”, LastName = “Walther”};

Here’s how you would create the same anonymous type in VB.NET:

Dim customer = New With {.FirstName = “Stephen”, .LastName = “Walther”}

In a single line of code, we’ve managed to both create a new class and initialize its properties.

5. Generics

if you want to represent a list of strings, you can declare a list of strings like this (in C#):

List stuffToBuy = new List();

stuffToBuy.Add(“socks”);

stuffToBuy.Add(“beer”);

stuffToBuy.Add(“cigars”);

Here’s how you would declare the list of strings in VB.NET:

Dim stuffToBuy As New List(Of String)

stuffToBuy.Add(“socks”)

stuffToBuy.Add(“beer”)

And, by taking advantage of collection initializers, you can now declare a strongly typed list of strings in a single line like this (in C#):

List stuffToBuy2 = new List {“socks”, “beer”, “cigars”}; 

6. Lambda Expressions

Lambda expressions, another new language feature introduced with .NET Framework 3.5, provide you with an extremely terse way of defining methods.A lambda expression uses the => operator (the “goes into” operator) to separate a list of method parameters from the method body

(object sender, EventArgs e) => lblResult.Text = DateTime.Now.ToString();

 

7. Extension Methods

By taking advantage of extension methods, you can add new methods to existing classes. 

LINQ

LINQ stands for Language Integrated Query. LINQ consists of a set of new language features added to both the C# and VB.NET languages that enable you to perform queries. LINQ enables you to use SQL query–like syntax within C# or VB.NET.

You can perform a standard LINQ query against any object that implements the IEnumerable interface. An object that implements this interface is called a sequence. The C# language supports the following clauses that you can use in a query: 

From —Enables you to specify the data source and a variable for iterating over the data source (a range variable).

Where —Enables you to filter the results of a query.

Select —Enables you to specify the items included in the results of the query.

Group —Enables you to group related values by a common key.

Into —Enables you to store the results of a group or join into a temporary variable.

Orderby —Enables you to order query results in ascending or descending order.

Join —Enables you to join two data sources using a common key.

Let —Enables you to create a temporary variable to represent subquery results. 

Building a LINQ query is like building a backward SQL query. You start by specifying a from clause that indicates where you want to get your data. Next, optionally, you specify a where clause that filters your data. Finally, you specify a select clause that gives shape to your data (determines the objects and properties you want to return). 

So, the query

var results = from w in words

where w.Contains(“z”)

select w;

 

is translated into this query by the C# compiler:

var results = words.Where( w => w.Contains(“z”) ).Select( w => w ); 

The first query uses query syntax and the second query uses method syntax. The two queries are otherwise identical.

 

Here is a list of some of the more interesting and useful methods:

Aggregate() —Enables you to apply a function to every item in a sequence.

Average() —Returns the average value of every item in a sequence.

Count() —Returns the count of items from a sequence.

Distinct() —Returns distinct items from a sequence.

Max() —Returns the maximum value from a sequence.

Min() —Returns the minimum value from a sequence.

Select() —Returns certain items or properties from a sequence.

Single() —Returns a single value from a sequence.

Skip() —Enables you to skip a certain number of items in a sequence and return the remaining elements.

Take() —Enables you to return a certain number of elements from a sequence.

Where() —Enables you to filter the elements in a sequence.

 

LINQ TO SQL

LINQ to SQL enables you to perform LINQ queries against database data. Currently, you can use LINQ to SQL with Microsoft SQL Server 2000 or Microsoft SQL Server 2005

Note: To use LINQ to SQL, you need to add a reference to the System.Data.Linq.dll assembly.

you always want to specify the primary key column by using the IsPrimaryKey property. For example, if you don’t specify a primary key column, you can’t do updates against your database using LINQ. 

you almost always want to include a timestamp column in your database table and indicate the timestamp column by using the IsVersion property. If you don’t do this, LINQ to SQL will check whether the values of all the properties match the values of all the columns before performing an update command to prevent concurrency conflicts. If you specify a version property, LINQ to SQL can check the value of this single property against the database rather than all the columns.

The Column attribute supports the following properties:

AutoSync—Indicates whether the value of the property is synchronized with the value of the database column automatically. Possible values are OnInsert, Always, and None.

CanBeNull—Indicates whether the property can represent a null value.

DbType —Indicates the database column data type.

Expression—Indicates the expression used by a computed database column.

IsDbGenerated—Indicates that the value of the property is generated in the database (for example, an identity column).

IsDiscriminator—Indicates whether the property holds the discriminator value for an inheritance hierarchy.

IsPrimaryKey—Indicates whether the property represents a primary key column.

IsVersion—Indicates whether the property represents a column that represents a row version (for example, a timestamp column).

Name—Indicates the name of the database column that corresponds to the property.

Storage—Indicates a field where the value of the property is stored.

UpdateCheck—Indicates whether the property participates in optimistic concurrency comparisons. The Table attribute supports the following single property:

Name—Indicates the name of the database table that corresponds to the class.

 

Wednesday, January 7, 2009

Creating SQL Server 2005 login and user via SQL query

Create Login with password
CREATE LOGIN app3 WITH PASSWORD='app3', DEFAULT_DATABASE=master, CHECK_POLICY=OFF

Create login with windows domain account
CREATE LOGIN [Adventure-Works\Mary5] FROM WINDOWS;

As you create a login in SQL 2005 database, it assigns a fixed server role to login. By default it assigns a Public role (VIEW ANY DATABASE PERMISSION)

To assign any other fixed server role to login, you may use following T- SQL
sp_addsrvrolemember @loginame =  'apploginname' ,  @rolename =  'processadmin'

Note: To add server level and database level permissions, you should be a member of security admin

I tried to consolidate the information on SQL server fixed role. Please see following page for details about SQL server fixed role http://aspdotnetgeek.blogspot.com/2008/07/sql-server-2005-fixed-server-roles.html

Add user mapping
Following SQL would create a user in mydatabase and assign a default_schema as DBO

USE [mydatabase]
GO
CREATE USER [applogin] FOR LOGIN [applogin]
GO
USE [mydatabase]
GO
ALTER USER [applogin] WITH DEFAULT_SCHEMA=[dbo]
GO

A user can be assigned many schemas and has one default schema

db_accessadmin: Members of the db_accessadmin fixed database role can add or remove access for Windows logins, Windows groups, and SQL Server logins.

db_backupoperator: Members of the db_backupoperator fixed database role can backup the database.

db_datareader: Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.

db_datawriter: Members of the db_datawriter fixed database role can add, delete, or change data in all user tables.

db_ddladmin: Members of the db_ddladmin fixed database role can run any Data Definition Language (DDL) command in a database.

db_denydatareader: Members of the db_denydatareader fixed database role cannot read any data in the user tables within a database.

db_denydatawriter: Members of the db_denydatawriter fixed database role cannot add, modify, or delete any data in the user tables within a database.

db_owner: Members of the db_owner fixed database role can perform all configuration and maintenance activities on the database.

db_securityadmin: Members of the db_securityadmin fixed database role can modify role membership and manage permissions.

http://msdn.microsoft.com/en-us/library/ms189121.aspx