Asp.Net MVC Membership Provider

Here we will learn how to use membership provider in asp.net mvc, and how to create users, and their roles using asp.net mvc membership, with this we will also learn how to assign roles to users in asp.net mvc membership provider, and how remove users from roles, after getting all roles users from asp.net mvc membership and we will implement security in asp.net mvc applications with examples.

To making security in asp.net mvc application use the following method to create the security in asp.net mvc application

(1) Authentication And Authorization in asp.net mvc

Authentication: It is the process of checking that the user is valid or not

Authorization: it is the process of checking that the user is applicable for the process or not

(2) Membership providers in asp.net mvc

(3) Roles based authentication for user in asp.net mvc

We will learn how to create a database for the membership provider in asp.net mvc and how to assign role to user, we will create a registration page to understand this

Let’s create a application for membership provider asp.net mvc.

Step (1) : Go to visual studio and click on new project -> a window will open from here select a ‘Asp.net MVC4 web application’ and give the name for this project in my case I give it as “MvcMembershipProvider “.

Now click ok and select a template as Internet Application and engine as Razor engine , after sleeting all these click ok. it will click a solution project this will contain .Css file ,script file and MVC application structure.

Step(2) : after creation of application let’s create a database for this and give the name for this database i gave it as ‘MVCApp’ and then add a connection string to the database.

         <connectionStrings>

<add name=”DefaultConnection” connectionString = “Data Source=MUNESH-PC;Database=MVCApp;UID=sa;Password=*****” providerName=”System.Data.SqlClient” />

</connectionStrings>

if you are creating new connection string then existinf connection string in ewb config file we have remove with we have remove a following line of code from the “InitializeSimpleMembershipAttribute.cs” which available in filter folder. because it give double connection existing run time error.

                       // WebSecurity.InitializeDatabaseConnection(“DefaultConnection”, “UserProfile”, “UserId”, “UserName”, autoCreateTables: true);

After adding the connection string to the project now we need to create membership tables to the database but before this go to the models folder and have a look on AccountModels.cs class. this class automatically create when we select mvc application as Internet application

AccountModel.cs class contain following methods.

now for creating membership tables in database initialize the connection in globel.asax . here we will use code first approach for that we need to add following code in this class

For adding data table in database membership we need to add a line of code in Global.asax

WebSecurity.InitializeDatabaseConnection(“DBConnection”, “UserProfile”, “UserId”, “UserName”, autoCreateTables: true);

Here namespace for WebSecurity is “using WebMatrix.WebData;”

WebSecurity.InitializeDatabaseConnection

Definition for the InitializeDatabaseConnection is

public static void InitializeDatabaseConnection (string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables);

connectionStringName:  It the name of database table where user information stored.

userTableName: It contain user profile information.

userIdColumn: this column name of table contain user ID this should be integer.

userNameColumn: column name of table contain user name. This column is basically used to match profile data of user with membership account data.

autoCreateTables: True to indicate that user profile and membership tables should be created if they do not exist; false to indicate that tables should not be created automatically. Although the membership tables can be created automatically, the database itself must already exist.

Now globel.asax page will look like

Now after all this configuration lets run your application and see the ur hoe page and click on register link which is your page right side.

After running your application you go to database and see the table, it will generate following tables for us

When you will click on registration link following screen will open with 3 field.

we can add more field to this view, for making change in registration view 1st need to add field in database table name is “UserProfile”;

Here we added 3 column as shown above now we need to add these column parameters in registration model ,it is in Account.cs class which is available in Model.

Code for registration model is

    public class RegisterModel

{

[Required]

[Display(Name = “User name”)]

public string UserName { get; set; }

[Required]

[StringLength(100, ErrorMessage = “The {0} must be at least {2} characters long.”, MinimumLength = 6)]

[DataType(DataType.Password)]

[Display(Name = “Password”)]

public string Password { get; set; }

[DataType(DataType.Password)]

[Display(Name = “Confirm password”)]

[Compare(“Password”, ErrorMessage = “The password and confirmation password do not match.”)]

public string ConfirmPassword { get; set; }

[Required]

[Display(Name = “EmailID”)]

public string EmailId { get; set; }

[Required]

[Display(Name = “address”)]

public string Address { get; set; }

[Required]

[Display(Name = “Mobile No”)]

public string MobileNo { get; set; }

}

Add these field in registration view

    <fieldset>

<legend>Registration Form</legend>

<ol>

<li>

@Html.LabelFor(m => m.UserName)

@Html.TextBoxFor(m => m.UserName)

</li>

<li>

@Html.LabelFor(m => m.Password)

@Html. PasswordFor (m => m.Password)

</li>

<li>

@Html.LabelFor(m => m.ConfirmPassword)

@Html.PasswordFor(m => m.ConfirmPassword)

</li>

<li>

@Html.LabelFor(m => m.EmailId)

@Html.TextBoxFor(m => m.EmailId)

</li>

<li>

@Html.LabelFor(m => m.Address)

@Html.TextBoxFor(m => m.Address)

</li>

<li>

@Html.LabelFor(m => m.MobileNo)

@Html.TextBoxFor(m => m.MobileNo)

</li>

</ol>

<input type=”submit” value=”Register” />

</fieldset>

Now if you will run your application and you will see registration page it will look with new fields.

Now according to this we need to add or handle these field in controller also so for that go to Account Controller and we have to make changes in HTTPPost method of registration Action.

Now the code for this action according to old registration model is

WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

Now will make changes in this according to new model

WebSecurity.CreateUserAndAccount(model.UserName, model.Password,

new

{

EmailID = model.EmailId,

Address = model.Address,

MobileNo = model.MobileNo

}

);

So the code for the Registration action method is

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public ActionResult Register(RegisterModel model)

{

if (ModelState.IsValid)

{

// Attempt to register the user

try

{

WebSecurity.CreateUserAndAccount(model.UserName, model.Password,

new

{

EmailID = model.EmailId,

Address = model.Address,

MobileNo = model.MobileNo

}

);

WebSecurity.Login(model.UserName, model.Password);

return RedirectToAction(“Index”, “Home”);

}

catch (MembershipCreateUserException e)

{

ModelState.AddModelError(“”, ErrorCodeToString(e.StatusCode));

}

}

// If we got this far, something failed, redisplay form

return View(model);

}

Now run your application and go to registration page and enter some data to fields then save it ,data will save in database.

 

 

Asp.net Server validation controls

The Validation Controls are used for validating the data entered in Text Box(input) Controls. When any user enters the data on a text Box (web page) and submits the page on the server ,then validation controls are used to check the data field  entered  by the user .if  any data entered by the user  is invalid (not correct format) then validation control displays  an error message on the screen. The entire error message is defined as properties values of validation controls. All the validation controls comes under System.UI.Webcontrols Namespace.

These are some validation controls that are used in ASP.Net which are given below:

  • The RequiredField Validator control
  • The RangeValidator control
  • The RegularExpressionValidator control
  • The CompareValidator control
  • The customValidator control
  • The Validationsummary control

The RequiredFieldValidator control:

It is used to check that there must be some value specify within the control.

Some important properties are given below:-

  • ControlToValidate: It is used to set the control field (text box) for validation.
  • Initial value: It is only guidance for user which display default in the control. This property can be used for drop down list.
  • Text:  It is used to set the text value (Name) to the validation control.

The RangeValidator control:

It checks whether or not the value of an input control is inside a specified range of values. These controls can be used with mobile Number, Age, and Date of Birth etc. on the websites. I will discuss later this with the help of a real time example.

There are some important properties of RangeValidator control which are given below:-

  • ControlToValidate: It is used to set the specific control to validate.
  • Minimum Value: It is used to hold the minimum value of the valid range.
  • Maximum value: It holds the maximum value of the valid range.
  • Type: You can set Type properties also after the above properties if required.

String –> For a string data type

Integer –> For a Integer Data type

Double:–> For A double data type

Currency –> For currency data type

Date    –> For a date data type

The CompareValidator control:

It is used to compare the values of two fields whether it is same or not. If both controls values are not same then it will show error message. I will implement this control below with one real example.
There is some operator property also that is used for different type of comparisons.

  • Equal: It is used to check whether the compared values are equal.
  • Not Equal: It is used to check that control is not equal to each other.
  • Greater than–> it is used for greater than relationship.
  • GreaterThanEqual: It is for GreaterThanEqual relationship.
  • Less than–> it is for less than relationship.
  • LessThanEqual:  It is for less than equal relationship.

The RegularExpressionValidation control:
It is use to check whether or not the text matches a certain pattern. There are some elements that used to make expression, which are given below:-
\d –> [0->9] .it takes value zero to nine.
\D–> other than [0->9].
\w –> [a->z][A->Z][0->9]
\s –> space
\S–> other value except space.
{Length}–> {min, max}
[ ] –> choice of given character (one out of them).
( ) –-> group of validator
–> OR
We can use special characters which are given below:
* –>  0 -> more numeric values
+ –>  1 –> more numeric values
? –> 0(min) or 1 (max)
Note: This is used to specify the preceded character, how many time used.

 The CustomValidator control:

This validation control is used to customize and implement data validation according to our condition and requirement.
Ex.
Suppose, if we want to check given number is even or odd then we cannot use our existing controls.so that, to solve this type of problem we can use customvalidation control in ASP.NET.
There are some properties of custom validator controls which are given below:-

  • ValidateEmptyText: It is used to set a Boolean value indicating whether empty text should be validated or not.
  • ClientValidationFunction: It is used to set the name of custom client -side script function used for validation.

There are some other important property that can be used for validation.Which are given below:

  • IsValid” property of page class:                                                                                                     If all the validations controls are IsValid property will be true, page class property also contains true. But if only one validation control IsValid property is false then page class property will also contains false.

Note: If any validation is failed then code will not executed.

  •  Cause Validation property of button control.                                                Every button has this property which contains by default ‘True’ value that means if we click on Button then all the validation on the form will fired. If we don’t want to validation check on the button click then we can change this value false.

The Button control and validation control has a property called Validation Group in which we specify the group name.

 The Validation Summary control:
This control is mostly less used. It is used to collect all the validation control error messages and display it collectively on the screen.
There is some important property of validation summary control

  • Display Mode: It is used to set the display mode of the validation summary control.
  • Forecolor: It is used to set the foreground color of the control.
  • HeaderText: It is used to set the header text displayed at the top of the summary.

Now I am going to Explain above Validation Controls with one Real time examples. There are some steps which are given below:

Step1: First open your visual studio→File→New→project→Select ASP.NET Empty Website→OK→Solution Explorer→Add New Web form→and drag and drop Label, Text Box ,Button and Validation controls  as shown below,

Step2: Now change then following things which are given below for every control

 RequiredFieldValidator: Go property of this control and change

ControlToValidate: Text Box, Which you want to validate.

Error Message: which you want to show on the screen.

Text: * (mandatory field), if required

RegularExpressionValidator: Go property of this control and change:-
ControlToValidate: Text Box, Which you want to validate.

Validation Expression: Use predefined Regular Expression or custom

Error Message: which you want to show on the screen.

Text: * (mandatory field),if required

CompareValidator: Go property of this control and change:-

 Control To Compare: Which control you want to compare.

ControlToValidate: Text Box, Which you want to validate.

Error Message: which you want to show on the screen.

Text: * (mandatory field),if required

RangeValidator: Go property of this control and change:- 

ControlToValidate: Text Box, Which you want to validate.

Error Message: which you want to show on the screen.

Maximum Value: Enter Maximum value limit.

Minimum Value: Enter Minimum value limit.

Text:* (mandatory field), if required

After the changes you can see the page which is given below

Servervalidations.aspx:

Design view

5

Servervalidations.aspx.cs

Step3: Now Run the Application by pressing  F5 or ctrl +f5

  1

Step4: Now Click the submit button → then you will see the following output.

2

Step 5:Now , Enter all the fields without fail..

3

Step 6:Click on submit button it redirects you to the welcome page..

4

Thank you for all… To view more tutorials, please visit http://gofaqs.com.

 

 

How to Implement Form Based Authentication In Asp.Net

How to Implement Form Based Authentication In Asp.Net,Form based authentication class resides within “System.web.securityNamespace .  There are two techniques which used to authenticate the user manually by following ways.

  • By the hard code value
  • By the web.config file

By the hard code value:  In this user can verify (authenticate) the web form (login.aspx) by specifying the user name and password from hard code value.

By web.config file:-In this user can authenticate (verify) the web form    (login.aspx page) by specifying the user name and password from web.config file.

Note: We can authenticate the user name and password from database also.

Where we can use this Authentication:

Suppose you have limited employee in your organization (ex.200 employee).if you want to host your asp.net website on server to provide the relevant information to your employee. if you want ,only company ‘s member can access the asp.net website then you will have to generate user name and password manually and save in web.config file or in hard code values. If you want to share secure information on your asp.net website so that only company’s members can access them, then you will have to provide user name and password to each employee whom you have mentioned in web.config file or hard code values. If any employee want to see the information send by the manager of company then they will have to verify your user name and password which is provide by the organization (manager). When any employee open the website then login page (login.aspx)  will be opened first, after authenticate the login page with user name and password employee will be redirected to home page (main page) of the website. After access the application you have to Logout .Otherwise any anonymous user can login as your name with the help of browser cookie (persistence or Non persistence) data. It can be more harmful for an organization (company).
There are some attribute and element which we can use in web.config file (under authentication and authorization section).

  1. Name:-It is an optional attribute. It specifies the HTTPCookie to use for authentication. If you are running multiple application on server then you will be required a unique cookie name in each web.config file for each application.ASPXAUTH is a default name where cookie data is stored.
  2. LoginUrl: – It is a optional attribute that specifies the URL to which the request is redirected for logon. In this application, i have set login.aspx page for logon. If no valid cookie is found for authentication then it will automatically redirected to login.aspx page.
  3. DefaultUrl: – It is an optional attribute .It defines the default URL that is used for redirection after authentication. I have already set defaultUrl = “home.aspx” in my application.
  4. Protection: – It specifies the type of encryption if any to use for cookie. This option usages the configuration data validation algorithm such as DES and Triple DES If it is available.
  5. Path:- It specifies the path cookies that are used by the application. Most of Browsers at this time are case sensitive. If there is a path case mismatch then it doesn’t send cookies back to the application.
  6. RequiredSSL: – It specifies whether an SSL connection is required to transmit the authentication cookie. In my application, i have used requiredSSL =”false”.
  7. Timeout: – It is a time in minute after which the cookie of browser will be expired. By default it is 30 minute.
  8. Sliding Expiration: – It specifies whether sliding Expiration is enabled, sliding Expiration resets the active authentication time for a cookie to expire on each request during single session.
  9. Credentials: – It allows user name and password credentials within configuration file. We can easily create custom user name and password scheme to use an external source for authentication of web page like database.
  10. Authentication: It is a parent element of web.config file. It is used to identify the users who view an asp.net application.

There are some steps to implement this concept on asp.net application.

Step 1:- First open your visual studio–>File –>New –>Website–>Select asp.net Empty website –>OK–>Open solution Explorer –>Add a Web Form named as formauth.aspx–>Drag and drop Label, Text Box and Button control from the tool Box as shown below

Design View:

1

Step 2:– Now add another web form  named as home.aspx in your project–>Drag and drop Button and Label control as shown below:-

7

Web.config:

Note:  Here, i have created some user name and password manually in web.config file. Only these users can be able to authenticate the login.aspx page.
Step 4: Open formauth.aspx page –> Write the following c# codes for each button codes of formauth.aspx.cs as given below

Formauth.aspx.cs

Description:– In button 1 and button 2 clicks,i have written a common function which is given below,

  • RedirectLoginPage Function:-> This function takes two parameter, one is for user name for whom cookie is created and second one is Boolean value to specify whether cookie is persistence or Non Persistence. This function checks the URL of login page,if it return the URL specify in web.config then user will be redirected to that web page and it checks web.config file for default Url .It specify, user is redirected to that web page but it not specify,user will be redirected to default Url page.
  • Password Format Attribute:-> This attribute is used in format ,in which, password value is given in web.config file.If this attribute  value is clear ,it means  password value is store in plane text format.If this attribute  value is  in MD5 or SHA1 ,it means Password is stored in encrypted form By using MD5 or SHA1 . To set the encrypted values of some plane text we can call “HashPasswordForStoringIn ConfigFile” class.it  takes two parameter

1.) value for the text which we want to encrypt
2.) Value for name of algorithm

Example:- If you are using password format MD5 or SH1 then you can use below c# codes

If there are some resources which have to access by all the users then we can specify that tag by using location tag in web.config file.

Note:– Here, Codes on first button click ,we can authenticate only those user which satisfied the if and else if conditions.

Step 5: Now open home.aspx page –>write the c# codes in home.aspx.cs file as given below:-

Home.aspx

Home.aspx.cs

Output: Press Ctrl+F5 or F5  to run the page on server..

1

Step 6:- Now  Filled the required field values  user name and password for hard code value authentication

2

Step7: once you click on Login through hard code button. It redirects to home.aspx and displays below output.

3

Step 8:-  Filled the required field values  user name and password for form authentication–>press Login through Web Config button.

4

Step 8 displays below output.

5

Step 9:- If you save the password in browser cookie –>then you can login without user name and password.But it is harmful ,if any other user access your computer.–>so press Logout Button before exit the application.

Edit Delete operations using repeater data bound control in Asp.Net

The Repeater control is a control which is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. it uses Templates to display data. It does not have any built-in support for editing, sorting, and paging of the data that is rendered through one or more of its templates. The Repeater control works by looping through the records in your data source and then repeating the rendering of one of its templates called the ItemTemplate, one that contains the records that the control needs to render.

To use the Repeater control, you create templates that define the layout of the control’s content. Templates can contain any combination of markup and controls. If no templates are defined, or if none of the templates contain elements, the control does not appear on the page when the application is run.

The following describes the templates that are supported by the Repeater control.

HeaderTemplate: This template is used for elements that you want to render once before your ItemTemplate section. You can say, it displays Header text for a Data Source collection and applies a different style for the Header text.

FooterTemplate: This template is used for elements that you want to render once after you’re ItemTemplate section. You can say, it displays a footer element for the Data Source collection.

ItemTemplate: This template is used for elements that are rendered once per row of data. It is used to display records. You can say, it defines how the each item is rendered from the Data Source collection.

AlternatingItemTemplate: This template is used for elements that are rendered every second row of data. This allows you to alternate background colours. It works on even number of records only.

SeperatorTemplate: It is used for elements to render between each row, such as line breaks. You can say, it will determine the separator element that separates each item in the item collection. It will be a <br /> or <hr /> HTML element.

Because the Repeater control has no default look, you can use it to create many kinds of lists, including the following:

  • A table layout
  • A comma-delimited list

The Repeater control must be bound to a data source. The most common data source is a data source control, such as a SqlDataSource, ObjectDataSource, AccessDataSource, or XmlDataSource control. Alternatively, you can bind a Repeater control to any class that implement the ICollection, IEnumerable, or IListSource interface, which includes the ADO.NET datasets (Dataset class), data readers (SqlDataReader, OleDbDataReader, OdbcDataReader,or OracleDataReader classes), or most collections.

Events Supported by the Repeater Control:

The Repeater control supports several events. One of them, the ItemCreated event, gives you a way to customize the item-creation process at run time. The ItemDataBound event also gives you the ability to customize The ItemCommand event is raised in response to button clicks in individual items. This event is designed to allow you to embed a Button, LinkButton, or ImageButton Web server control in an item template and then be notified when the button is clicked. When a user clicks the button, the event is sent to the button’s container — the Repeater control. The most common uses for the ItemCommand event are to program update and delete behaviours to the Repeater control. Since every button click raises the same ItemCommand event, you can determine which button was clicked by setting each button’s CommandName property to a unique string value. The CommandSource property of the RepeaterCommandEventArgs parameter contains the CommandName property of the button that was clicked.

Here ,I Have Explained how to perform edit and delete operations using repeater control by designing custom lay out in asp.net

Prerequisites for this tutorial:

  • Visual studio(IDE)-2012 ultimate/professional/2013 express/any/2015
  • .Net framework 4.0 above
  • Sql server 2008/08 sp1/12/14

Database :(Sql Server 2008 sp2)

Table Name’s:Department and Employee

1.Department Table

bgv2

2.Employee Table

bgv3

Application:

Step1:Before ,you going to see this tutorial please go through my previous article which creating an example of gridview to display employee data

Step2: Open Visual studio goto→file→open new website or project and click→choose language as c#, select web and click on asp.net empty website (or) Application→save the file in your required directory at below pane→click ok.

Step3: Right click on project name  in solution explorer→select add click→select new item, a new template will open→choose web form named as CRUD_Repeater in right pane and click ok.

Step4: To add Repeater control on page, go to toolbox→find Repeater control → drag and drop on to designer page or source page.

Step5: Go to code behind file … (CRUD_Repeater.aspx.cs)

1 CRUD_Repeater.aspx

 2.CRUD_Repeater.aspx.cs

 Design View:

1

Step6:Add a new webpage named as UpdateEmp.aspx by right clicking on project name→add→web form or Add new item.  2.UpdateEmp.aspx

Design view:

2

3.UpdateEmp.aspx.cs

Output:

Press F5 or CTRL +F5 to run the page in server.

3

1.click on edit button to change Kelvin Department as Banking, it redirects to separate page using employee id with query string. See the below url

http://localhost/gofaq/Updateemp.aspx?eid=2

4

2.now select The department which you want by choosing the listitem displayed in dropdown list

5

3.then ,click on   Update button record will be updated successfully.

6

3.Now click on view employee link displayed above, to see your record updated.

7

…follow the below  link to get more interview questions in asp.net http://www.gofaqs.com/interview-questions/programming/asp-net   and
for previous tutorials http://gofaqs.com/training

Create an example of sending email using Asp.Net

E-mail is one of the most common and reliable methods of communication for both personal and business purposes. It also plays an important role in each and every Web site. This role will be in the type of automated e-mails from the server after posting information from a form. You may have noticed these types of e-mails while registering on a site. As soon as you post the form, the server will send an e-mail asking you to confirm either your registration or with the information you entered. If you have to confirm the registration, the server will send you a long URL that you have to click to proceed further with the registration process. A classic example of this functionality is ASP.NET forums. As soon as you register, you will be e-mailed a random password. You will also get e-mails after your post has been accepted by a moderator or if somebody replies to your post. If you are wondering that this is a server magic—it is not.

To send e-mails, you should require access to a server with .NET Framework and SMTP enabled on it. SMTP stands for Simple Mail Transfer Protocol and e-mails are sent using this protocol.

The .NET Framework supplies a SMTP class that enables you to send a simple e-mail message. If you have to send an e-mail with added functionalities, you have to make use of the MailMessage class. With the help of this class, you can add attachments, set priorities, and much more, very easily. You can also send HTML e-mail using this class.

Fortunately, ASP.NET makes sending email a breeze. The .NET Framework version 1.x included a number of classes in the System.Web.Mail namespace that allowed programmatically sending an email with a few scant lines of code. While this namespace and these classes still exist in the .NET Framework version 2.0, they have been deprecated in favor of new mail-related classes found in the System.Net.Mail namespace.

In order to send an email from an ASP.NET Web page, we need to use the SmtpMail class found in the System.Web.Mail namespace, which contains a static method Send().

In this article I will explain how to send email using Gmail SMTP Server in ASP.Net. To send email with Gmail SMTP Server, you will need to use an email address and password of a valid Gmail account and along with that you will need the Gmail SMTP Mail Server settings.

MailMessage Class Properties

Following are the required properties of the MailMessage class.

From – Sender’s email address

To – Recipient(s) Email Address

CC – Carbon Copies (if any)

BCC – Blind Carbon Copies (if any)

Subject – Subject of the Email

Body – Body of the Email

IsBodyHtml – Specify whether body contains text or HTML mark up.

Attachments – Attachments (if any)

ReplyTo – ReplyTo Email address. 

SMTP Class Properties

Following are the properties of the SMTP class.

Host – SMTP Server URL (Gmail: smtp.gmail.com)

EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True)

UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails

Credentials – Valid login credentials for the SMTP server (Gmail: email address and password)

Port – Port Number of the SMTP server (Gmail: 587)

Prerequisites for this tutorial:

  • Visual studio(IDE)-2012 ultimate/professional/2013 express/any/2015
  • SMPT server configuration in IIS

Application:

Step1: Open Visual studio gotoàfileàopen new website or project and clickàchoose language as c#, select web and click onasp.net empty website (or) Applicationàsave the file in your required directory at below paneàclick ok.

Step2: Right click on project name  in solution exploreràselect add clickàselect new item, a new template will open àchoose web form named as sendemail in right pane and click ok.

Step3: Design User interface as below by using asp.net server controls

Step4: To add controls  on page, go to toolboxàfind required control by type its nameà drag and drop on to designer page or source page.

 Step5:  Go to code behind file … (sendemail.aspx.cs)

  1. sendemail.aspx

Design view :

Press CTRL+F5 or F5 to run the  page on server .

3   2.sendemail.aspx.cs

Output:

Press CTRL+F5 or F5 to run the  page on server .

1.Click on Submit button it validates all fields are required.

4

3.Enter all the fields with out fail.. then click on submit button to send an mail.

54. email was sent successfully..

6

……..follow the below  link to get more interview questions in asp.net http://www.gofaqs.com/interview-questions/programming/asp-net  and
for previous tutorials http://gofaqs.com/training

Create an example of repeater databound control using Asp.Net

The Repeater control is a control which is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. it uses Templates to display data. It does not have any built-in support for editing, sorting, and paging of the data that is rendered through one or more of its templates. The Repeater control works by looping through the records in your data source and then repeating the rendering of one of its templates called the ItemTemplate, one that contains the records that the control needs to render.

To use the Repeater control, you create templates that define the layout of the control’s content. Templates can contain any combination of markup and controls. If no templates are defined, or if none of the templates contain elements, the control does not appear on the page when the application is run.

The following describes the templates that are supported by the Repeater control.

HeaderTemplate: This template is used for elements that you want to render once before your ItemTemplate section. You can say, it displays Header text for a Data Source collection and applies a different style for the Header text.

FooterTemplate: This template is used for elements that you want to render once after you’re ItemTemplate section. You can say, it displays a footer element for the Data Source collection.

ItemTemplate: This template is used for elements that are rendered once per row of data. It is used to display records. You can say, it defines how the each item is rendered from the Data Source collection.

AlternatingItemTemplate: This template is used for elements that are rendered every second row of data. This allows you to alternate background colours. It works on even number of records only.

SeperatorTemplate: It is used for elements to render between each row, such as line breaks. You can say, it will determine the separator element that separates each item in the item collection. It will be a <br /> or <hr /> HTML element.

Because the Repeater control has no default look, you can use it to create many kinds of lists, including the following:

  • A table layout
  • A comma-delimited list

The Repeater control has a DataSource property that is used to set the DataSource of this control to any ICollection, IEnumerable, or IListSource instance. Once this is set, the data from one of these types of data sources can be easily bound to the Repeater control using its DataBind () method.

Or you can say:

The Repeater control must be bound to a data source. The most common data source is a data source control, such as a SqlDataSource, ObjectDataSource, AccessDataSource, or XmlDataSource control. Alternatively, you can bind a Repeater control to any class that implement the ICollection, IEnumerable, or IListSource interface, which includes the ADO.NET datasets (Dataset class), data readers (SqlDataReader, OleDbDataReader, OdbcDataReader,or OracleDataReader classes), or most collections.

Events Supported by the Repeater Control:

The Repeater control supports several events. One of them, the ItemCreated event, gives you a way to customize the item-creation process at run time. The ItemDataBound event also gives you the ability to customize The ItemCommand event is raised in response to button clicks in individual items. This event is designed to allow you to embed a Button, LinkButton, or ImageButton Web server control in an item template and then be notified when the button is clicked. When a user clicks the button, the event is sent to the button’s container — the Repeater control. The most common uses for the ItemCommand event are to program update and delete behaviours to the Repeater control. Since every button click raises the same ItemCommand event, you can determine which button was clicked by setting each button’s CommandName property to a unique string value. The CommandSource property of the RepeaterCommandEventArgs parameter contains the CommandName property of the button that was clicked.

Prerequisites for this tutorial:

  • Visual studio(IDE)-2012 ultimate/professional/2013 express/any/2015
  • .Net framework 4.0 above
  • Sql server 2008/08 sp1/12/14

Database:

Table Name:Comment

Table structure:

4  Table Data:

5

Application:

Step1: Open Visual studio gotoàfileàopen new website or project and clickàchoose language as c#, select web and click onasp.net empty website (or) Applicationàsave the file in your required directory at below paneàclick ok.

Step2: Right click on project name  in solution exploreràselect add clickàselect new item, a new template will open àchoose web form named as Repeater  in right pane and click ok.

Step3: Add Repeater control on page, to add, go to toolboxàfind required control by typing its nameà drag and drop on to designer page or source page.

 Step4:  Go to code behind file … (Repeater.aspx.cs)

 Repeater.aspx

Repeater.aspx.cs

 Output:

1.Press CTRL+F5 or F5 to run the  page on server .

1

2.Enter all the fields .. then click on submit button to comment.

2

  1. Comment submitted successfully..

3

…follow the below  link to get more interview questions in asp.net  http://www.gofaqs.com/interview-questions/programming/asp-net  and
for previous tutorials http://gofaqs.com/training

How to Implement Caching Techniques in Asp.Net

How to Implement Caching Techniques in Asp.Net ,Caching is very important concept for any web application. Which is used to store the data temporarily either on a web server or on the client side (client system).In other words, Caching is a place where data is stored temporarily. This data can be stored for a specific time period on the server or client system. It is more useful when any user access the same set of data continuously.

 For Real Example:

Almost every user access the Search    Engine (Google, Yahoo, Mozilla etc.) for searching relevant information. Suppose if you open Google page on your system first time then first time Google page comes from Google Database. If you open again Google search engine then this Google page comes from Google server cache or client system Cache memory. You already know about the cache memory concepts. Sometimes you have seen, when your internet connection is disconnected, when you open the Google then it open without connection. What is the reason about that, when you open Google page multiple times in your system then this page is saved in our system cache memory for a specific time period. So that it is opened without internet connection. This rule is applicable for all cache enable web applications. Cache is the best way to improve the performance of any web application.
Accessing a database in an Asp.Net applications generally a slow and time consuming process.To improve the performance of asp.net page, we can use Caching concept. This is quicker than retrieving the data from the database on each request.

Advantage of Caching:

  • Reduce the processing Time
  • Reduce the Network Traffic
  • Improve the Performance of web application
  • Enhance the user Experience
  • Lower Data used (Internet)
  • Improve the site performance
  • Large data management

Caching in asp.net application:

Cache is a place where data is stored for a specific time period (temporarily). An application written is ASP.NET is faster than the application written in ASP (Active server page), in terms of retrieving data from a database. In ASP caching technique we can cache data in two level variables to speed up its retrieval.

  1. Application level
  2. Session level

But in large scale web application. Data Retrieval at both levels is insufficient. In asp.net application, there are number of classes in .NET Framework that deal the issues related to caching of data.
Suppose if you are not using caching concepts on your web application then what will be happened, suppose your application needs to query from database every two seconds that contains millions of records and your database is updated after half an hour’s However, querying the database after every two seconds increase the Network Traffic every second and reduce the performance of the application.
How to solve above problem:
When any user access the database records, then save that records in cache memory for a specific time period. If all records are saved in cache memory for a specific time periods then millions of users can access the records from cache memory not database. When database is updated after 30 minutes or one hour (a time periods) then saved the updated records also in cache memory. When we use these concepts then Network Traffic will be reduced and web application performance also improved.
Real Life Example:- 
Many times you will have to seen, When you retrieve balance slip after withdrawing the money from ATM Machine then you find, your balance remain same as before (not deducted).What is the reason about that, Your deducted balance is saved in cache memory of the bank’s server. After a specific time period when database is updated, then you will receive balance deduction sms on your registered mobile Number. Means when database will update then write operation performed from cache to database. Google and other top most website also use these concepts on your web applications. You already know, why Google server is not busy, because it uses more power full caching concepts and others things also.
This single concept reduces the load and processing time on the database server as well as improves the site performance of the web application.
There can be implemented three level of caching concepts in ASP.NET application which are given below:-

  • Page Output Caching
  • Fragment Caching (partial page Caching)
  • Data Caching

Page Output Caching:         

In this type of caching the Entire web page (HTML page) cached within memory by specifying output Cache @Directive.
In this Caching technique page output and HTTP response stored in an memory cache (Random Access Memory) of the computer. In ASP.NET 4.0, you can create more than one custom Output Cache provider also.
System.web.caching.OutputCacheprovider; Class is used to create custom output cache provider which can be registered within the web.config file. This caching concept is more useful for static web page(page whose content does not change).In this caching data can be stored on different-2 location such as client side, server side or proxy side.
We can easily implement the page output caching by adding the @output cache Directive as shown below:-
<%@OutputCache Duration = “30” VaryByParam =”none” %>
We can define the location such as server side, client side or proxy side as given below:

<%@OutputCache Duration = “50” Location= “Any/Client/Downstream/Server/None” VaryByParam =”none” %>

Some Important Attributes supported by the @OutputCache Directive

Cache Profile → It is an optional attribute. It  contains the setting of the cache to associate with a web page.
Duration→It is used to define the time duration of web page to be cached.
Location It is used to define the location where the cache is created.
SqlDependency → It contains a string value that identifies a set of database and table name.  

VaryByControl →It contains a semicolon-separated list of strings. These strings represent ID Property values of ASP.NET, Server controls declared in user control.

VaryByCustom →It is used to define the custom strings for custom output caching.

VaryByHeader It is used to define a semicolon-separated list of Http Headers.

VaryByParam It is used to define the semicolon-separated lists of strings, which the output cache uses to identify the cache entry.
The Locate Attribute:
There are some elements of locate attribute which are given below:-
Any→ it specifies that output cache can be located anywhere such as on the client’s browser, server or proxy server.
Client → It specifies that the output cache is only located on the client browser.
Downstream → it specifies that the output cache is stored in any HTTP 1.1 cache  capable devices or other proxy server or originating server.
None → it specifies, disables the output cache of the requested page.

Server→ It specifies that the output cache is located on the web server only.
Server and Client  → It specify that the output cache is stored on the web server and on the client browser.

The VaryByCustom Attribute:
The VaryByCustom attribute is used custom strings according to the requirements of a user.
Ex. If we want to cache different types of contents for different browsers such as

  • Image for Internet Explorer
  • Text for Google chrome
  • Video for Mozilla Firefox

Then we have to VaryByCustom attribute. If we want to implement a custom logic then we must override the HttpApplication. GetVaryByCustomStrings Method in our web application’s Globasl.asax.

The VaryByParam Attribute:
The VaryByParam attribute is used to cache different copies of a web page, when the web page is changed dynamically, based on the parameters received in the form of HTTP Post or HTTP GET.
Why we use VaryByParam attribute:
For Example ,Suppose we want to received the student records on the basis of student Id 13 and the VaryByParam attribute set to its default value “None”. In this case student Id 13 records saved in cache memory. Suppose another person want to received the records of student Id 20,In this case cache engine unable to differentiate between the two request (id 13 ,id 20) and sends the cached output student Id 13 records to the person. To overcome this problem we use the VaryByParam attribute and specify the cache engine should vary its cache data on the basis of the student Id at the top of the web page.
Meanings of below Directives:
<%@OutputCache Duration = “30” VaryByParam =”none” %>

Once the page is process from the server, the process page kept in the memory within 30 seconds after that this page removed from cache memory and again it will be process from server property.
There are some techniques to implement the page output caching in asp.net application.
1.Page Output caching Depends on some control values.
   2.Page Output caching Depends on query string key value.
Example:
There are some steps to implement this page output caching concept in asp.net applications.
Step 1 : First open your visual studio→FileNew→website→Select ASP.NET Empty website→OK→Open solution Explorer →Add New web Form (caching.aspx)→Drag and drop Label, Textbox, Button and Gridview control on the form(caching.aspx) from Toolbox as shown below,

5

Step 2: Now goto sql server create a Product table with three columns and insert some values as shown below

Table structure:

2

Step 3: caching.aspx 

Step 4: caching.aspx.cs

Step 5 :  now run the page by press ctrl+f5 or f5

3Here we are not yet cache any value.

Step 6:  Enter Product Id in textbox which will be cache the values.

4

Note:This above page is saved in cache memory for 30 seconds.

…follow the below  link to get more interview questions in  asp.net http://www.gofaqs.com/interview-questions/programming/asp-net and for tutorials http://gofaqs.com/training

How to maintain session in Inproc mode using asp.net

Introduction:

How to maintain session in asp.net, HTTP is a stateless protocol. Actually statelessness is one of the many advantages of the World Wide Web. In a statelessness condition all information associated with the page and the controls on the page would be lost with each round trip. Round trip means a request from a user to Web Server and response from Web server to user. There is no standard way in which the server can determine whether a subsequent HTTP request is from the same user. To overcome this limitation of traditional Web programming, ASP.NET includes several features that help you preserve data on both a per-page basis and an application-wide basis by its State Management Capabilities. ASP.NET provides various options for state management such as Client-Based State Management Options and Server-Based State Management Options.

Here I explained about session management, session is one of the server side state management techniques.

Session is one of the most common ways which is being used by developers to maintain the state of the application. The Session basically stores the values as a dictionary collection in key/value pairs. It completely utilizes server resources to store the data. It is a secure way of storing data, since the data will never be passed to the client. For each and every user, a separate Session is created, and each and every Session has its Unique ID. This ID is being stored in the client’s machine using cookies. If there are multiple users who are accessing a web application, then for each user a separate Session is created. If a single user logs in and logs out the Session is killed, then if the same user again logs into the application, then a new Session ID is being created for the same user. The Session has a default timeout value (20 minutes). We can also set the timeout value for a session in the web.config file.

Session Variables:

Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name of a user, and set them to values retrieved from TextBox controls. Session [“FirstName”] = txtFirstName.Text; Session[“LastName”] = txtLastName.Text; Note: When you use a session-state mode other than InProc, the session-variable type must be either a primitive .NET type or serializable. This is because the session-variable value is stored in an external data store.

Session Identifiers:

Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response. By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a “cookieless” session. A session is considered active as long as requests continue to be made with the same SessionID value. If the time between requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session.

Security Note:

SessionID values are sent in clear text, whether as a cookie or as part of the URL. A malicious user could get access to the session of another user by obtaining the SessionID value and including it in requests to the server. If you are storing sensitive information in session state, it is recommended that you use SSL to encrypt any communication between the browser and server that includes the SessionID value.

Cookie less SessionIDs:

By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the <SessionState> section of the Web.config file.

The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers.

Web Configuration:

ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page’s URL.

For example, the following URL has been modified by ASP.NET to include the unique session ID u1daopo5vmuwl55yenibg1zl: http://localhost/WebSiteHttp1/(S(u1daopo5vmuwl55yenibg1zl))/ViewEmp.aspx

When ASP.NET sends a page to the browser. It modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that case, a new session is started for the request.

The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier. This enables ASP.NET to resolve the application name before involving the SessionStateModule in the request.

 Note: To improve the security of your application, you should allow users to log out of your application, at which point the application should call the Abandon () method. This reduces the potential for a malicious user to get the unique identifier in the URL and use it to retrieve private user data stored in the session.

Regenerating Expired Session Identifiers:

By default, the session ID values that are used in cookieless sessions are recycled. That is, if a request is made with a session ID that has expired, a new session is started by using the SessionID value that is supplied with the request. This can result in a session unintentionally being shared when a link that contains a cookieless SessionID value is used by multiple browsers. (This can occur if the link is passed through a search engine, through an e-mail message, or through another program.) You can reduce the chance of session data being shared by configuring the application not to recycle session identifiers. To do this, set the regenerateExpiredSessionId attribute of the configuration element to true. This generates a new session ID when a cookieless session request is made with an expired session ID.

Note: If the request that is made with the expired session ID is made by using the HTTP POST method, any posted data will be lost when regenerateExpiredSessionId is true. This is because ASP.NET performs a redirect to make sure that the browser has the new session identifier in the URL.

Session-State Modes:

ASP.NET session state supports several storage options for session variables. Each option is identified by a value in the SessionStateMode enumeration. The default behaviour is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a custom data source. If you do not want session state enabled for your application, you can set the session mode to off.

There are four session storage mechanisms provided by ASP.NET:

InProc mode, which stores session state in memory on the Web server. This is the default. It offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use StateServer or SQLServer.

StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications. However, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the start-up type to Automatic.

 SQLServer mode, stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web form.

 Custom mode, which enables you to specify a custom storage provider. You also need to implement the custom storage provider.

Off mode, this disables session state. You should disable session state if you are not using it to improve performance.

Configuring Session State:

Session state is configured by using the <sessionState> element of the<System.Web> configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive. The <sessionState> element enables you to specify the following options:

  • The mode in which the session will store data.
  • The way in which session identifier values are sent between the client and the server.
  • The session Timeout value.
  • Supporting values that are based on the session Mode setting.

The following example shows a sessionState element that configures an application for any of the session mode.

Configuration Setting:

The settings above are used to configure ASP.NET session state. Let’s look at each in more detail and cover the various uses afterward.

  • Mode. The mode setting supports three options: inproc, sqlserver, and stateserver. As stated earlier, ASP.NET supports two modes: in process and out of process. There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We’ll discuss implementing these options shortly.
  • Cookieless. The cookieless option for ASP.NET is configured with this simple Boolean setting.
  • Timeout. This option controls the length of time a session is considered valid. The session timeout is a sliding value; on each request the timeout period is set to the current time plus the timeout value.
  • Sqlconnectionstring. The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver.
  • Server. In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState.
  • Port. The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver.

You can disable session state for an application by setting the session-state mode to Off. If you want to disable session state for only a particular page of an application, you can set the EnableSessionState value in the @ Page directive to false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables. Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability

  • In process mode (in-memory)- State information is stored in memory of web server
  • Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
  • Database mode as session state is maintained on a SQL Server database.

InProc session state mode:

InProc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server’s memory inside the asp.net worker process. If there are more than one IIS servers then session values are stored in each server separately on which request has been made. Since the session values are stored in server, whenever server (asp.net worker process) is restarted the session values will be lost. It is the only mode that supports the Session_End event.

Configuration:

 

Advantages of InProc session state mode:

  • Very easy to implement. All that is required is, to set, the session state mode=”InProc” in config file.
  • Will perform best because the session state memory is kept on the webserver, within the ASP.NET worker process (aspnet_wp.exe).
  • Suitable for web applications hosted on a single server.
  • Objects can be added without serialization.

 Dis-advantages of InProc session state mode:

  • Session state data is lost, when the worker process or application pool is recycled.
  • Not suitable for web farms and web gardens.
  • Scalability could be an issue.

Sample session state application
before we use session state, we need an application to test it with. Below is the code for a simple C# application that writes to and reads from session state,

Session.aspx

Output:

Step1:Press ctrl+F5 or f5 ,To run the page on server

Step2: Enter the  text in  name filed.

2

Step3: Now, click on add to session state button it will maintain a session for name filed.

3

Step4: To see the session click on view sessionsate button ,it will returns your value until session default timeout end .

4

Step5:Now, click on remove session state button it will call the Abandon() Method of Session and clears the session .To check, click on view session state button it will show the below message

5

…follow the below  link to get more interview questions in asp.net http://www.gofaqs.com/interview-questions/programming/asp-net and for previous tutorials http://gofaqs.com/training

Grid View Control to insert employee data

Grid View Control to insert employee data – The Template Field class is used by data-bound controls (such as Grid View and Details View) to display custom content for each record displayed.  When you need to display content in a data-bound control that is not provided by one of the predefined data control fields (such as Bound Field).

You can hide a Template Field object in a data-bound control by setting the visible property to false. As an alternative to defining a custom Header Template or Footer Template, you can customize the header and footer sections of a Template Field object by setting other properties of the Template Field object. To display a caption in the header or footer sections, set the Header Text or the Footer Text property, respectively. Instead of displaying text in the header section, you can display an image by setting the HeaderImageUrl property. The header section can be hidden in the Template Field object by setting the Show Header property to false.

Here, I Explained step-by-step how to do insert Operations using Columns as Template Fields in a Grid View.

Prerequisites for this tutorial:

  • Visual studio(IDE)-2012 ultimate/professional/2013 express/any/2015
  • SQl server 2008 sp2/14/12

Database :(Sql Server 2008 sp2)

Table structures:

1.Department Table:

grid control

2.Employee Table:

grid view control image

Application:

Step1: Before ,you going to see this tutorial please go through my previous article which creating an example of gridview to display employee data

Step2: Open Visual studio go to → file → open new website or project and click → choose language as c#, select web and click on asp.net empty website (or) Application → save the file in your required directory at below pane →click OK.

Step3: Right click on project name  in solution explorer → select add click → select new item, a new template will open → choose web form named as Insertdata in right pane and click OK.

Step4: To add Gird view on page, go to toolbox → find Grid view → drag and drop on to designer page or source page.

Step5: Go to code behind file … (Insertdata.aspx.cs)

1.Insertdata.aspx

  1. Insertdata.aspx.cs: