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 :: ASP.Net 4.5 Strongly Typed Data Controls and Visual Studio 2012

clock June 25, 2013 06:46 by author Scott

In this post I will show you one of great features in ASP.NET 4.5, it is called Strongly Typed Data controls in ASP.NET 4.5.

I will be demonstrating with a hands-on example on Strongly Typed Data controls and how we can have Intellisense and compile type checking using this new feature.

I assume you have downloaded VS 2012 (Express edition will do).I have also downloaded and installed AdventureWorksLT2012 database.You can download this database from the codeplex website.

I will be creating a simple website without using this feature. Then I will show you what the problem is without using this feature.

1) Launch VS 2012. Create a new ASP.Net Web Forms Site. Choose C# as the development language.Give an appropriate name to your site.

2) Now we will add a data access layer to our site in order to fetch some data to the user interface.I will use EF database first approach.

3) Add a new item in your project, an ADO.Net Entity Data Model. I have named it AdventureWorksLT.edmx.Then we will create the model from the database and click Next.Create a new connection by specifying the SQL Server instance and the database name and click OK.Then click Next in the wizard.In the next screen of the wizard select only the Customer table from the database and hit Finish.You will see the Customer entity in the Entity Designer. 

4) Add a new web form to your site.Name is Customer.aspx.We will add a new web server control a GridView that will get the data from the database through EF.

This is the code for the web server control.I am using the Bind syntax.We are using strings to represent the property names (FirstName,LastName).

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

            <Columns>
                <asp:TemplateField HeaderText="FirstName">
                   
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                    </ItemTemplate>
               
               </asp:TemplateField>
               
               <asp:TemplateField HeaderText="LastName">
                   

                     <ItemTemplate>
    <asp:Label ID="lbName" runat="server" Text='<%# Bind("LastName")
%>'></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

5) In the Page_Load event handling routine of the Customer.aspx page type the following code

        AdventureWorks2012Entities ctx = new AdventureWorks2012Entities();

        var query = from cust in ctx.Customers
     
        select new {cust.FirstName,cust.LastName};

        GridView1.DataSource = query.ToList();

        GridView1.DataBind();

6)  Build and Run the application. You will see the data appearing on the page.

7) Now let's do a simple typo.Replace the following line

<asp:Label ID="lbName" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>

with this

<asp:Label ID="lbName" runat="server" Text='<%# Bind("LLastName") %>'></asp:Label>

Build your site. It will compile. The compiler does not know anything . Guess where you will get the exception, at runtime.Run your site and you will get an exception.

8) Let's rewrite the code in the Customers.aspx page.

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ItemType="AdventureWorks2012Entities.Customer">

            <Columns>
                <asp:TemplateField HeaderText="FirstName">

                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Item.FirstName %>'></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="LastName">

                    <ItemTemplate>
                        <asp:Label ID="lbName" runat="server" Text='<%# Item.LastName %>'></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

Now we can tell our application what type of data the control will be bound to using the ItemType 

ItemType="AdventureWorks2012Entities.Customer"

Now we need to alter the code in the template. Have a look at those 2 lines 

  <asp:Label ID="lblName" runat="server" Text='<%# Item.FirstName %>'></asp:Label>
  <asp:Label ID="lbName" runat="server" Text='<%# Item.LastName %>'></asp:Label> 

Now we have compile type checking and Intellisense in our sample application.As we type the compiler informs us if it recognizes the property. This is a great enhancement since I do not want to face exceptions on runtime because of typos. 

9) Build and run your application again. The sample application works fine.

 



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 "dotnetExpertGuide.com";
        // 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?

ModelStateDictionary

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 Hosting - Amsterdam :: The Parallel.Invoke() Method C# / .NET

clock February 4, 2013 10:17 by author Scott

Many times in software development, we want to invoke several processes at one time and continue when we get all the results back.  Obviously, if we were needing to process a sequence of items in a similar matter, we could use PLINQ.  Unfortunately, when the things we want to invoke asynchronously are heterogeneous tasks, PLINQ doesn’t really fit the bill.  Today we will look at a handy method in the Parallel class that can help us accomplish this.

Invoking processes asynchronously

Let’s say we have three completely separate methods and we want to invoke all three of them and the continue when they have returned.  These methods may be from separate classes and have completely different parameters and/or return types.  Thus, it may not be possible to use facilities likeParallel.ForEach() or PLINQ.

So how would we do this?  Well, we could obviously create three threads, start them, and join on them to come back:

   1: var threads = new List<Thread>
   2:                   {
   3:                       new Thread(SomeMethod),
   4:                       new Thread(() => SomeOtherMethod(x, y)),
   5:                       new Thread(() => { result = YetAnotherMethod(x, y, z); })
   6:                   };
   7: threads.ForEach(t => t.Start());
   8: threads.ForEach(t => t.Join());

Which, as you can see, can be used to call any method that fits Thread’s constructor (or can be adapted to it using a lambda, etc.). 

But that’s a bit heavy.  In addition, if an unhandled exception is thrown in one of those methods it will kill the thread, but we don’t have a very clean way of catching it here at the point of invocation.

Of course, we also have the Task class from the TPL which can help simplify threads:

   1: var tasks = new []
   2:
                 {
   3:                     Task.Factory.StartNew(SomeMethod),
   4:                     Task.Factory.StartNew(() => SomeOtherMethod(x, y)),
   5:                     Task.Factory.StartNew(() => { result = YetAnotherMethod(x, y, z); })
   6:                 };
   7: Task.WaitAll(tasks);

This simplifies things on the surface, and better yet simplifies things a lot more with exception handling as well (TPL task exceptions get wrapped into a AggregateException and can be caught at the WaitAll() – and other possible places).

But there’s an even easier way…

Parallel.Invoke() – Easily invoke asynchronously

Just as the TPL gave us Parallel.For() and Parallel.ForEach() to make processing loops asynchronously a breeze, it also gave us Parallel.Invoke(), which takes any number of Action delegates and invokes them asynchronously and waits for them to rejoin.  If your methods have return values you want to store or need parameters, you can easily use lambda expressions as well:

   1: Parallel.Invoke(
   2:
     SomeMethod,
   3:     () => SomeOtherMethod(x, y)),
   4:     () => { result = YetAnotherMethod(x, y, z); })

As long as the method can convert to an Action or you can form a lambda that will allow it to do so, you can use the Parallel.Invoke() to easily call them all in parallel without having to worry about starting or joining the threads or tasks.  And, because this is part of the TPL, you get the nice AggregateException handling as well that lets you easily catch tasks thrown from the underlying tasks.

Summary

When you just need to fire off several methods in parallel, consider the Parallel.Invoke().  It is a very handy way to invoke several different methods easily without having to worry about all the details of creating tasks or threads.

 



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