Powered by Blogger.

Working with enterprise library for data access in asp.net Part-3

To work with enterprise library you have to download required from this URL. Here we will use Enterprise Library 5.0 version. We need to give reference in Bin folder to the following dlls: Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll

Asp.Net MVC4 sample application

we will make a sample application using Asp.Net MVC4. Open Visual Studio 2010, then go to File -> New Project. This will open the New Project dialog box. From there make sure .Net Framework 4 is selected. Then select the Visual C# -> Web templates list. From the web template lists, Select ASP.NET MVC 4 Web Application and give a name.

Object Oriented Programming (OOP) concepts in .Net

Mainly there are 3 things in OOPs concept. 1- Inheritance 2- Abstraction 3- Polimorphism Inheritance is one of the key feature of oops concept and C# supports inheritance. Inheritance is a process of deriving the new class from already existing class. It allows you to reuse existing code.

Tutorial on MVVM with WPF

MVVM is nothing but Model view and viewModel.This is the best architecture for WPF. VIEW: A View is defined in XAML and should not have any logic in the code-behind. It binds to the view-model by only using data binding. The View contains the visual controls that will be shown to the user.This is the UI.

WCF tutorial and example in C#.Net

We will discuss how to create a WCF service and how we can consume the WCF service. Open Visual Studio 2010, then go to File -> New -> Project. Then from the New Project dialog box, From the Installed Templates Select WCF from the left hand site, And then Choose WCF Service Library and Give a proper name and Click on OK.

Thursday, September 26, 2013

Difference between Dataset and Datareader asp.net

In this blog we will discuss about difference between datareader and dataset in Ado.Net.

Also you can check out:

How To Call a Button Click From Another Button in C#.Net?

RangeValidator example in Asp.Net

Bind dropdownlist from enum in Asp.Net

(1)-It is defined with multiple tables.

(2)-It is a disconnected architecture.

(3)-It can't be defined without DataAdapter.

(4)-Dataset is able to fetch record in bidirection.

(5)-Dataset having read/write acess.

(6)-It comes under disconnected architecture.

(7)-It is slower as compared to datareader.

(1)-It is a readonly and forward only data i.e Read-Only access.

(2)-You can access one table at a time .

(3)-It comes under connected architecture.

(4)-One of the most advantage is that it is much faster than dataadapter.

(5)-Using Datareader only one value can be accessed at a time from the database.

(6)-Here the data is retrieved based on the select statement .

(7)-We can't do DML operations through datareader.

Caching in Asp.Net

Caching is a very good technique provided by Asp.Net to improve performance of a Asp.Net site. Caching is the process of storing frequently used data on the server to fulfill subsequent requests. This technique improves web response time. Through this technique we store some static or dynamic content in server cache memory so that web server can easily retrieve data in the next time when the request come. This also minimizes the database hits as well as minimize the consumption of server resources.

There are different types of caching in asp.net like below:

1. Page Level Output Caching:
This is the most simplest form of caching. Output caching simply keeps a copy of the HTML that was sent in response to a request in memory. Subsequent requests are then sent the cached output until the cache expires, resulting in potentially very large performance gains.

To implement page output caching we have to add OutputCache directive to the page like below:

<%@ OutputCache Duration="60" VaryByParam="*" %>

Here Duration and VaryByParam are mandatory parameters and appart from that there are also parameters like Location, VaryByHeader, VaryByCustom.

Duration: specifies the time the page should be cached (in seconds).

VaryByParam: Specifies the name of variables for request. The value "none" represents  no variation and the value "*" represents to create new cache entries for every different set of variables.

2. Fragment Caching or User Control Output Caching:
Like page level caching we can also implement caching to the user controls. Fragment caching allows us to cache certain blocks of your website.

To implement caching we have to add OutputCache directive like below:

<%@ OutputCache Duration="60" VaryByParam="*" %>

The parameters will be as explained in the Page Level Output Caching.

3. Data Caching:
The above type of caching will be helpful in caching the output of a page. We can also cache DataSet objects like below:

Cache["MyDataSet"] = dsMyDataSet;

Similarly to retrieve the dataset from the cache we can use like below:

DataSet dsFromCache = new DataSet();
dsFromCache = (DataSet)Cache["MyDataSet"];

Read and write from Text file in Asp.Net

Here we will disucss how we can read and write from a text file in Asp.net.

You will get a string array while reading all the lines and it will store one line to an array element in C#.Net.

And once you will get the array then you can modify what ever you want and then you can Write the whole array to the file.

Here is the code:

string[] Details = new string[0];
string strPath = @"C:\myfile.txt";
if (File.Exists(strPath))
                Details = File.ReadAllLines(strPath);

//Here you will get in the form of array
            Details [0] = "password^###~" + "What ever text you want";
Here you can write the whole array to the file.
            File.WriteAllLines(strPath, Details );

What is ContentPlaceHolder in Masterpage in asp.net?

In this post we will discuss about contentplaceholders in master page in asp.net. Also you can check out my previous posts on:

- ExecuteNonQuery(), ExecuteReader() and ExecuteScalar() in Ado.Net

- Singleton class in C#.Net

- Cookieless session in Asp.Net

In  ASP.NET Web site development master page is frequently used. A master page defines common structure, layout, navigation and default content for all of the webpages of web application including headers,footers, style definitions, or navigation bars. The master page can be shared by any of the pages in the Web site, called the Content page.A content page is a web page that is connected to master page and that displays its own individual content along with the content of the master page. The ContentPlaceHolder is used by the content page to display its own content.

Below is the ContentPlaceHolder tag:

<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

Master Page in Asp.Net

To create web pages with a consistent layout you need a way to define these relatively static regions in a single template file. Versions of ASP.NET prior to 2.0 did not have a template solution so you were forced to duplicate your page layout on every single page in the web site.Fortunately, this is no longer the case due to master pages.

Also you can check out my previous posts on:

- Shortcut keys in Visual Studio 2010

- Filter Attribute in MVC

- Functions and Subroutines in C#.Net

The biggest benefit of master pages is that they enable you to define the look and feel of all the pages in your site in a single location.

This means that if you want to change the layout of your site i.e, if you want to move the menu from the left to the right,you only need to modify the master page and the pages based on this master will pick up the changes automatically.

To some extent, a master page looks like a normal ASPX page. It contains static HTML such as the <html>, <head>, and <body> elements, and it can also contain other HTML and ASP.NET server controls.

A master page uses an @ Master directive that identifies the file as a master page.


<%@ Master Language="VB" %>


<%@ Master Language="C#" %>

The content pages, which are essentially normal ASPX files, but without the usual code you find in them like the <html>, <head>, <body>, and <form> elements, are connected to a master page using the MasterPageFile attribute of the Page directive:

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPages/Test.master"
AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default">

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

The page-specific content is then put inside a Content control that points to the relevant ContentPlaceHolder:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"

A master page is useless without a content page that uses it. Generally, you’ll only have a few master pages, whereas you can have many content pages.

DataAdapter in Asp.Net

In this article we will discuss about what is a dataadapter in asp.net and how to use dataadapter in asp.net. Also you can check out my previous posts on: Adding meta tags to aspx pages in asp.net, Bind gridview using datareader in asp.net and Method Overloading in C#.Net.

DataAdapter will act as a mediator between dataset and database server. This will perform 2 things:

- It will read data from database and place within dataset in the form of datatables.

- The manipulation on the dataset table will be updated with database.

string conn = "You connection string will goes here";


SqlConnection conn = new SqlConnection(conn);

SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);

DataSet ds = new DataSet();

da.Fill(ds, "Employees");

Here Employees is the datatable name.

Check out the below diagram how it is working:

Delete record using enterprise library in Asp.Net

In this article we will discuss how to delete a record using enterprise library in Asp.Net.

You should read how to use enterprise library in Asp.Net before starting this article.

You can also check my previous posts on How to convert ArrayList to String using C#? [Click here], Set default focus in Asp.net and Method Overloading in C#.Net.

In this post we will see, whenever a user put an id in the textbox and click on submit, the data should get deleted from the database. Below is the full code:

Store Procedure:

@Empid int

DELETE FROM EmloyeeDetail WHERE Empid=@Empid


.aspx code:

                    Emp Id
                    <asp:TextBox ID="txtEmpid" runat="server"></asp:TextBox>
                    <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
            <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;
using System.Data;

public partial class DeleteData : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
    protected void btnDelete_Click(object sender, EventArgs e)
        Database db = DatabaseFactory.CreateDatabase("connection");
        DbCommand dbCommand = db.GetStoredProcCommand("[DeleteEmployeData]");
        db.AddInParameter(dbCommand, "@Empid", DbType.Int32, Convert.ToInt32(txtEmpid.Text));

            int result = db.ExecuteNonQuery(dbCommand);
            if (result > 0)
                lblResult.Text = "Record deleted successfully!";
                lblResult.Text = "Some error occured!";
        catch (Exception ex)

Create datatable at runtime in Asp.Net

In this blog we will discuss about how to create a datatable at runtime in asp.net using C#.Net.

Also check my previous articles on Tutorials on WCF in Asp.Net, Implement SQL Server authentication in asp.net and Difference between Abstract Class and Interface in C#.Net

Below is the namespace needed.

using System.Data;

// Create a DataTable instance
DataTable dataTable = new DataTable("DataTableName");
// Create a DataColumn instances
DataColumn dtCol1 = new DataColumn();
DataColumn dtCol2 = new DataColumn();
dtCol1.ColumnName = "Id";
dtCol1.DataType = Type.GetType("System.Int32");

dtCol2.ColumnName = "Name";
dtCol2.DataType = Type.GetType("System.String");

// Add these DataColumns into the DataTable

// Create a DataRow Instance from the table we create above, with NewRow();
DataRow row = dataTable.NewRow();

row["Id"] = 1;
row["Name"] = "AspDotNetHelp";

// Add the row into the table

Tuesday, September 24, 2013

Get last modified time of a file in C#.Net

In this post we will discuss how to get the last modified time of a file in C#.Net.

Also you can check my previous posts on multithreading in C#.Net, Thread Pool class and Lock and Monitor statement in C#.Net.

To work with files and directory, Microsoft provides System.IO namespace.

Below is the sample code that will get the last modified time of the file in C#.Net.

string fileName = @"C:\AspDotNetHelp";
DateTime dt = File.GetLastWriteTime(fileName);
string modifiedTime = dt.ToString();

Similarly you can get the last file access time like below:

string fileName = @"C:\AspDotNetHelp";
DateTime dt = File.LastAccessTime(fileName);
string lastAccessTime = dt.ToString();

Also you can check how to delete a file in C#.Net and Partial class in C#.Net.

Working with enterprise library for data access in asp.net

In this post we will discuss about data access using enterprise library in Asp.net.

You can also check my previous posts on: ValidationGroup example in Asp.Net, WCF tutorial and example in C#.Net and Difference between primary key and foreign key in SQL server.

Here we will see how we can insert data into database by using inline sql statements using enterprise library in Asp.Net.

To work with enterprise library you have to download required from this url. Here we will use Enterprise Library 5.0 version.

We need to give reference in Bin folder to the following dlls:

Now open the web.config file to define the connection string. If you are using Windows authentication to login to database then write like below:

<add name="connection" providerName="System.Data.SqlClient" connectionString="Data  Source=localhost;database=TestDB;Integrated Security=SSPI"/>

But if you are using SQL Server authentication to login to SQL Server database then you can write like below:

<add name="connection" providerName="System.Data.SqlClient" connectionString="Data
Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=aspdotnethelp;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>

Below is the code:
.aspx code:
<form id="form1" runat="server">
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtLocation" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" /><br />
        <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Configuration;

public partial class EnterpriseLibraryTest : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void btnSubmit_Click(object sender, EventArgs e)
        Database db = DatabaseFactory.CreateDatabase("connection");
        string sql = "insert into Employees (Name,Age,JoiningDate,Location) values (@Name,@Age,@JoiningDate,@Location)";
        DbCommand dbCommand = db.GetSqlStringCommand(sql);
        db.AddInParameter(dbCommand, "@Name", DbType.AnsiString, txtName.Text.ToString());
        db.AddInParameter(dbCommand, "@Age", DbType.AnsiString, txtAge.Text.ToString());
        db.AddInParameter(dbCommand, "@JoiningDate", DbType.DateTime, DateTime.Now);
        db.AddInParameter(dbCommand, "@Location", DbType.AnsiString, txtLocation.Text.ToString());
           int result = db.ExecuteNonQuery(dbCommand);
           if (result > 0)
               lblResult.Text = "Record saved successfully!";
               lblResult.Text = "OOPS Some error occured!";
        catch (Exception ex)
            lblResult.Text = "OOPS Some error occured!";

Look at the using statements that we have used above.

After that the data will be save in the database. You can check Part-2 to do the same thing using Store Procedure.

Monday, September 23, 2013

Create dll in window based application in vb.net

In this post we will discuss how we can create a dll in windows bases application in vb.Net. Also you can check out my previous posts on:

- Single stored procedure to insert update and delete in sql server 2008

- Serialization and Deserialization in Remoting in C#.Net

 - Activation Models in Remoting in C#.Net

Follow below steps:

-> First open the Visual Studio.
-> Then go to File menu
-> create new project
-> select class library
-> select visual basic
-> Then give the name of the solution as myDll
-> Then give the location like D:\myDll1
-> Then press ok.

Below is the Example:
Public Class class1
Public Str As String
Public Function Display() As String
Return "AspDotnetHelp"
End Function
Public Function Add (By Val a As integer, By Val b As integer) As integer
Return a+b
End Function
End Sub
End Class

Then go to build option.
Select build myDll.(It creates some dll files in a location like D:\myDll1\myDll\myDll\bin\Debug\myDll.dll).

Tutorial on XHTML in Asp.Net

In this post we will discuss about What is XHTML. Also you can check out my previous posts on:

- Activation Models in Remoting in C#.Net

- Get nth highest lowest salary in SQL Server 2008

- Tutorial on Cookies in asp.net

"XHTML" stands for Extensible Hyper-Text Markup Language. This is considered as the extended version of Hypertext Markup Language (HTML) that has been modified to be valid XML. XHTML is an XML format. This language is well structured and is parsed by the XML parser. The implementation is purely based on its syntax rules.

The features of XHTML are given below:

-> It requires every tag to have corresponding closing tags.

-> It is case sensitive.

-> It requires all web pages to contain the<html>,<head>,<body> elements and the DOCTYPE declarations.

-> It requires that all attributes be enclosed in quotation marks and includes a space between each attribute

      width ="100" height="50" (valid)
      width ="100"height="50"(invalid)

-> Double dashes (--) are not allowed within comments

-> CSS (Cascading Style Sheets) rules apply only to documents that are delivered as text/html in XHTML.

-> It uses &amp instead of ampersand (even in hyperlinks) and always use &lt and &gt instead of less-than and greater-than symbols in your text.

-> The web pages written in XHTML are rendered properly in almost all browsers.

Tutorial on Asp.Net 4.0

Before discussing about Asp.net, it is important to know about .Net framework. In dotnet framework programs are written in a software environment called Common language runtime and an application virtual machine that provides services such as security, memory management and exception handling. Microsoft first release the .Net framework in 2002 with version as .Net framework 1.0. After that different versions released like 1.0 (Feb 2002), 1.1 (Apr 2003), 2.0 (Nov 2005), 3.0 (Nov  2006), 3.5 (Nov  2007), 4.0 (Apr  2010) and 4.5 (Aug  2012).

Asp.Net is one of the most popular Microsoft technology for developing web applications, web sites or web services.

ASP.NET is a technology for developing, deploying, and running Web applications. Asp.Net is a part of .NET framework, means while coding for Asp.Net application you can access to the .Net framework classes. Asp.Net allows us to use any language compatible to common language runtime (CLR), most popularly used C#.Net and VB.Net languages.

Asp.Net runs on IIS server and the page extension is ".aspx".

Microsoft provides tools for developing web applications like visual studio. Like different .Net framework versions, Microsoft released different versions of Visual Studio like Visual Studio 2003/2005/2008/2010 and visual studio 2012.

Apart from web applications or web sites, also by using .Net you can develop other applications like Windows form based applications, Console applications, Windows custom controls etc.

While working with Asp.net Microsoft allows to store data in databases like Microsoft SQL Server, Oracle, Access etc. To work with database .Net framework provides different classes popularly known as Ado.Net. It has different namespaces or classes to work with database. Apart from Ado.Net, you can also use Microsoft enterprise library to work with database from web applications or web sites.

Microsoft also provides a new improved technology to work with web applications which is known as MVC (Model View Controller).

There are different reason why Asp.Net popular like below:
- ASP.NET Is Integrated with the .NET Framework
- ASP.NET Is Compiled, Not Interpreted
- ASP.NET Is Multilanguage
- ASP.NET uses benifit of Common Language Runtime
- ASP.NET Is Object-Oriented
- ASP.NET Supports all Browsers
- ASP.NET Is Easy to Deploy and Configure
You can check this article to know more about why Asp.Net is so popular.

C#.Net is the most popular language used in Asp.net. C#.Net is fully object-oriented programming language. There are different versions of C#.Net comes like 1.0 (January 2002),  1.2 (April 2003), 2.0 (November 2005), 3.0 (November 2007), 4.0 (April 2010), 5.0 (August 2012).

While developing web application using Asp.Net, Apart from Asp.Net, C#.Net you can use Ajax, JavaScript, jQuery, CSS, HTML etc.

Below are some of concepts mostly used in Asp.Net like: Different web controls (Label, Button, validation controls, data controls like gridview etc), State Management (View State, Cookies, Session state, Application state), Asp.net caching, Asp.Net security, Connected and Disconnected data access using Ado.Net classes, Web.config, global.asax file etc.