European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET 4.5 Hosting - Amsterdam :: Using ASP.NET 4.5 to Upload Multiple Files

clock November 23, 2012 05:20 by author Scott

In versions of ASP.NET before 4.5 there was no direct way to enable a user to upload multiple files at once. The FileUpload control only supported a single file at the time. Common solutions to uploading multiple files were to use a server-side control such as those from Telerik or DevExpress or to use a client-side solution using a jQuery plugin for example. In the latter case, you would access Request.Files to get at the uploaded files, rather than retrieving them form a FileUpload control directly. Fortunately, in ASP.NET 4.5 uploading multiple files is now really easy.

The FileUpload Control with HTML5 Support

The FileUpload control has been enhanced in ASP.NET to support the HTML5 multiple attribute on an input with its type set to file. The server control has been expanded with an AllowMultiple attribute that renders the necessary HTML5 attribute. In addition, the control now has properties such as HasFiles and PostedFiles that enable you to work with a collection of uploaded files, rather than with just a single file as was the case with previous versions of the control.

All you need to do to enable multiple file uploads is set the AllowMultiple property of the FileUpload control to true:

<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />

In the browser, this renders the following HTML:

<input type="file" multiple="multiple" name="FileUpload1" id="FileUpload1" />

Notice how the multiple="multiple" attribute tells the browser to enable support for multiple files. Each browser that supports this feature uses a slight different interface. For example, in Chrome it looks like this:

while in Opera it looks like this:

All major browsers (Firefox, Chrome, Opera and Safari) except Internet Explorer 9 support this feature. IE 10 will support uploading multiple files as well, so hopefully this limitation is soon a thing of the past. While Safari seems to officially support this feature, I couldn't make the example work with multiple files. This could be a bug in Safari.

Working with the uploaded files at the server is similar to how you used to work with the control, except that you now work with a collection of files, rather than with a single instance. The following code snippet demonstrates how to save the uploaded files to disk and assign their names to a simple Label control, reporting back to the user which files were uploaded:

protected void Upload_Click(object sender, EventArgs e)
{
  if (FileUpload1.HasFiles)
  {
    string rootPath = Server.MapPath("~/App_Data/");
    foreach (HttpPostedFile file in FileUpload1.PostedFiles)
    {
      file.SaveAs(Path.Combine(rootPath, file.FileName));
      Label1.Text += String.Format("{0}<br />", file.FileName);
    }
  }
}

With this code, each uploaded file is saved in the App_Data folder in the root of the web site. Notice that this is just a simple example, and you would still need to write code you normally would to prevent existing files from being overwritten, and to block specific files types from being uploaded.

 



Premier European HostForLIFE.eu Officially Announces SharePoint 2013 Hosting in European Data Center

clock November 21, 2012 07:46 by author Scott

HostForLIFE.eu, the premier European Windows and ASP.NET provider proudly announces the immediate availability of Microsoft’s new SharePoint 2013 hosting. HostForLIFE.eu offers this new product at the amazing price, just only €9.99/month.

“SharePoint 2013 is really fantastic; it brings many exciting new features, like Microsoft App Store, SharePoint Designer 2013 support, the use of mobile smart devices. And what amazing here is you can find all this new functionality for only €9.99/month” Said Kevin Joseph, manager of HostForLIFE.eu. “These enhancements are fantastic and make the platform more user-friendly, scalable, modern, and powerful as a robust collaboration, social, and knowledge management platform for the enterprise.”

HostForLIFE.eu utilizes the newly-released Microsoft Windows Server 2012 and SQL Server 2012 as the foundation for the plans. The base hosting plans specification have been architected to meet Microsoft recommended configurations for both SharePoint 2013 and SQL Server 2012 and will include SQL Server and disk configuration best practices identified by HostForLife’s database administrators to optimize SharePoint 2013 performance.

The HostForLIFE.eu SharePoint 2013 product is divided into SharePoint Foundation 2013 and SharePoint Server 2013 hosting plan. SharePoint 2013 Foundation is the core platform of the product which comes with enhancements to the administration and user experience, plus new options for enterprise users to collaborate using social media features. SharePoint Server 2013 is basically Foundation with additional Enterprise services and functionality added on top. You will still get Central administration, basic search, document collaboration, and team sites with Foundation.

For additional information about SharePoint 2013 offered by HostForLIFE.eu, please visit http://www.hostforlife.eu.

About HostForLIFE.eu:

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.



European Visual Studio LightSwitch Hosting - Amsterdam :: How to Manage Users and Roles Using LightSwitch

clock November 6, 2012 06:14 by author Scott

This article presents how you can use an existing users database with a LightSwitch application. I found a sample about linking the current application users to another table but no sample about using an existing users database in a LightSwitch application. This article presents this process step by step.

Here is the steps:


1. Creating the Users Database


LightSwitch applications use the same database tables for security that are used by all the other .NET applications. Since I do not have an existing users database, I will create one here.


As we all know, in order to add the
aspnet_* database tables and stored procedures to an existing database, we can use the aspnet_regsql.exe tool. After we have created the database by using SQL Server Management Studio, we can run the following command in order to add our tables.



In the image above, you can see that we are adding the membership, role and profile tables to the
LSTestDB database. These are the tables that are used by the LightSwitch application. After this command is run, we have the specified tables in our database. This can be seen in the image below:



LightSwitch uses an additional table. This table is named
RolePermissions and it is used to hold all the permissions assigned to the roles. The image below presents the table structure:



We do not need to add this table to our database. The permissions will be held in the LightSwitch application database (that uses the
_IntrinsicData connection string)

At this point, the database is ready to go.


2. Creating the LightSwitch Application


The next step is to create the LightSwitch application. For this, we just follow the new project wizard. After the project is opened, we need to set up the application to use Forms Authentication. This can be done from the Access Control tab in the Properties window. This can be seen in the image below:




As you can see from the image above, I have granted the Security Administration permission for debug. This will allow us to access the corresponding screens in the UI. We can run the app now to see that everything is ok. The image below presents the application:




Remember not to add any users as this will add the users to the LightSwitch database.


3. Modifying the LightSwitch Application to Connect to the Existing Users Database


Now comes the interesting part. We will modify some of the LightSwitch generated files in order to connect to our users database. In particular, we will modify the generated web.config file. This file can be found in the
ServerGenerated project. This is one of the projects that got generated when we created our application project. In order to get to the web.config file, we need to switch from Logical View to File View as in the image below:



We than need to click
Show All Files and open the web.config file from the ServerGenerated project.

In this file, we can see a number of interesting things:


- A connection string has been added that points to the default data source and its name is
_IntrinsicData.
- The membership, role and profile providers are set up and use the _IntrinsicData connection string.

We need to do two things in order to make the application use our users database:


- Add a new connection string to our users database. Make the providers use our connection string instead of
_IntrinsicData.

We will add the following connection string to the web.config file:

<add name="myDB" connectionString="Data Source=.\sqlexpress;

         Initial Catalog=LSTestDB;Integrated Security=True;
         Connect Timeout=30;MultipleActiveResultSets=True" />

This connection string is very similar to the generated one except that the User Instance property is not set. All that is left now is to point the providers to use our connection string. In case the users already exist in the database, we also need to set the applicationName in the providers to the application from which we want to access the users.

This is it. The first thing we need to do to start testing our work is to add some random permission like in the image below:




After this, we can start our application and add a test user and role. This can be seen in the images below. Our custom permission is also added to the role.






The last thing we need to do is to check our database to see if the data has been added. The image below presents the results.




From the image above, you can see that the user and role were indeed added.

 



European Visual Studio 2012 Hosting - Amsterdam :: How to Use IntelliTrace in Visual Studio 2012

clock October 22, 2012 10:43 by author Scott

IntelliTrace can be used to collect and analyze the data in production. IntelliTrace speeds debugging by showing history of what happened in your application while you run. This reduces how often you restart the application when you want look at past events. IntelliTrace automatically collects information about events when you start debugging. Some examples of events exceptions, break points and dot net events. You can also use IntelliTrace for calls information.

Configuring IntelliTrace in VS 2012

To turn on IntelliTrace Collection, Open Visual Studio Tools Menu then click options then tick mark the Enable IntelliTrace check box




You can select IntelliTrace Events and choose the events and event categories that you want to collect. You can examine the values for variables , inputs and outputs for functions and procedures. Selecting an event takes you to the code where that event happened.



You can then use the standard debugging windows to review the application state and examine the collected value. You can collect and save this information to a file.



This file contains the information about exceptions, web requests, test steps and other appropriate data. This file helps you to debug your application after crash and identify how to reproduce bugs.

Collecting the information from Applications in Production

You can use stand-alone collector to get IntelliTrace information about applications that are in production. You can use Power-Shell commands to collect the data and delete the collector when you are done. You can download this tool from here



IntelliTrace collects the information with-out interrupting applications operations data. You can now open the file in Visual Studio 2012 , if the application is web then you can select the specific web request and see the details as shown below



After selecting a particular web request then you will get all the associated events to that request , You can select a specific event and choose start debugging



Visual Studio takes you to the code where the event happened , Now you can use standard VS debugging experience with IntelliTrace to examine the collected values. You can definitely save debugging time using IntelliTrace by using applications history and state without restarting. It provides more debugging information and capabilities to find and fix bugs faster.

API reference for extensibility can found here

 



European ASP.NET 4.5 Hosting - Amsterdam :: How to Create ASP.NET Permanent User Login

clock October 16, 2012 08:48 by author Scott

Introduction

This article describes how to create a permanent user login session in ASP.NET. The sample code includes an ASP.NET MVC4 project to control the user registration and login process. But you can use this technique in any type of ASP.NET project.

Forms Authentication


Before getting into the depth of this article, you must be familiar with forms authentication in ASP.NET. The configuration of form authentication resides in web.config file which has the following configuration-file fragment with the assigned values.


<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn"
             protection="All"
             timeout="1"
             name=".USERLOGINCONTROLAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="~/Home/Index"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false"/></authentication>

The default values are described below:

-
loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.

-
protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.

-
timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.

-
name and path are set to the values defined in the application's configuration file.

-
requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.

-
slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.

-
defaultUrl is set to the Default.aspx page for the application.

-
cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.

-
enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

FormsAuthentication.SetAuthCookie Method

This method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication. The first overload of this function has two parameters:


-
userName: The name of the authenticated user

-
createPersisntentCookie: True to create a persistent cookie (one that is saved across browser sessions); otherwise, false.

This method add a cookie or persistent cookie to the browser with an expire time set in "timeOut" parameter with the name and path set in "name" and "path" parameter. The user will be automatically logged out once the cookie is expired. So the user login session depends on the expire of forms authentication ticket saved in browser cookie. Here, I will create a permanent user login session using this technique.

Cookie Helper

The functionality of this class is to add a form authentication ticket to the browser cookie collection with a life time expiry.


public sealed class CookieHelper
{
    private HttpRequestBase _request;
    private HttpResponseBase _response;

    public CookieHelper(HttpRequestBase request,
      HttpResponseBase response)
      {
            _request = request;
            _response = response;
      }

    //[DebuggerStepThrough()]
    public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
    {
        if (_response != null)
        {
            if (isPermanentCookie)
            {
                FormsAuthenticationTicket userAuthTicket =
                  new FormsAuthenticationTicket(1, userName, DateTime.Now,
                  DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
                string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
                HttpCookie userAuthCookie = new HttpCookie
                  (FormsAuthentication.FormsCookieName, encUserAuthTicket);
                if (userAuthTicket.IsPersistent) userAuthCookie.Expires =
                                    userAuthTicket.Expiration;
                userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
                _response.Cookies.Add(userAuthCookie);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
            }
        }
    }
}

This function is used in login page or control on the click of login button. In the attached sample project, the following function is written in AccountController class. This function validates the login of the user and then add a permanent form authentication ticket to the browser.

private bool Login(string userName, string password,bool rememberMe)
{
    if (Membership.ValidateUser(userName, password))
    {
        CookieHelper newCookieHelper =
            new CookieHelper(HttpContext.Request,HttpContext.Response);
        newCookieHelper.SetLoginCookie(userName, password, rememberMe);
        return true;
    }
    else
    {
        return false;
    }
}

 



European ASP.NET Hosting - Amsterdam :: jQuery and Clicking an ASP.NET Linkbutton

clock October 11, 2012 08:15 by author Scott

As a web developer one common request is to make sure that the interfaces we build out for users look the best that they can and also provide users with the best experience both via the keyboard and mouse. As part of this we will often have areas of conflict. This post is going to cover one common scenario that will impact users that might be using DotNetNuke common styles or working to create their own custom button styles. With ASP.NET it is common for people to use "LinkButton" controls to trigger actions rather than your standard "Button" controls as they are easier to style.

There is nothing wrong with this until you try to perform actions against the 'LinkButton' and it doesn't function as you would expect. For this purposes of this post lets say we are building a custom login form that has two textboxes; txtUsername and txtPassword and a single LinkButton btnLogin. We want to ensure that if the user presses enter on either of the textboxes that they are logged in.


Using standard jQuery we would try something like this:


   1:  $("#<%=txtPassword.ClientID %>").keydown(function(event) {
   2:      if (event.keyCode == 13) {
   3:          $("#<%=btnLogin.ClientID %>").click();
   4:      }
   5:  });


This is a pretty standard jQuery method to listen for the enter key and simply "click" the button. However, if you are using a LinkButton this code will not work. The reason for this is that a LinkButton is rendered to the browser as an Anchor tag with a href property that contains a javascript action to trigger the postback. Click does nothing on the button as there is nothing for it to complete.


To get around this you need to actually look into the generated anchor tag, grab the href value and evaluate it. Similar to the following:


   1:  $("#<%=txtPassword.ClientID %>").keydown(function(event) {
   2:      if (event.keyCode == 13) {
   3:          eval($("#<%=btnLogin.ClientID %>").attr('href'));
   4:      }
   5:  });


Using this structure the postback will be triggered and the user will be logged in as you expect them. This works great for any linkbutton, including those styled with the default DotNetNuke 6.x form pattern styles.

 



HostForLIFE.eu now supports Windows Server 2012 Hosting Platform in European Data Center

clock October 1, 2012 08:04 by author Scott

Microsoft has just officially released the highly anticipated Windows Server 2012. The newly released server operating system offers a number of features that can be utilized to benefit developers, resellers and businesses. As a premier European Windows and ASP.NET hosting provider that follow the developments of Microsoft products, HostForLIFE.eu proudly announces the support of Windows Server 2012 Hosting Platform in the world-class Amsterdam (The Netherlands) data center.

“We know that our customers are always looking for new technologies and the latest Microsoft product. With the launch of Windows Server 2012, we believe that anyone can take advantage of all the improvements available in this platform”, said Manager of HostForLIFE.eu, Kevin Joseph. “The focus on high availability, scalability, and virtualization has made this one of the most important releases of Windows Server to date. We have been working closely with Microsoft throughout the pre-release development cycle of the platform to both drive the direction of the product and ensure our team is ready to support Server 2012 solutions. We couldn’t be more excited and confident in the solutions now available to our clients with Windows Server 2012.”


With our Windows Server 2012 Hosting Platform, customers have an access directly to all the newest technologies and frameworks, such as ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, Silverlight 5 Hosting, WebMatrix Hosting, Visual Studio Lightswitch Hosting and SQL 2012 Hosting. All these technologies/frameworks are integrated properly on our world-class Control Panel. The package is offered from just €2.45/month and we believe that this is the most affordable, features-rich Windows and ASP.NET Hosting package in European market.


HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see
http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.

For more information about our service, please visit
http://www.hostforlife.eu.

About HostForLIFE.eu:


HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.


Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET 4 Hosting - Amsterdam :: How to Fix ValidateRequest="false" in ASP.NET 4

clock September 27, 2012 06:03 by author Scott

If you are someone like me who have recently upgrade to ASP.NET 4.0, you may have come across Yellow Screen of Death with Http Request Validation Exception, something like:

“A potentially dangerous Request.Form value was detected from the client”

Exception Details
: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client

Surprisingly, you will still see this exception even if you have set ValidateRequest to false in either the Page Tag or Web.Config.


ValidateRequest="false" or  <pages validateRequest="false" />


This may end you being freak out identifying the problem.


The solution is perhaps very simple. I would recommend to go and read
ASP.NET 4 Breaking Changes.

“In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.and therefore request validation errors might now occur for requests that previously did not trigger errors.”


In order to revert to the behavior we had previously, you need to add the following setting in Web.config file:


<httpRuntime requestValidationMode="2.0"/>


And this should work!


Hope this helps!

 



European Visual Studio 2012 Hosting - Amsterdam :: What is New in Visual Studio 2012 RC

clock September 18, 2012 09:13 by author Scott

Let's start with the new functionalities introduced in Visual Studio 2012 RC.

Recent Project List


Though this was available in earlier versions of Visual Studio, the option to remove a project from the list is now not available; you can remove unwanted projects from the "Recent" list by selecting the "Remove From List" option. (Right-click on the project you want to remove from the list then select "Remove From List".)


You can even see the latest Visual Studio GUI in the following screen shot:


Visual Studio Dark Theme

I have seen so many developers that don't like the default Visual Studio GUI color and they prefer to code using a dark background. Most of them go to Tools-> Options and change the default color and fonts.

But now you can do this by just changing the Visual Experience. Select Tools -> Options then click on "General" from the "Environment" section. You have the option to select "Dark" or "Light". This is really cool stuff. You can even download themes online.






Visual Studio Installation Engine Improvement

The Visual Studio 2012 installation has become very user-friendly compared to previous versions of Visual Studio. You can save almost 25% of installation time and save about 2.5 GB of space. There is significant improvement in the installation engine.


Other Features

Metro Style Application Development

This is the greatest feature and only available for the Window 8 operating system. To develop a Metro style application, you need to download and install the Windows 8 Release Preview Evaluation copy which is freely available on the Microsoft site. Once you install the Window 8 Release Preview, install Visual Studio 2012 RC.


Select File -> New -> Project which will open the "New Project" window. Select Visual C# or Visual Basic from the Template (my favorite is Visual C#) and go to "Windows Metro style".


Here you have the options to select the kind of Metro style application you want to develop.


(Note: Metro style applications are only available for .Net Framework 4.0 and .Net Framework 4.5.)


 



Europe ASP.NET 4.5 Hosting - Amsterdam :: Using Model Binding in ASP.NET Data Controls

clock September 6, 2012 09:12 by author Scott

Introduction

ASP.NET Web Forms became popular due to the wide range of data bound controls such as GridView, DetailsView and ListView. The earlier versions of ASP.NET, however, were a bit rigid about how data was bound to these controls. Most of the time developers had to use one or the other data source control (SQL Data Source, Object Data Source, Entity Data Source etc.) to bind data from the underlying data store with the data bound controls. ASP.NET 4.5 provides a flexible alternative to data bind these controls - model binding. Using the new model binding features you can use methods instead of data source controls to perform CRUD operations. This article explains how the new model binding features can be used. You will also learn to use strongly typed data controls.

Data Binding in ASP.NET Server Controls

In the earlier versions of ASP.NET you used data bound controls and data source controls hand in hand to display and edit data. First, you needed to configure a data source control, such as Object Data Source or Entity Data Source and then set the DataSourceID property of a data bound control to the respective data source control. The data bound control would have one or more fields of some inbuilt type (BoundField for example) or template fields. If the control was using template fields you used Eval() data binding expression for one way data binding and Bind() data binding expression for two way data binding.

The following sample markup shows a GridView control bound with an Entity Data Source.

<asp:EntityDataSource ID="EntityDataSource1" runat="server"
    ConnectionString="name=NorthwindEntities"
    DefaultContainerName="NorthwindEntities" EnableFlattening="False"
    EntitySetName="Customers"
    Select="it.[CustomerID], it.[CompanyName], it.[ContactName], it.[Country]">
</asp:EntityDataSource>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
    DataKeyNames="CustomerID" DataSourceID="EntityDataSource1">
    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
            SortExpression="CustomerID" />
        <asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
            ReadOnly="True" SortExpression="CompanyName" />
        <asp:BoundField DataField="ContactName" HeaderText="ContactName"
            ReadOnly="True" SortExpression="ContactName" />
        <asp:TemplateField HeaderText="Country" SortExpression="Country">
            <EditItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>


Notice how the DataSourceID property of the GridView is set to EntityDataSource1. Also, notice the use of Eval() and Bind() to bind the Country column.


Though data source controls work well in simple situations, developers often need complete control on how the data is fetched and how it is saved back to the database. This calls for a more code centered approach than the control driven approach. That is where the new model binding features come into the picture. Using model binding features you can write methods in your code behind class that perform the CRUD operations on the underlying data store. This way you have total control over the process of fetching and editing the data. Have a look at the following markup that uses the new model binding features:

<asp:GridView ID="GridView1" runat="server"
SelectMethod="GetCustomers"
dateMethod="UpdateCustomer"
DeleteMethod="DeleteCustomer"
... >


This time the GridView control doesn't use a data source control. The SelectMethod, UpdateMethod and DeleteMethod properties are set to method names GetCustomers, UpdateCustomers and DeleteCustomers respectively. These methods reside in the code behind. You will develop a complete version of this example in the following sections.

In addition to the code centered data binding, you can also use data within the controls in strongly typed manner. This is especially handy for template fields. Instead of using Eval() and Bind() data binding expressions, you can now use Item and BindItem properties respectively. These properties work along with the ItemType property. The use of these properties will be clear from the following markup.

<asp:GridView ID="GridView1" runat="server"
SelectMethod="GetCustomers"
UpdateMethod="UpdateCustomer"
DeleteMethod="DeleteCustomer"
ItemType="NorthwindModel.Customer"
... >
<Columns>
...
<asp:TemplateField HeaderText="Country" SortExpression="Country">
  <ItemTemplate>
   <asp:Label ID="Label2" runat="server" Text='<%# Item.Country %>'></asp:Label>
  </ItemTemplate
  <EditItemTemplate>
   <asp:TextBox ID="TextBox2" Text='<%# BindItem.Country %>' runat="server"></asp:TextBox>
  </EditItemTemplate>
</asp:TemplateField>
...


Notice the code marked in bold letters. The ItemType property is set to an Entity Framework Data Model type - Customer. Once you do so, you can access properties of Customer class in a strongly typed fashion. Instead of Eval("Country") you now use Item.Country and instead of Bind("Country") you use BindItem.Country. This way there can't be any errors while specifying column names because they are available to you in the intellisense in strongly typed manner.


Creating a Sample Website

Now that you understand the basics of model binding and strongly typed data binding, let's create a web form that illustrates the complete process in detail. You will be using Customers table from the Northwind database in this example. Begin by creating a new ASP.NET Web Site. Then add an Entity Framework Data Model to its App_Code folder and create model class for the Customers table. The following figure shows the Customers model class in the Visual Studio designer




Open the default web form and place a GridView control on it. Configure the GridView to show CustomerID, CompanyName, ContactName and Country columns. Also add Edit and Delete command buttons. The following markup shows the GridView after adding these columns:


<asp:GridView ID="GridView1" runat="server"

SelectMethod="GetCustomers"

UpdateMethod="UpdateCustomer"

DeleteMethod="DeleteCustomer"

ItemType="NorthwindModel.Customer"

AllowSorting="True"

AllowPaging="True"

DataKeyNames="CustomerID" ...>

    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="Customer ID" ReadOnly="True"
            SortExpression="CustomerID"></asp:BoundField>
        <asp:TemplateField HeaderText="Company Name" SortExpression="CompanyName">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox2" Text='<%# BindItem.CompanyName %>' runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Item.CompanyName %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name"
            SortExpression="ContactName"></asp:BoundField>
        <asp:TemplateField HeaderText="Country" SortExpression="Country">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox3" runat="server" Text='<%# BindItem.Country %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label3" runat="server" Text='<%# Item.Country %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowEditButton="True" ButtonType="Button">
        <ControlStyle Width="75px" />
        </asp:CommandField>
        <asp:CommandField ShowDeleteButton="True" ButtonType="Button">
        <ControlStyle Width="75px" />
        </asp:CommandField>
    </Columns>
...

</asp:GridView>


The following figure shows the GridView at runtime:




Notice that the ItemType property of the GridView is set to NorthwindModel.Customer and its SelectMethod, UpdateMethod and DeleteMethod properties are set to GetCustomers, UpdateCustomer and DeleteCustomer respectively. You will be creating these methods in the following sections.


Selecting Data

In order to display data in the GridView you need to write a method that fetches data from the data store and then specify it in the SelectMethod property of GridView. So, switch to the code behind and add a method named GetCustomers() as shown below:


public IQueryable<Customer> GetCustomers()
{
    NorthwindEntities db = new NorthwindEntities();
    var data = from item in db.Customers
                orderby item.CustomerID
                select item;
    return data;
}


The GetCustomers() method returns an IQueryable collection of Customer objects. Inside it fetches all of the records from the Customers table and returns them to the caller. Note that we have enabled paging in our GridView. When you enable paging for a GridView, behind the scenes it fetches only the required number of records as specified by the PageSize property.

Updating and Deleting Data

The methods UpdateCustomer() and DeleteCustomer() do the job of updating and deleting a Customer respectively. The UpdateCustomer() method is shown next:


public void UpdateCustomer(Customer c)

{
    NorthwindEntities db = new NorthwindEntities();
    var data = from item in db.Customers
                where item.CustomerID == c.CustomerID
                select item;

    Customer obj = data.SingleOrDefault();
    obj.CompanyName = c.CompanyName;
    obj.ContactName = c.ContactName;
    obj.Country = c.Country;
    db.SaveChanges();
}


The UpdateCustomer() method accepts a parameter of type Customer. At runtime, when you modify a GridView row and click the Update button, UpdateCustomer() method will be called and the corresponding Customer object is passed as its parameter. Inside, you find out a specific Customer based on its CustomerID, assign the modified values and then save the changes to the database by calling the SaveChanges() method.

The DeleteCustomer() method follows a similar method signature but internally deletes a Customer. The following code shows the DeleteCustomer() method:

public void DeleteCustomer(Customer c)
{
    NorthwindEntities db=new NorthwindEntities();
    var data = from item in db.Customers
                where item.CustomerID == c.CustomerID
                select item;
    Customer obj = data.SingleOrDefault();
    db.DeleteObject(obj);
    db.SaveChanges();
}


The DeleteCustomer() method receives the Customer being deleted as a parameter. Inside it fetches a Customer matching the CustomerID and deletes it using the DeleteObject() method.

Now, run the web form and try editing and deleting a few Customer records.

Adding Validation Support

Though the GridView is able to modify Customer data, there are no validations on the data being saved. One way to enforce the validations is to use a combination of template fields and validation controls. However, there is an easy alternative - Data Annotations.

Data Annotations are special attributes that you apply on the data model properties. They specify validation criteria such as maximum length, minimum length and specific data format (Email address, URL etc.).

To use Data Annotations add a new class in the App_Code folder and name it as CustomerValidations. The CustomerValidations class will store only validation information for the Customer class. You could have added the data annotation attributes directly to the Customer data model class but to avoid accidental overwriting during model recreation it is recommended to isolate them in a separate class.

public class CustomerValidations
{
    [StringLength(5,MinimumLength=3 ,ErrorMessage="CustomerID must between 3-5 characters!")]
    public string CustomerID { get; set; }

    [StringLength(20, ErrorMessage = "Company Name must be upto 20 characters!")]
    public string CompanyName { get; set; }

    [Required]
    public string ContactName { get; set; }

    [Required]
    [StringLength(15,ErrorMessage="Invalid country length!")]
    public string Country { get; set; }
}


The CustomerValidations class makes use of data annotation attributes such as [StringLength] and [Required]. The former attribute ensures that the entered data is within a specified maximum length. The later attribute enforces that the property value must be provided. You can also use many other data annotation attributes depending on your requirement.

As of now the CustomerValidations class is a stand alone class. You need to associate it with the Customer data model class using the [MetadataType] attribute. To do so, open the Entity Framework Data Model file (Model.Designer.cs) and add the following piece of code:

[MetadataType(typeof(CustomerValidations))]
public partial class Customer : EntityObject
{
...
}


The [MetadataType] attribute specifies the type of the class that contains validation information (CustomerValidations in this case).

Now, open the web form and place a ValidationSummary control below the GridView. Set its ShowModelStateErrors property to true. The ShowModelStateErrors property controls whether data model validation errors should be displayed in the ValidationSummary or not.

<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowModelStateErrors="true" ... />


In addition to displaying validation errors to the end user, you should also ensure that the changed Customer details are saved in the database only if model validations are successful. To do so, modify the UpdateCustomer() method as shown below:

public void UpdateCustomer(Customer c)

{

    NorthwindEntities db = new NorthwindEntities();
    var data = from item in db.Customers
                where item.CustomerID == c.CustomerID
                select item;
    Customer obj = data.SingleOrDefault();
    obj.CompanyName = c.CompanyName;
    ...
    if (ModelState.IsValid)
    {
        db.SaveChanges();
    }
}


Notice the code marked in bold letters. The UpdateCustomer() method now checks the state of the model using the ModelState.IsValid property. If all the model validations are successful, the IsValid property will return true and only then will changes be saved to the database.


Now, run the web form again and try to enter some invalid data. You should see validation errors similar to the following figure:




Summary


ASP.NET 4.5 supports model binding that allows a more code centric approach for performing CRUD operations on the data. Instead of using Data Source Controls, you can now write methods in the code behind file that select, insert, update and delete data from the underlying data store. The SelectMethod, InsertMethod, UpdateMethod and DeleteMethod properties of data bound controls are used to specify the respective method. You can also make use of Data Annotations for performing validations on the data being entered. Thus the new model binding features provide a more flexible and powerful approach to data binding.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in