Tuesday, 18 February 2014

Creating a simple model using MVC

In this section we will create a simple customer model, flourish the same with
some data and display the same in a view.


Step1:- Create a simple class file

The first step is to create a simple customer model which is nothing but a
class with 3 properties code, name and amount. Create a simple MVC project,
right click on the model folder and click on add new item as shown in the below
figure.
14
From the templates select a simple class and name it as customer.
15 

Create the class with 3 properties as shown in the below the code snippet.

public class Customer
{
private string _Code;
private string _Name;
private double _Amount;

public string Code
{
set
{
_Code = value;
}
get
{
return _Code;
}
}

public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}

public double Amount
{
set
{
_Amount = value;
}
get 
{
return _Amount;
}
}
}


Step2:- Define the controller with action

The next step is to add the controller and create a simple action display
customer as shown in the below code snippet. Import the model namespace in the
controller class. In the action we created the object of the customer class,
flourished with some data and passed the same to a view named as “DisplayCustomer”

public class CustomerController : Controller
{
…..
….
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer);
}
}

Step3:- Create strongly typed view using the class

We need to now join the points of MVC by creating views. So right click on the
view folder and click add view. You should see a drop down as shown in the below
figure. Give a view name, check create a strongly typed view and bind this view
to the customer class using the dropdown as shown in the below figure.



16
 
The advantage of creating a strong typed view is you can now get the
properties of class in the view by typing the model and “.” as shown in the
below figure.



17



Below is the view code which displays the customer property value. We have
also put an if condition which displays the customer as privileged customer if
above 100 and normal customer if below 100.

<body>
<div>
The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>
This is a priveleged customer
<% } else{ %>
This is a normal customer
<%} %>

</div>
</body>





Step 4 :- Run your application 

Now the “D” thing, hit cntrl + f5 and you will get the output.

18
















Passing Data between controllers and views

The controller gets the first hit and loads the model. Most of the time we
would like to pass the model to the view for display purpose.

As an ASP.NET developer your choice would be to use session variables, view
state or some other ASP.NET session management object.

The problem with using ASP.NET session or view state object is the scope.
ASP.NET session objects have session scope and view state has page scope. For
MVC we would like to see scope limited to controller and the view. In other
words we would like to maintain data when the hit comes to controller and
reaches the view and after that the scope of the data should expire.

That’s where the new session management technique has been introduced in ASP.NET
MVC framework i.e. ViewData.

13 

Step1:- Create project and set view data

So the first step is to create a project and a controller. In the controller
set the viewdata variable as shown in the below code snippet and kick of the
view.

public class DisplayTimeController : Controller
{
//
// GET: /DisplayTime/

public ActionResult Index()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View();
}

}

Step 2:- Display view data in the view.

The next thing is to display data in the view by using the percentage tag. One
important point to note is the view does not have a behind code. So to display
the view we need to use the <%: tag in the aspx page as shown in the below code
snippet.

<body>
<div>
<%: ViewData["CurrentTime"] %>
</div>
</body>

 

Creating a simple Hello world ASP.NET MVC application

In this Section we will create a simple hello world program using MVC template.
So we will create a simple controller, attach the controller to simple
index.aspx page and view the display on the browser.


Step1:- Create project


Create a new project by selecting the MVC 2 empty web application template as
shown in the below figure.
6
Once you click ok, you have a readymade structure with appropriate folders where
you can add controllers, models and views.

7

Step 2:- Add controller


So let’s go and add a new controller as shown in the below figure.
8

Once you add the new controller you should see some kind of code snippet as
shown in the below snippet.

public class Default1Controller : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
return View();
}
}

Step 3:- Add View


Now that we have the controller we need to go and add the view. So click on
the Index function which is present in the control and click on add view menu as
shown in the below figure.











9

The add view pops up a modal box to enter view name which will be invoked
when this controller is called as shown in the figure below. For now keep the
view name same as the controller name and also uncheck the master page check
box.

10 

Once you click on the ok button of the view, you should see a simple ASPX
page with the below HTML code snippet. In the below HTML code snippet I have
added “This is my first MVC application”.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
This is my first MVC application
</div>
</body>
</html>

Step 4:- Run the application


If you do a CNTRL + F5 you should see a error as shown in the below figure.
This error is obvious because we have not invoked the appropriate controller /
action.




11
 

If you append the proper controller on the URL you should be able to see the
proper view.

12






ASP.NET MVC

Here i will show you an example of ASP.Net MVC Hello World Application.

ASP.Net MVC Hello World tutorial:

Step 1: Open Visual Studio & Click on File - New Project

Step 2: In the New Project Dialog box under Visual Studio Installed templates - Select ASP.Net MVC Web Application & Name the project as HelloWorldMVC - You can create applications using Visual Basic or Visual C#. For now, Select Visual C# and Click on OK 


MVC HelloWorld1





























































Step 3: In the Next "Create unit Test project" dialog box Select - "No" for not creating a unit test project.

MVC HelloWorld2






Step 4: Now you will find one demo module is added in Solution Explorer as shown in figure.
MVC HelloWorld3

Step 5: Now Click on the  Debug (Press F5) button to Run the project. Now you will find a demo site as shown in figure. [Note we have modified the text of About Us through About.aspx]. This site by default have two link which are Home & About and also it has Login and register page which you can modify according to your need.
MVC HelloWorld4






Monday, 17 February 2014

Set MaxLength for Multiline TextBox in ASP.Net using jQuery

By default the MaxLength property does not work for Multiline TextBox and hence I have created a jQuery Plugin which sets MaxLength for ASP.Net Multiline TextBox and also displays the character count as text is typed.
 
Implementing the jQuery MaxLength Plugin for ASP.Net MultiLine TextBox (TextArea)
Below you will notice the implementation of the jQuery MaxLength plugin. The jQuery MaxLength plugin has the following required and optional parameters
1. MaxLength (required) – Integer value indicating the Maximum character length limit.
2. CharacterCountControl (optional) – By default the plugin will display character count below the TextArea, but user has option to explicitly specify the Character Count Control.
Note: The character count control can only HTML SPAN or DIV.
3. DisplayCharacterCount (optional) – Default true. If set to false the Character counting will be disabled.
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">script>
    <script type="text/javascript" src="MaxLength.min.js">script>
    <script type="text/javascript">
        $(function () {
            //Normal Configuration
            $("[id*=TextBox1]").MaxLength({ MaxLength: 10 });
 
            //Specifying the Character Count control explicitly
            $("[id*=TextBox2]").MaxLength(
            {
                MaxLength: 15,
                CharacterCountControl: $('#counter')
            });
 
            //Disable Character Count
            $("[id*=TextBox3]").MaxLength(
            {
                MaxLength: 20,
                DisplayCharacterCount: false
            });
        });
    script>
head>
<body>
    <form id="form1" runat="server">
    <div id="counter">
    div>
    <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Width="300" Height="100"
        Text="Mudassar Khan">asp:TextBox>
    <br />
    <br />
    <asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine" Width="300" Height="100">asp:TextBox>
    <br />
    <br />
    <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Width="300" Height="100">asp:TextBox>
    form>
body>
html>

Print Specific part of Web page in ASP.NET

In this short article I will explain how to print specific (particular) part of web page in ASP.Net using C# and VB.Net.

The idea is to place the contents to be printed inside an ASP.Net Panel control and then print the contents of the Panel control.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type = "text/javascript">
        function PrintPanel() {
            var panel = document.getElementById("<%=pnlContents.ClientID %>");
            var printWindow = window.open('', '', 'height=400,width=800');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write('</head><body >');
            printWindow.document.write(panel.innerHTML);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            setTimeout(function () {
                printWindow.print();
            }, 500);
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat = "server">
    <asp:Panel id="pnlContents" runat = "server">
        <span style="font-size: 10pt; font-weight:bold; font-family: Arial">Hello,
            <br />
            This is <span style="color: #18B5F0">Mudassar Khan</span>.<br />
            Hoping that you are enjoying my articles!</span>
    </asp:Panel>
    <br />
    <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick = "return PrintPanel();" />
    </form>
</body>
</html>
In the above HTML Markup I have an ASP.Net Panel control pnlContents whose contents needs to be printed and an ASP.Net Button btnPrint which has an OnClientClick event which will call the JavaScript method PrintPanel() to print the contents of the Panel.

Thursday, 13 February 2014

Simple Form based authentication example in ASP.Net

In this article I will explain with example how to implement simple Form based authentication using Login page and Login control in ASP.Net using C#.
The Form based authentication has been implemented using ASP.Net Membership Provider.
Database
I am making use of the same database table Users which was used in the article Simple User Registration Form Example in ASP.Net.
This example consists of two pages Login page (Login.aspx) using which the user will login and the Landing page (Home.aspx) which is the page user will be redirected after successful authentication.
 Login Page
This is the login form which will do the following:-
1. Authenticate user by verifying Username and Password.
2. Make sure user has activated his account. Refer my article for details Send user Confirmation email after Registration with Activation Link in ASP.Net
  HTML Markup
The HTML markup consists of an ASP.Net Login control for which the OnAuthenticate event handler has been specified.
<form id="form1" runat="server">
<asp:Login ID = "Login1" runat = "server" OnAuthenticate= "ValidateUser"></asp:Login>
</form>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;
Stored Procedure to Validate the User Credentials
The following stored procedure is used to validate the user credentials, this stored procedure first checks whether the username and password are correct else returns -1.
If the username and password are correct but the user has not been activated then the code returned is -2.
If the username and password are correct and the user account has been activated then UserId of the user is returned by the stored procedure.
CREATE PROCEDURE [dbo].[Validate_User]
      @Username NVARCHAR(20),
      @Password NVARCHAR(20)
AS
BEGIN
      SET NOCOUNT ON;
      DECLARE @UserId INT, @LastLoginDate DATETIME
     
      SELECT @UserId = UserId, @LastLoginDate = LastLoginDate
      FROM Users WHERE Username = @Username AND [Password] = @Password
     
      IF @UserId IS NOT NULL
      BEGIN
            IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId)
            BEGIN
                  UPDATE Users
                  SET LastLoginDate = GETDATE()
                  WHERE UserId = @UserId
                  SELECT @UserId [UserId] -- User Valid
            END
            ELSE
            BEGIN
                  SELECT -2 -- User not activated.
            END
      END
      ELSE
      BEGIN
            SELECT -1 -- User invalid.
      END
END
Validating the User Credentials
The below event handler gets called when the Log In button is clicked. Here the Username and Password entered by the user is passed to the stored procedure and its status is captured and if the value is not -1 (Username or password incorrect) or -2 (Account not activated) then the user is redirected to the Home page using FormsAuthentication RedirectFromLoginPage method.
C#
protected void ValidateUser(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Validate_User"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Username", Login1.UserName);
            cmd.Parameters.AddWithValue("@Password", Login1.Password);
            cmd.Connection = con;
            con.Open();
            userId = Convert.ToInt32(cmd.ExecuteScalar());
            con.Close();
        }
        switch (userId)
        {
            case -1:
                Login1.FailureText = "Username and/or password is incorrect.";
                break;
            case -2:
                Login1.FailureText = "Account has not been activated.";
                break;
            default:
                FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
                break;
        }
    }
}
Home Page
After successful login user will be redirected to this page.
 
HTML Markup
In this page I have made use of ASP.Net LoginName control to display the name of the Logged In user and LoginStatus control to allow user Logout.
<div>
    Welcome
    <asp:LoginName ID="LoginName1" runat="server" Font-Bold = "true" />
    <br />
    <br />
    <asp:LoginStatus ID="LoginStatus1" runat="server" />
</div>
Namespaces
You will need to import the following namespaces.
C#
using System.Web.Security;
Verify whether User has Logged In
Inside the Page Load event, first we verify whether the User is authenticated using the IsAuthenticated property. If the user is not authenticated then he is redirected back to the Login page using FormsAuthentication RedirectToLoginPage method.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.Page.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
    }
}
Web.Config Configuration
You will need to add the following configuration in the Web.Config file in the <system.web> section.
<authentication mode="Forms">
 <formsdefaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms>
</authentication>
 
 

Send user Confirmation email after Registration with Activation Link in ASP.Net

In this article I will explain how to send user confirmation email after registration with Activation link in ASP.Net using C# and VB.Net.
In order to validate the email address of the user provided during registration, a confirmation email with activation link in sent to the email address and when user clicks the link, his email address is verified and his account gets activated.
Database
In the previous article we have already created database named LoginDB which contains the following table named Users in it. For this article I have created a new table named UserActivation.
On the registration page I have made some changes in the RegisterUser event handler, if the username and email address are found valid then the SendActivationEmail method is executed
C#
protected void RegisterUser(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Insert_User"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
                cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
                cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                cmd.Connection = con;
                con.Open();
                userId = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
            }
        }
        string message = string.Empty;
        switch (userId)
        {
            case -1:
                message = "Username already exists.\\nPlease choose a different username.";
                break;
            case -2:
                message = "Supplied email address has already been used.";
                break;
            default:
                message = "Registration successful. Activation email has been sent.";
                SendActivationEmail(userId);
                break;
        }
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
    }
}
Inside the SendActivationEmail method, a unique Activation code is generated using Guid’s NewGuid method and it is inserted in the UserActivation table.
Then an email is sent to the user’s email address with the URL of the Activation page with generated Activation Code in the QueryString of the URL
C#
private void SendActivationEmail(int userId)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string activationCode = Guid.NewGuid().ToString();
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@UserId", userId);
                cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    using (MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text))
    {
        mm.Subject = "Account Activation";
        string body = "Hello " + txtUsername.Text.Trim() + ",";
        body += "<br /><br />Please click the following link to activate your account";
        body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
        body += "<br /><br />Thanks";
        mm.Body = body;
        mm.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential("sender@gmail.com", "<password>");
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
    }
}
 
 Activation email sent to the user
 
 
 
 
 

Simple User Registration Form Example in ASP.Net

In this article I will explain how to build a simple user registration form that will allow user register to the website in ASP.Net using C#.
User will fill up the registration form with details such as username, password, email address, etc. and these details will be saved in the database table.
The registration form will also make sure that duplicate username and email addresses are not saved by verifying whether username and email address must not exists in the table.
 
Database
For this article I have created a new database named LoginDB which contains the following table named Users in it.
 In the above table column UserId is set as primary key and it Identity property is set to true.
 
HTML Markup
The HTML Markup consists of some TextBox, their corresponding Validators and a Button. Other than RequiredField Validators there’s a CompareValidator to compare passwords and a RegularExpressionValidator to validate email address.
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <th colspan="3">
            Registration
        </th>
    </tr>
    <tr>
        <td>
            Username
        </td>
        <td>
            <asp:TextBox ID="txtUsername" runat="server" />
        </td>
        <td>
            <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUsername"
                runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            Password
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
        </td>
        <td>
            <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtPassword"
                runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            Confirm Password
        </td>
        <td>
            <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" />
        </td>
        <td>
            <asp:CompareValidator ErrorMessage="Passwords do not match." ForeColor="Red" ControlToCompare="txtPassword"
                ControlToValidate="txtConfirmPassword" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" />
        </td>
        <td>
            <asp:RequiredFieldValidator ErrorMessage="Required" Display="Dynamic" ForeColor="Red"
                ControlToValidate="txtEmail" runat="server" />
            <asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                ControlToValidate="txtEmail" ForeColor="Red" ErrorMessage="Invalid email address." />
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button Text="Submit" runat="server" OnClick="RegisterUser" />
        </td>
        <td>
        </td>
    </tr>
</table>
Stored Procedure to insert the User details
The following stored procedure is used to insert the user details such as username, password and email address.
The stored procedure first checks whether the username supplied already exists, if yes then it will return negative 1 value.
Then the stored procedure checks whether the email address supplied already exists, if yes then it will return negative 2 value.
If both username and email address are valid then the record will be inserted and the auto-generated UserId will be returned by the stored procedure.
CREATE PROCEDURE [dbo].[Insert_User]
      @Username NVARCHAR(20),
      @Password NVARCHAR(20),
      @Email NVARCHAR(30)
AS
BEGIN
      SET NOCOUNT ON;
      IF EXISTS(SELECT UserId FROM Users WHERE Username = @Username)
      BEGIN
            SELECT -1 -- Username exists.
      END
      ELSE IF EXISTS(SELECT UserId FROM Users WHERE Email = @Email)
      BEGIN
            SELECT -2 -- Email exists.
      END
      ELSE
      BEGIN
            INSERT INTO [Users]
                     ([Username]
                     ,[Password]
                     ,[Email]
                     ,[CreatedDate])
            VALUES
                     (@Username
                     ,@Password
                     ,@Email
                     ,GETDATE())
           
            SELECT SCOPE_IDENTITY() -- UserId                 
     END
END
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
Inserting the User Details
The following event handler is raised when the submit button is clicked, here the values from the Registration Form’s TextBoxes are passed to the stored procedure and the stored procedure is executed.
The return value from the stored procedure is captured in a variable and then based on its value appropriate message is displayed using JavaScript Alert message box.
C#
protected void RegisterUser(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Insert_User"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
                cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
                cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                cmd.Connection = con;
                con.Open();
                userId = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
            }
        }
        string message = string.Empty;
        switch (userId)
        {
            case -1:
                message = "Username already exists.\\nPlease choose a different username.";
                break;
            case -2:
                message = "Supplied email address has already been used.";
                break;
            default:
                message = "Registration successful.\\nUser Id: " + userId.ToString();
                break;
        }
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
    }
}
   
Message Box when registration is successful

Message Box when username already exists

Message Box when email address already exists

User record inserted in table