Ehsan Tavakoli

Writing About .NET Programming and other stuff

Archive for the ‘asp.net’ Category

Three common ways to Connect to database in ASP.NET

with one comment

There are numbers of ways for building database driven websites using ASP.NET. In this post I’m going to show you three common ways of doing that. Please note these three are not the best ways for retrieving data from database and present it on the web. However, you may find one or coup of this ways easy, fast or even flexible for your specific project. In next articles I’m going to develop a small project using 3-layer architecture. But before that, I’m going to show other ways.

The Spaghetti Model

Oh yeah, the old fashion way for dealing with any kind of algorithm or database or even interface design.  To be honest, it still works well. Depends on what do you want to get. Or how much time do you have. Or simply about how much you care! No just joking! Here is sample page: retrieving information from [tblProduct] in [dbShop]. Present those two field on page and you can update them! Easy and straight forward.

using System;
using System.Configuration;
using System.Data.SqlClient;

namespace ecom
{
    public partial class spaghetti : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string sql = @"SELECT Title, Price FROM tblProduct WHERE ID=1";

                using (
                    SqlConnection myConnection =
                        new SqlConnection(ConfigurationManager.ConnectionStrings["NLayer"].ConnectionString))
                {
                    using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
                    {
                        myConnection.Open();
                        using (SqlDataReader myReader = myCommand.ExecuteReader())
                        {
                            if (myReader.Read())
                            {
                                txtTitle.Text = myReader.GetString(0).ToString();
                                txtPrice.Text = myReader.GetValue((1)).ToString();

                            }
                            myReader.Close();
                        }
                        myConnection.Close();
                    }
                }

        }
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            string sqlBase = @"UPDATE tblProduct SET Title='{0}', Price='{1}' WHERE ID=1";
            using (SqlConnection myConnection =
                new SqlConnection(ConfigurationManager.ConnectionStrings["NLayer"].ConnectionString))
            {
                string sql = string.Format(sqlBase, txtTitle.Text, txtPrice.Text);
                SqlCommand myCommand = new SqlCommand(sql, myConnection);
                myConnection.Open();
                myCommand.ExecuteNonQuery();
                myConnection.Close();
            }
        }
    }
}

But there is number of issues:

  1. SQL injection is a piece of cake for this code. However, you can put another method there to handle SQL Injection. Otherwise, you can loss your data in a snap!
  2. This code is hard to write and remember. And it’s hard to modify any fields in DB or add new field.
  3. You cannot use this code for other scenarios.



Using SqlDataSource Control

It’s another common ways to connect to database is using SqlDataSource. There are easy to configure and create CRUD (Create, Read, Update and Delete) procedures in a glance. Then you can easily assign them to control like the GrideView or ForView.

The problem is they make huge amount of codes on your page. And really you don’t know how they manage the transaction. Of course they put all things in XML files but it’s kind of hard to manage and edit these files. And it will become more complicated if you want to add your own function for conversation or validation of data.

Here is an example of using SqlDataSource Control for previous scenario.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="sqldatasource.aspx.cs" Inherits="ecom.sqldatasource" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:SqlDataSource ID="SqlDataSource1"
            ConnectionString="<%$ ConnectionStrings:dbEcomConnectionString %>"
            SelectCommand="SELECT * FROM [tblProduct]" runat="server"></asp:SqlDataSource>

    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
                ReadOnly="True" SortExpression="ID" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

Using TableAdapters
Another alternative way for working with database is using TableAdapters. They can be made by Visual Studio and all you need it’s just put your query statements and using the tools. You can access to business object by using classes that inherit form System.Data.DataTable and System.Data.DataRow by using method like AcceptChanges.
There is valuable article about using TableAdapters by Scott Mitchell’s here

In next few posts I’m going to build a simple website using 3-layer architecture..

*This article is highly adopted from here

Advertisements

Written by Ehsan Tavakoli

May 24, 2010 at 2:33 am

Simple code to use LINQ on a Generic list

with 2 comments

What is LINQ?

Most programmers today are required to integrate some sort of data into their applications. Often, you have to take data from multiple sources such as memory collections, relational databases, XML files, etc. With the current implementation of .NET Framework, getting to this data is often tedious and requires familiarity with multiple data access technologies and XML APIs. To make matters worse, all data sources have different means of querying the data in them: SQL for databases, XQuery for XML, LDAP queries for Active Directory etc. In short, today’s data access story lacks a unified approach to accessing data from disparate data sources, which is exactly what the LINQ (Language INtegrated Query) family of technologies are intended to solve.

Introduction to LINQ

The official goal of LINQ family of technologies is to add “general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data”. One of the nice things about LINQ is that it integrates seamlessly with the existing .NET languages such as C#, VB.NET because the underlying LINQ API is just nothing but a set of .NET classes that operate like any other .NET class. In addition, the query functionality is not just restricted to SQL or XML data; you can apply LINQ to query any class as long as that class implements IEnumerable class.

read it more here: http://www.15seconds.com/Issue/060713.htm

Here is a sample code to use LINQ on a generic list in ASP.NET 3.5. First, I’m going to create a sample class (Customer) with three variables: name, family and phone. Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Customer
{
    private String _name;
    private String _family;
    private String _phone;

	public List<Customer> fillCustomer()
	{
            List<Customer> customerList = new List<Customer>();
            customerList.Add(new Customer("Ehsan","Tavakoli","0234234234"));
            customerList.Add(new Customer("John", "Smith", "0366544574"));
            customerList.Add(new Customer("Eddie", "Williams", "085448782"));

            return customerList;
	}

    public Customer() { }

    public Customer(String name, String family, String phone)
    {
        _name = name;
        _family = family;
        _phone = phone;
    }

    public String name
    {
        get {return _name;}

        set {_name = value;}
    }

    public String family
    {
        get {return _family;}

        set {_family = value;}
    }

    public String phone
    {
        get {return _phone;}

        set {_phone = value;}
    }
}

As you can see, there are two Constructors for this class: Customer() and Customer(String name, String Family, String Phone) and there is method which generate our generic list of Customer

public List<Customer> fillCustomer()
{
            List<Customer> customerList = new List<Customer>();
            customerList.Add(new Customer("Ehsan","Tavakoli","0234234234"));
            customerList.Add(new Customer("John", "Smith", "0366544574"));
            customerList.Add(new Customer("Eddie", "Williams", "085448782"));

            return customerList;
}

In this method, first we create a list of Customer(s) and then add 3 sample Customer into this list.

Now, let look at our page:

Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
        Customer customer = new Customer();
        List<Customer> customerList = customer.fillCustomer();


        IEnumerable<Customer> customerQuery =
        from cust in customerList
        where cust.name == "Ehsan"
        select cust;
        
        foreach (Customer customerrow in customerQuery)
        {
            Response.Write(customerrow.family + ", " + customerrow.name);
        }

    }
}

you can see, we filled the “customerList” with our method. And then we use a Linq query over customerList. In this case, we just select customers with the first name “Ehsan”. And finally we just print them out using foreach loop.

Learn LINQ from MSDN:
http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

Written by Ehsan Tavakoli

March 8, 2010 at 12:16 pm

Posted in asp.net, Generic, Linq

Using MasterPage and Tableless design ASP.NET

with 3 comments

              
Hey again, in this post I’m going to show how easily we can use a tableless design (with div and CSS) with MasterPage in ASP.NET 3.5. The trick is that we need nested master pages.

1. For start, we need a tableless design. We can get free designs from: http://www.oswd.org
I chose a template called Grapes: http://www.oswd.org/design/preview/id/3567 it’s awesome! You can download it as well.

First, you need to copy the css file and images folder into your project. Then we need 3 different Masterpages to implement what we need. We assume that we need a dynamic menu and dynamic content.

Here is our template code: (it’s plain HTML with CSS)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Grapes</title>
<link rel="stylesheet" type="text/css" href="grapes.css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="Your name here" />
<meta name="Copyright" content="Copyright (c) Your copyright here 2005" />
</head>
<body>
<div id="container">
<div id="hdr">
<h1>grapes</h1>
<p id="tagline">fruit, wine &amp; web design</p>
</div>

<div id="lftcol">
 <ul id="nav">
  <li><a href="" id="current">Introduction</a></li>
  <li><a href="">Our Wines</a></li>
  <li><a href="">Important Grapes</a></li>
  <li><a href="">Contact Us</a></li>
  <li><a href="">Links</a></li>
 </ul>

<div id="quote">
<p><em>A great source for information...</em></p>
</div>
 
<h3>More stuff</h3>
 <ul>
  <li><a href="http://validator.w3.org/check?uri=referer">Validate XHTML</a></li>
  <li><a href="http://jigsaw.w3.org/css-validator/check/referer">Validate CSS</a></li>
  <li><a href="http://www.davereederdesign.com/">Authors Website</a></li>
  <li><a href="http://www.oswd.org/">OSWD</a></li>  
 </ul>

</div>



<div id="rgtcol">
<h2>Introduction</h2>
<p>Hello and welcome to my latest template called &quot;Grapes&quot;.  
<br /> 
&quot;Grapes&quot; is an Open Source web template which means it can be used without the need to ask permission and you have full rights to use and adapt its images.  For more of my work, please see my website which can be found  <a href="http://www.davereederdesign.com/">here.</a>
</p>
<p>
I wanted to create a fairly simple yet attractive template which can be used for food or wine related websites, although it can easily be adapted for other uses too. 
</p>


<h2>But is it <em>easy</em> to Use?</h2>
<p>&quot;Grapes&quot; should be quite easy to use as I have added plenty of comments and tried to make the <acronym title="Cascading Style Sheet">CSS</acronym> as neat and organised as possible. 
</p>
<p>There are also plenty of styles for other tags, including:</p>

<p><code>Text using the code tag, this is ideal for showing code on a page.</code></p>

<p><acronym title="acronym text">acronym text</acronym></p>

<p><strong>strong or bold text</strong></p>

<p><em>em or italic text</em></p>

<p>This is a paragraph of normal text that contains <span>span</span> tags with a class set to <span>special</span>.  This means all the <span>big words</span> in this paragraph are words that are placed between opening and closing <span>span</span> tags.  These span tags can be used to add meaning to a block of text or to <span>shout out</span> when needed.</p>
</div>

<div id="bttmbar">Copyright &copy; Your Copyright Info</div>


</div>

</body>
</html>

Second, HeaderMasterPage.master

<%@ Master Language="C#" MasterPageFile="~/MainMasterPage.master" AutoEventWireup="true" CodeFile="HeaderMasterPage.master.cs" Inherits="MasterPage1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
        <div id="hdr">
            <h1>
                grapes</h1>
            <p id="tagline">
                fruit, wine & web design</p>
        </div>


            <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
            </asp:ContentPlaceHolder>
     
</asp:Content>

and Third, MenuMasterPage.master

<%@ Master Language="C#" MasterPageFile="~/HeaderMasterPage.master" AutoEventWireup="true" CodeFile="MenuMasterPage.master.cs" Inherits="MasterPage2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
    <div id="lftcol">
<ul id="nav">
<li><a href="" id="current">Introduction</a></li>
<li><a href="">Our Wines</a></li>
<li><a href="">Important Grapes</a></li>
<li><a href="">Contact Us</a></li>
<li><a href="">Links</a></li>
</ul>

<div id="quote">
<p><em>A great source for information...</em></p>
</div>

<h3>More stuff</h3>
<ul>
<li><a href="http://validator.w3.org/check?uri=referer">Validate XHTML</a></li>
<li><a href="http://jigsaw.w3.org/css-validator/check/referer">Validate CSS</a></li>
<li><a href="http://www.davereederdesign.com/">Authors Website</a></li>
<li><a href="http://www.oswd.org/">OSWD</a></li>
</ul>

</div>



<div id="rgtcol">
            <asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server">
            </asp:ContentPlaceHolder>
</div>
</asp:Content>

now, we can use MenuMasterPage.master in our ASPX file

Here is a sample default.aspx file:

<%@ Page Title="" Language="C#" MasterPageFile="~/MenuMasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default3" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder3" Runat="Server">
<h2>Introduction</h2>
<p>Hello and welcome to my latest template called "Grapes".
<br />
"Grapes" is an Open Source web template which means it can be used without the need to ask permission and you have full rights to use and adapt its images.  For more of my work, please see my website which can be found  <a href="http://www.davereederdesign.com/">here.</a>
</p>
<p>
I wanted to create a fairly simple yet attractive template which can be used for food or wine related websites, although it can easily be adapted for other uses too.
</p>


<h2>But is it <em>easy</em> to Use?</h2>
<p>"Grapes" should be quite easy to use as I have added plenty of comments and tried to make the <acronym title="Cascading Style Sheet">CSS</acronym> as neat and organised as possible.
</p>
<p>There are also plenty of styles for other tags, including:</p>

<p><code>Text using the code tag, this is ideal for showing code on a page.</code></p>

<p><acronym title="acronym text">acronym text</acronym></p>

<p><strong>strong or bold text</strong></p>

<p><em>em or italic text</em></p>

<p>This is a paragraph of normal text that contains <span>span</span> tags with a class set to <span>special</span>.  This means all the <span>big words</span> in this paragraph are words that are placed between opening and closing <span>span</span> tags.  These span tags can be used to add meaning to a block of text or to <span>shout out</span> when needed.</p>
</asp:Content>

Look at the final screenshot:

Written by Ehsan Tavakoli

February 17, 2010 at 2:00 am

Sample use of CompareValidator and CustomValidator for Calendar component

leave a comment »

Here is a very simple sample about how we can use CompareValidator and also CustomValidator for checking calendar selection. In this example, there are two calendars which ask user to select his arrival and departure date. It can be usually used in booking systems. With validators we are trying to ask user to entry proper date at first and then want to force user to book at least for 2 days. We implement the last rule by using CustomValidator…

Here is our default.aspx source:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Booking</title>


<style type="text/css">
div.fixed 
{
    width: 900px;
    margin: 0px auto;
}

div.left 
{
    float: left;
    width: 450px;
}

div.right 
{
    float: right;
    width: 450px;
}
</style>


</head>
<body>
    <form id="form1" runat="server">
        <div class="fixed">
            <div class="left">
                <p>Select your arrival date:</p>
                

                <asp:TextBox ID="arriveTxt" runat="server"></asp:TextBox>
                <asp:Calendar ID="arrive" runat="server" 
                    onselectionchanged="arrive_SelectionChanged"></asp:Calendar>        
            </div>
            <div class="right">
                <p>Select your departure date:</p>
                

                <asp:TextBox ID="departureTxt" runat="server"></asp:TextBox>
                <asp:Calendar ID="departure" runat="server" 
                    onselectionchanged="departure_SelectionChanged"></asp:Calendar>    
            </div>
        
            <asp:CompareValidator ID="validator1" runat="server" ControlToValidate="departureTxt" ControlToCompare="arriveTxt" Type="Date" Operator="GreaterThan" Text="Please Select a Proper Date For Departure/Arrive"></asp:CompareValidator>
        
    
            

            <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
            <asp:CustomValidator ID="validator2" runat="server" ControlToValidate="departureTxt" OnServerValidate="ServerDateValidation">You Must at Least Book for 2 Days</asp:CustomValidator>
            

        
        </div>
    </form>
</body>
</html>

And this is our code behinde:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) {
            departure.SelectedDate = DateTime.Now.Date;
            arrive.SelectedDate = DateTime.Now.Date;
        
            departureTxt.Text = departure.SelectedDate.ToShortDateString();
            arriveTxt.Text = arrive.SelectedDate.ToShortDateString();

       }
    
    
    
    }


    protected void departure_SelectionChanged(object sender, EventArgs e)
    {
        departureTxt.Text = departure.SelectedDate.ToShortDateString();
    }

    protected void arrive_SelectionChanged(object sender, EventArgs e)
    {
        arriveTxt.Text = arrive.SelectedDate.ToShortDateString();

    }


    protected void Button1_Click(object sender, EventArgs e)
    {
    
    }
    protected void ServerDateValidation(object source, ServerValidateEventArgs args)
    {
        System.TimeSpan datediff = departure.SelectedDate - arrive.SelectedDate;

        if (datediff.Days > 2)
            args.IsValid = true;
        else
            args.IsValid = false;

    }
}

Written by Ehsan Tavakoli

February 16, 2010 at 12:13 am