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

Wednesday, November 18, 2009

Program to reverse a string in VB

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim String1 As String
Dim String2 As String
Dim NextChar As String
String2 = ""
String1 = "abcdefgh"
MsgBox(Len(String1))
For i = Len(String1) To 1 Step -1
NextChar = Mid(String1, i, 1)
String2 = String2 & NextChar
Next
MsgBox(String2)
End Sub

Friday, September 18, 2009

Attach and Detach the database by SQL

-- Get all the db names from SQL server
select name from sys.databases

-- Detach the Database
sp_detach_db 'Bugtracker'

-- Attach the database
Create database bugtracker On
(filename = 'F:\SQL Files\bugtracker.mdf'),
(filename = 'F:\SQL Files\bugtracker_log.ldf')
for attach

Go

Thursday, August 20, 2009

Loop through dataset

Imports System.Data.OleDb
Imports System.Data
Imports System.Diagnostics


Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim m_sConn1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=E:\Vikas\AutoExcel\myexcel.xls;" & _
"Extended Properties=""Excel 8.0;HDR=no"""
Dim conn2 As New OleDbConnection(m_sConn1)
Dim da As New OleDbDataAdapter("Select * From [Cities$]", conn2)
Dim ds As DataSet = New DataSet()
Dim i = 0

Dim j
da.Fill(ds)
Dim dr As DataRow
If ds.Tables(0).Rows.Count > 0 And ds.Tables(0).Rows.Count > 10 Then
For Each dr In ds.Tables(0).Rows
For j = 0 To 7
If UCase(ds.Tables(0).Rows(i).Item(j).ToString) = "TOTAL" Then
MsgBox(ds.Tables(0).Rows(i).Item(j + 1).ToString)
End If
Next
i = i + 1
Next

End If
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()

conn2.Close()

End Sub

Updating excel with ADO.NET


Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim m_sConn1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=E:\Vikas\AutoExcel\myexcel.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes"""
Dim conn2 As New OleDbConnection(m_sConn1)
Dim da As New OleDbDataAdapter("Select * From [Cities$]", conn2)
Dim ds As DataSet = New DataSet()
da.Fill(ds, "MyInventoryTable")

' Generate the UpdateCommand and add the parameters for the command.
da.UpdateCommand = New OleDbCommand( _
"UPDATE [Cities$] SET Qty = ?, Price=? WHERE Product = ?", conn2)
da.UpdateCommand.Parameters.Add("@Qty", OleDbType.Numeric).SourceColumn = "Qty"
da.UpdateCommand.Parameters.Add("@Price", OleDbType.Currency).SourceColumn = "Price"
da.UpdateCommand.Parameters.Add("@Product", OleDbType.VarChar, 255, "Product")

' Update the first two records.
ds.Tables(0).Rows(0)("Qty") = 1000
ds.Tables(0).Rows(0)("Price") = 10.1
ds.Tables(0).Rows(1)("Qty") = 2000
ds.Tables(0).Rows(1)("Price") = 20.2

' Apply the dataset changes to the actual data source (the workbook).
da.Update(ds, "MyInventoryTable")
conn2.Close()
End Sub

Add rows in excel workbook

Code below shows how to add new row in excel sheet using ADO.NET

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim m_sConn1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=E:\Vikas\AutoExcel\myexcel.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes"""
Dim conn2 As New OleDbConnection(m_sConn1)
Dim da As New OleDbDataAdapter("Select * From [Cities$]", conn2)
Dim ds As DataSet = New DataSet()
da.Fill(ds, "myexcel")

' Generate the InsertCommand and add the parameters for the command.
da.InsertCommand = New OleDbCommand( _
"INSERT INTO [Cities$] (Product, Qty, Price) VALUES (?, ?, ?)", conn2)
da.InsertCommand.Parameters.Add("@Product", OleDbType.VarChar, 255, "Product")
da.InsertCommand.Parameters.Add("@Qty", OleDbType.Double).SourceColumn = "Qty"
da.InsertCommand.Parameters.Add("@Price", OleDbType.Currency).SourceColumn = "Price"

' Add two new records to the dataset.
Dim dr As DataRow
dr = ds.Tables(0).NewRow
dr("Product") = "Bread" : dr("Qty") = 390 : dr("Price") = 1.89 : ds.Tables(0).Rows.Add(dr)
dr = ds.Tables(0).NewRow
dr("Product") = "Milk" : dr("Qty") = 99 : dr("Price") = 2.59 : ds.Tables(0).Rows.Add(dr)

' Apply the dataset changes to the actual data source (the workbook).
da.Update(ds, "myexcel")
conn2.Close()

End Sub

Wednesday, August 19, 2009

Excel with Asp.net

Following is the code which will retrieve records from excel file and show up in output window. You can modify it to show up in grid as well. Myexcel file contains a sheet named cities and three columns Product, qty and price.

Imports System.Data.OleDb
Imports System.Data
Imports System.Diagnostics

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim m_sConn1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=E:\AutoExcel\myexcel.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes"""
Dim conn2 As New OleDbConnection(m_sConn1)
Dim da As New OleDbDataAdapter("Select * From [Cities$]", conn2)
Dim ds As DataSet = New DataSet()
da.Fill(ds)
Debug.WriteLine(vbCrLf & "InventoryData:" & vbCrLf & "==============")
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows 'Show results in output window
Debug.WriteLine(System.String.Format("{0,-15}{1, -6}{2}", _
dr("Product"), dr("Qty"), dr("Price")))
Next
conn2.Close()

End Sub
End Class

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.