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 :: Creating Custom Value Provider in ASP.NET 4.5

clock May 30, 2013 07:46 by author Scott

With ASP.NET 4.5, ASP.NET introduced model binding for web forms as well. Model binding helps to simplify code focused data access logic within web forms.

Here in this post, we will see how we can create our own custom value provider. We will also examine inbuilt class of ASP.NET 4.5 model binding framework which can be useful in creating custom value provider more easily with focused approach.

Before we look into actual interfaces and classes, let us examine few basics of model binding framework. All model binding framework and corresponding classes are resides in System.Web.ModelBinding namespace which is newly introduced with ASP.NET 4.5. For any value provider to work with model binder it requires two components one is implementation of value provider which reads data from request and forward it to model binder and other one is value provider source attribute which expose the actual value provider instance. Have a look at below code snippet here QueryStringAttribute is value provider source attribute which expose object of QueryStringValueProvider so model binder can use it to fetch data.

public IQueryable<Blog> SelectMethod([QueryString]int? id)

Creating Value Provider Source Attribute

To create custom value provider attribute we can derive Attribute class and implement IValueProviderSource interface as displayed in below code snippet.

public class CustomValueProviderAttribute : Attribute, IValueProviderSource
    public IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        return new CustomValueProvider(modelBindingExecutionContext);

Here we can have access of ModelBindingExecutionContext and we can pass same to value provider if it is required. Through ModelBindingExecutionContext we can also have access of HttpContextBase and ModelStateDictionary.

Creating Value Provider

Same way we can create Custom Value Provider by implementing IValueProvider interface. Below code snippet shows pseudo code for the same.

public class CustomValueProvider : IValueProvider
    ModelBindingExecutionContext _modelBindingExecutionContext;

    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        this._modelBindingExecutionContext = modelBindingExecutionContext;

    public bool ContainsPrefix(string prefix)
        // validate if requested key is exist or not

    public ValueProviderResult GetValue(string key)
        // return ValueProviderResult object we
        // can use ModelBindingExecutionContext
        // to access request data

Once we are ready we can use created value provider as

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

As noted earlier, there are few inbuilt classes in ASP.NET 4.5 model binding framework which give more focused control over custom business logic. Here we will also examine one of its which is SimpleValueProvider. Here we will examine how we can focus on core logic and leaving other responsibility on core framework.

public class CustomValueProvider : SimpleValueProvider
    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        : base(modelBindingExecutionContext)

    protected override object FetchValue(string key)
        // here we can access this.ModelBindingExecutionContext
        // and can look into request data. Once we fetch requested
        // data we just need to return actual value for e.g.           
        return "";
        // NOTE: WE ARE NOT RETURNING ValueProviderResult INSTANCE

Earlier with IValueProvider, we had to check if requested key exist or not and if it is then instantiating ValueProviderResult and return it. While with SimpleValueProvider we only need to return actual value of requested key or null incase if it does not exist rest will be taken care by SimpleValueProvider class. Another such framework class is NameValueCollectionValueProvider which act as a base class to create value provider from name value collection. Here I am not demonstrating it. I am leaving it for reader :).

SimpleValueProvider and ASP.NET MVC

Can’t we have/introduce SimpleValueProvider class for MVC in upcoming version?


Once model binding is done for parameter it is added to ModelStateDictionary dictionary along with its value. For e.g.

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

In above code once model binding is done for parameter id, it is added to ModelStateDictionary and it is accessible in rest of the parameter model binding i.e. parameter name here.


European ASP.NET 4.5 Hosting - Amsterdam :: Revisiting IBundleTransform ASP.NET 4.5 and MVC 4

clock May 13, 2013 10:12 by author Scott

Web optimization frameworks include two defaults transform type JsMinify and CssMinify which is used by ScriptBundle and StyleBundle respectively. However we can create our own custom transform type to processe references as per our need. To create custom transform type, we need to create class which implements IBundleTransform interface.

IBundleTransform interface define a method named Process which process bundle response. In developer preview version, Process method had only one parameter of type BundleResponse, however onwards RC release, Process method introduced one more parameter of type BundleContext. In this post, we will see how we can utilize this additional parameter while creating our custom transform type.


As name suggest, with BundleContext, we can get information about bundles which could include existing bundle information, bundle url, HTTP context for bundle, etc. Following is the list of all property of BundleContext.

- BundleContext.BundleCollection : We can get collection of all bundles including default and custom bundle in application through this property.

- BundleContext.BundleVirtualPath : This property expose virtual bundle url i.e. ~/bundles/MyBundle.

- BundleContext.HttpContext : This property is type of HttpContextBase, and we can have access of HTTP context through this property. This is very much useful property when we are creating transform type which generate dynamic response. For e.g. we can access query string parameter passed to bundle url (~/bundles/MyBundle?id=123) through this property (context.HttpContext.Request.QueryString["id"]) and we can use it to create dynamic bundle response.

- BundleContext.UseServerCache : Default value of this property is true. It means only first request to bundle url will be intercepted by transform types and once response is generated it will be stored in server cache and further request to bundle url will be served from server cache without processing it. This will help to reduce bundle processing time and to increase performance. If we set BundleContext.UseServerCache to false then all request will be processed by transform type this is only necessary when bundle url are generating dynamic response. See detailed walkthrough later in this post showing how to use this property in accordance with BundleResponse.Cacheability.

- BundleContext.EnableInstrumentation : Default value of this property is false. This is used for tracing and analysis purpose. We can check value of this property and can write tracing code accordingly. We can also set true to this property to enable instrumentation for further lifecycle of Web optimization frameworks for current bundle request.


Now let us recall BundleResponse parameter from old post. BundleResponse is used to retrieve list of files included in bundle so we can process it and generate response for bundle. As BundleResponse is used to generate response of bundles, it needs to take care of two primary properties of generated response. One is response content type and another one is HTTP Cache-Control header. So BundleResponse also expose properties for the same. Following is the list of all properties in BundleResponse class.

- BundleResponse.Files : This is IEnumerable collection of files which is included in bundle. We can iterate through this collection and process file content to generate bundle response.

- BundleResponse.ContentType : Through this property, we can set content type for bundle so that browser can render it appropriately. Default content type "text/html".

- BundleResponse.Cacheability : We can use this property to set Cache-Control HTTP header of bundled response. Default value of this property is Public.

- BundleResponse.Content : Anything which we set as a value of this property, that content will be sent back to browser as a response of bundle.

Following is the complete code which shows how to create custom transform type and how we can use it with bundling.

public class CustomTransformType : IBundleTransform
    public void Process(BundleContext context, BundleResponse response)
        string strBundleResponse = string.Empty;
        foreach (FileInfo file in response.Files)
        response.Content = strBundleResponse;

Bundle myBundle = new Bundle("~/bundles/MyBundle", new CustomTransformType());

Bundle and truly dynamic response

As we noted earlier, we can set BundleContext.UseServerCache to false in order to process all bundle request and generate dynamic response. Let try to simulate this by small walkthrough and see it works or we need to take care any additional parameter.

public void Process(BundleContext context, BundleResponse response)

    context.UseServerCache = false;
    response.Content = DateTime.Now.ToString();

We are returning current date time with UseServerCache set to false. Now try to hit bundle url multiple times by pressing F5. Oops… it seems it has processed bundle response only first time. Let dig more into this, open another browser and hit same url… ahmm it seems it has processed bundle response one more time… again press F5 multiple times…bad luck

As we can see, it seems (read again it seems) it is processing bundle response only first time for separate client (is it really? nop). Nop this is not the case. In fact this is how client deals with it due to HTTP cache control header. Confused? See response header of bundle url to get more information.

As we noted earlier default value of BundleResponse.Cacheability is Public. So even if we have set BundleContext.UseServerCache to false then also due to Expires response header and Public Cache-Control header client is not sending request back to server. So in this case we need to also set BundleResponse.Cacheability to NoCache. We can also set it to Private but in some client we need to press Ctrl + F5 to refresh bundle response.

public void Process(BundleContext context, BundleResponse response)
    context.UseServerCache = false;
    response.Cacheability = HttpCacheability.NoCache;
    response.Content = DateTime.Now.ToString();

After setting BundleResponse.Cacheability to NoCache try to refresh bundle url again now it is re generating bundle response on each request.

European ASP.NET Hosting - Amsterdam :: How to Develop Mobile WebSite Using ASP.NET

clock May 8, 2013 06:58 by author Scott

In this article we will learn how to create web pages for mobile. Developing mobile web pages is not as developing our simple desktop pages. For developing mobile web pages we have to use “System.Web.Mobile” dll which will provide the classes for developing our mobile web pages. This dll contains all about mobile web pages. How to add this dll and how to use we will see here step-by-step.

1. Start new Website give some name. It will create a website with web.confige and one Default.aspx and Default.aspx.cs files.

2. Next Goto Website menu and add Reference to “System.Web.Mobile” namespace.

3. Now just open Default.aspx page in source code view and register our System.Web.Mobile assembly like this.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

4. Open the page in Design view and see how the page is looking now. Generally mobile pages are not editable. If we want to design this pages with controls we cannot use our toolbox controls. For creating controls we must have to write control code in source view.

5. Now move to source code view and create controls like bellow. Here we will Create Label,TextBox And Button controls. For creating mobile web controls we must have to create mobile form for that just replace our Desktop form like and create the controls for our mobile web page.

<html xmlns="" >
    <mobile:Form id="Form1" runat="server">
<mobile:Label ID="label1" Runat="server">Label1</mobile:Label>
<mobile:TextBox ID="TextBox1" Runat="server"></mobile:TextBox>
<mobile:Command ID="Command1" Runat="server" OnClick="Command1_Click">Command1</mobile:Command>

6. Now go code view mean in aspx.cs file and import the namespace of mobile pages and controls as well inherit the Default page with MobilePage.

using System.Web.Mobile;
using System.Web.UI.MobileControls;
public partial class Default : System.Web.UI.MobileControls.MobilePage
    protected void Page_Load(object sender, EventArgs e)

    protected void Command1_Click(object sender, EventArgs e)


7. Now run the application and see in the browser pages will look like something bellow screen. To test this mobile web pages in mobile screens we have to test in mobile emulators. But here we will see our pages in generally desktop browser.

Adding Mobile Web Pages Template To Visual Studio 2008:

Here we will see how to add Deafult template to visual studio 2008. This template actually I got from some website. This template are specially mobile page templates which will add mobile page to our project. This is will make your work easy for adding the mobile web page. Means here you need not to write the code every time just follow the steps given bellow.

1. Here we will see how to add Deafult template to visual studio 2008. This template actually I got from some website. This template are specially mobile page templates which will add mobile page to our project. This is will make your work easy for adding the mobile web page. Means here you need not to write the code every time just follow the steps given bellow.

2. Now open this directory which contains 3 zip files and one text file just open that text file and copy that zip file to the given location  in text file. Fallol same procedure for both directory.

3. Now open Visual Studio and start new website again. Which will give same web.Confige Default.aspx and Default.aspx.cs files. Now delete this files and say Add new item which display visual studio template with our mobile web page templates as follows.

Done…. Now, you know how to develop mobile web pages.


European ASP.NET 4.5 Hosting - Amsterdam :: How to Upload a file in MVC4 C#5 .NET 4.5

clock May 3, 2013 06:27 by author Scott

One of the features of this so called killer app will be to upload pictures (nothing special I agree). But how would I do this for all the clients I hope to support (WinRT/WP7/Html5/IOS).

Let me first present the server that will be used for all these clients, I’ll then follow up with what I consider to be the simplest client a html5 browser!


So I fired up VS11 and created a new MVC4 application using .net 4.5 / C#  and the WebApi template.

I then added a controller called FileUploadController.cs

   1:  using System.Collections.Generic;
   2:  using System.Linq;
   3:  using System.Net;
   4:  using System.Net.Http;
   5:  using System.Threading.Tasks;
   6:  using System.Web.Http;
   8:  namespace MvcApplication16.Controllers
   9:  {
  10:      public class FileUploadController : ApiController
  11:      {
  12:          public async Task<IEnumerable<string>> PostMultipartStream()
  13:          {
  14:              // Check we're uploading a file
  15:              if (!Request.Content.IsMimeMultipartContent("form-data"))           
  16:                  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  18:              // Create the stream provider, and tell it sort files in my c:\temp\uploads folder
  19:              var provider = new MultipartFormDataStreamProvider("c:\\temp\\uploads");
  21:              // Read using the stream
  22:              var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);           
  24:              // Create response.
  25:              return provider.BodyPartFileNames.Select(kv => kv.Value);           
  26:          }
  27:      }
  29:  }

You can see from line 12 that I’ve made this operation async, you’ve really got to admire the simplicity of async/await construct in .net 4.5! In line 22 you can see that the compiler and some state machine magic allow the freeing up of the asp worker thread…..

HTML5 Client

The client couldn’t have been easier, fist a look at it in the browser

   7:      <meta name="viewport" content="width=device-width" />
   8:  </head>
   9:  <body>
  10:      @using (Html.BeginForm("FileUpload", "api", FormMethod.Post, new { enctype = "multipart/form-data" }))
  11:      {
  12:          <div>Please select some files</div>
  13:          <input name="data" type="file" multiple>
  14:          <input type="submit" />           
  15:      }
  16:  </body>
  17:  </html>

The important part above is using the enctype attribute, in fact line 10 loosely translates to

<form action="~/api/FileUpload" enctype="multipart/form-data" method="POST">

Don’t believe me? Then try VS11’s awesome new feature – page inspector

Right click on the html and choose view in page inspector

and we’re done! Of course in the real world we’ll use ajax with a few trick re sandbox, but here’s the response in the browser with xml.

I’ll hopefully follow up with the samples for the client list below when I get to the respective development machines.


European ASP.NET Hosting - Amsterdam :: Configuring ASP.NET Membership Using SQLMembershipProvider

clock May 1, 2013 08:57 by author Scott

This article describe article about how to configure ASP.NET Membership to store user information in an external SQL Server database. We will use SQLMembershipProvider for this task.

ASP.NET Membership

ASP.NET Membership enables us to validate and store user information. It creates all the necessary tables and stored procedures to store and manage user credentials. It provides an API that can be used to manage user's information programmatically.

ASP.NET Membership provides two types of Membership providers:

  1. SQLMembershipProvider : It is used to store user information in a SQL Server database
  2. ActiveDirectoryMembershipProvider : It is used to store user information in an Active Directory.

To configure SQLMembershipProvider, first you need to configure your database.

Open Visual Studio Command Prompt (All Programs -> Microsoft Visual Studio 2008 -> Visual Studio Tools -> Visual Studio 2008 Command Prompt)

Type command : aspnet_regsql and press Enter

This will launch ASP.NET SQL Server Setup Wizard

Click Next

Leave the default selection "Configure SQL Server for application services" and click Next again.

Enter the server name, Select SQL Server authentication and enter user id and password as in the following figure. Select the database you want to configure. Here, I am using Employee database.

Click Next

Click Next and then Finish.

Now, you can see the new tables created in the Employee database for storing user credentials. These table names start with "aspnet_". Similarly, you can also see new Stored Procedures created in the database with "aspnet_" prefix.

Now, we have configured our Employee database. Our next task is to enable SQLMembershipProvider in a Web application. Follow these steps to do that:

  • Create a new ASP.NET Web Application
  • Add <authentication mode="Forms"/> in the Web.Config file. ASP.NET Membership works with only Forms Authentication
  • Add the following to enable SQLMembershipProvider:

          <membership defaultProvider="MyMembershipProvider" >
              <add name="MyMembershipProvider"

          connectionStringName="ConString" />

  • Add a connection string with the name "ConString" to connect with the Employee database

          <add name="SqlConString" connectionString="Data Source=localhost\SQL2005EXPRESS; User ID=youruserid; Password=yourpassword;
                Initial Catalog=Employee;" />

Now, we are ready to use ASP.NET Membership to create a new user using CreateUserWizard control and authenticate users using Login control.

About 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.

Tag cloud

Sign in