.Net Better structure : With Product sample - Get Data (1)

Hi all, in this series of blog posts I'll explain how to create ASP.Net web applications using a better structure. This is the part 1 of this blog series, so in this post I'll try to explain how to retrieve data from database.

First go tot the Visual Studio and create a ASP.Net Empty Web Application project. Give a suitable name (I'll be using TestWeb).

Create database and tables with some sample data.
Now lets connect to that database using a connection string.

Web.config

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
        <add name="ProductDBConnectionString" connectionString="Data Source=LK-PRK\SQL2012DEV;Initial Catalog=ProductDB;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
</configuration>

Lets create Folder Connections and inside that create a class called Connection.
This is the class that we are going to use to retrieve the connection string for our database.

Connection.cs

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

namespace TestWeb.Connections
{
    public class Connection
    {
        public static SqlConnection GetConnection()
        {
            var conn = ConfigurationManager.ConnectionStrings["ProductDBConnectionString"].ConnectionString;
            return new SqlConnection(conn);
        }
    }
}

Lets create another folder to hold our domain objects. Lets called that folder 'Domains' and lets create a domain object; Product as bellow.

Product.cs

namespace TestWeb.Domains
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}

We will create another folder called DomainHelpers and create the following file called ProductHelper.

ProductHelper.cs

using System.Collections.Generic;
using System.Data.SqlClient;

namespace TestWeb.DomainHelpers
{
    public class ProductHelper
    {
        public List<Product> GetProducts()
        {
            var conn = Connection.GetConnection();
            conn.Open();
            var cmd = new SqlCommand("SELECT * FROM Products", conn);
            SqlDataReader dr = cmd.ExecuteReader();
            var products = new List<Product>();
            while (dr.Read())
            {
                var p = new Product
                {
                    Id = int.Parse(dr.GetValue(0).ToString()),
                    Name = dr.GetValue(1).ToString(),
                    Price = double.Parse(dr.GetValue(2).ToString())
                };
                products.Add(p);
            }
            return products;
        }
    }
}

Create web form called Products as bellow.

Products.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Products</h2>
        <asp:GridView ID="gridProducts" runat="server"></asp:GridView>
    </div>
    </form>
</body>
</html>

Inside the Products page, add the following to the Page_Load event handler. 

Products.aspx.cs

using System;
using TestWeb.ClassFiles;

namespace TestWeb
{
    public partial class Products : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var ph = new ProductHelper();
            gridProducts.DataSource = ph.GetProducts();
            gridProducts.DataBind();
        }
    }
}







Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#