Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 2

Last week, I wrote the first part of the post Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5. In the first post , I discussed about Strongly typed data control, Model Binding, filtering data, Value Providers and about writing own Custom value provider. Please find the link of earlier post below.

http://brijbhushan.net/2012/07/01/strongly-typed-data-controls-and-modal-binding-in-asp-net-4-5-part-1/

Model Binding feature also supports editing feature. Control’s like Gridview has three properties

  • InsertMethod
  • UpdateMethod
  • DeleteMethod

you can assign a method that has been written at code behind and the method takes a single parameter with the associated type. And the value of the parameter holds the value to be updated. As say if my Control is associated with a Type say Product then the delete method could be as

public void DeleteProduct(Product p)
{
//Write the logic of deleting the passed product p
}

Now, I’ll talk about Model Validation and custom validation attribute. So let’s start.

We all have used ASP.NET validators many times for validating lot of controls and of course used the same of data controls like GridView also. But Model Binding provides another way of implementing validation.

So now you can use System.ComponentModel.DataAnnotations and apply the validation at your model level. And if your control is bound to some model that validation would be taken care. So let’s start with an example. See how can we put different Validation attribute to our class as below

public class Speaker
{
[Required()]
public int Id { get; set; }
[Required(), StringLength(30)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(), StringLength(30)]
public string Lastname { get; set; }
[Required(), StringLength(30)]
public string ExpertArea { get; set; }
[Url ()]
public string blogURL { get; set; }
[Required(), Range(5,1000)]
public int LastYearSessionCount { get; set; }
public string Email { get; set; }
}

As I put Id as required attribute, it means it is required and if it is not provided it’ll throw an error.

DataAnnotations provides other kind of validations like Range,  StringLength etc as well. Also we can have multiple attributes as well on any property to have multiple validations on same Value as you can see above.

I have used a DetailsView and used this class as model for that DetailsView control as

<asp:DetailsView ID="detailsViewSpeaker" runat="server" SelectMethod="GetSpeakers" InsertMethod="InsertSpeaker" AutoGenerateInsertButton="true"
ItemType="Speaker"></asp:DetailsView>

You must have used ValidationSummary control earlier. Now this control has one more property called ShowModelStateErrors which need to be set as true. This will be enable the page to display all model related errors as

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

Now let’s run the page

You can see the above screen, all the validation errors are Mode state errors.

This is not at all, if your requirement does not get fulfilled by the in built validation attribute then you can write your own custom attribute as well. To create a custom attribute, you need to implement ValidationAttribute and override IsValid method and need to put own custom logic in this method only. lets create a custom validation attribute.

In my example, I have written custom logic for validating an email. Let’s have a look

public class MyCustomValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
Regex regex = new Regex(MatchEmailPattern);
return regex.IsMatch(value.ToString());
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString, name);
}
}

We can also tweak the default validation message by overriding FormatErrorMessage as I have done above. Now Let’s use it in my model. As

public class Speaker
{
[Required()]
public int Id { get; set; }
[Required(), StringLength(30)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(), StringLength(30)]
public string Lastname { get; set; }
[Required(), StringLength(30)]
public string ExpertArea { get; set; }
[Url ()]
public string blogURL { get; set; }
[Required(), Range(5,1000)]
public int LastYearSessionCount { get; set; }
[MyCustomValidation(ErrorMessage = "{0} field custom validation failed. Your email is not in proper format.")]
public string Email { get; set; }
}

Now Let’s run the application

As you can see, I have entered a wrong formatted email. And when clicked on Insert button, the custom validation is error is thrown.

Hope you all have enjoyed this post.

Thanks,

Brij

Win a Free Copy of Windows Identity Foundation book by Packt

Hello friends,

This post is something different and something new to all. You have read my blog several times and gave your precious comments. Now you have a chance to win a free e-copy of Microsoft Windows Identity Foundation Cookbook of Rs 924/-. Three lucky blog readers stand a chance to win an e-copy

This contest is sponsored by Packt Publishing. This contest starts from today (10th July 2012) and will end on 25th July 1st August 2012. The winner will be announced in three days after contest ends.

The Last date of this contest has been extended to 1st August 2012. Make the most use of it.

Windows Identity foundation is a .NET Technology which plays a pivotal role on Cloud based system.It provides a framework to work with Identity aware applications. ACS is based on Identity framework which provides Authentication and Authorization services for applications hosted on Azure.

About the Book:

  • Gain a firm understanding of Microsoft’s Identity and Access Control paradigm with real world scenarios and hands-on solutions.
  • Includes step-by-step recipes on easy-to-implement examples and practical advice on real world scenarios.

Read more about this book and download free Sample Chapter: www.packtpub.com/microsoft-windows-identity-foundation-cookbook/book

How to Enter?

You just need to follow few steps.

Cheers,
Brij

Microsoft Windows Identity Foundation Cookbook – Review

Hello All,

In this Post, I am reviewing a book on Windows Identity Foundation by Packt Publishing.

The content of this includes basic to advance topics of Windows Identity foundation. It has full of hands on examples with explanation which can give fair enough knowledge for working with Windows Identity Foundation.

But I feel, It could contain more explanation on the basics of Claims based Authentication, Windows Identity Foundation and some other topics as well. But as a developer, there is enough sample based examples that one can study and so some hands on. Being a developer, It is one of the key point that I need.

So if you have basic knowledge current Authentication and Authorization mechanism and also read n heard a lot about Claim based Authentication. And now if you want to hands on working knowledge then this bo0k will be very helpful for you.

Access control Service (ACS) is main component of Windows Azure and it provides the feature of Authentication and Authorization for Application hosted on Cloud. This book contain step by step examples for working with ACS 2.0.

Also I need to mention the system requirement for working with WIF. These are

  • Microsoft Windows Vista® SP1, Windows 7, Windows Server 2008 (32-bit or 64-bit), or Windows Server 2008 R2 (32-bit or 64-bit)
  • Microsoft Internet Information Services (IIS) 7.0 or 7.5
  • Microsoft .NET Framework 4.0
  • Microsoft Visual Studio® 2010 (excluding Express editions)
  • Windows Identity Foundation

You can get a book from here

http://www.packtpub.com/microsoft-windows-identity-foundation-cookbook/book

Thanks,
Brij

Recieved Microsoft MVP (ASP.NET/IIS) award second time in a Row

Thanks a lot to all my Readers and supporters. I received MVP award second time in a Row. It’s really a great achievement for me and all the kudos goes to my Readers and supporters.

I also would like to take names of few of my friends Abhijit Jana, Abhishek Sur, Kunal Chaowdary, Ravi, Srinandan and many more. and some other blog friends Daniel,  Pete O Hanlon, Alan Beasley, Petr Pechovic and many others. They always gave their candid feedback which helped me a lot. I would also like to thank Mr Tanmay Kapoor (MVP lead).

I’ll continue blogging and speaking in coming years with the same enthusiasm and will always need you support and feedback.

Again Thanks a lot to all.

Cheers,

Brij

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 1

Recently, I took  a session on KolkataGeeks and discussed on  ASP.NET 4.5 enhancements. I mainly discussed on changes in data controls and model binding feature added in ASP.NET4.5.

I am going to write a series of post on the same feature here also. Till date, you all must have  had a look on the enhancement and new features introduced in ASP.NET 4.5. The main change in data control that now it provides intellisense support at aspx pages. You need to assign the ItemType property to model that is going to be associated with the data controls. As

Strongly Typed Data Control

These controls are also referred as Strongly Typed Data Controls.

There are also other major changes took place, in the way we provide the DataSource to the our DataControls. Here in my example, I have taken a GridView.

Earlier, we used to provide DataSource to our Data Control and then call DataBind. We used multiple Data Sources like SQLDataSource, ObjectDataSource etc. But now, you have another option which allows us to not set DataSource property and call the DataBind specifically.

There is a property got introduced named as SelectMethod. We can write our own method at server side and assign the method to this property. One thing, we need to take care that it must return the collection of objects and it should be either IEnumerable or IQueryable. Server side method could be as

public IQueryable<Product> GetProducts()
{
return dbcontext.Products.AsQueryable().OrderBy(i => i.Name);
}

And my gridview at aspx

<asp:GridView ID="gridProducts" runat="server" ItemType="AdventureWorksLTModel.Product" AutoGenerateColumns="false"
SelectMethod="GetProducts" >
<Columns>
<asp:TemplateField HeaderText="Product Name" SortExpression="Name">
<ItemTemplate>
<%#Item.Name %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="ListPrice">
<ItemTemplate>
<%#Item.ListPrice %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Color" SortExpression="Color">
<ItemTemplate>
<%#Item.Color %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Now why this method should return only IEnumerable or IQueryable . Controls like GridView provides many features like Paging, Sorting etc. As soon as you assign the method to SelectMethod property. You don’t need to write any special code for Paging, Sorting.. feature. For that it creates Linq  queries on the fly and it can be written only on the collection that implements IEnumerable or IQueryable.

That’s not it, in many cases we provide some kind of filter criteria to the users, based on user can view only filtered data.

ASP.NET4.5 provides many Value Providers that can be used and these value providers are

  • Querystring
  • Session
  • Cookie
  • Control Value
  • Form Value etc..

These value provider can be directly used to filter the data. But how?

These value providers must be passed as a parameter in the method, that is going to be assigned to Select method. Let’s if we want Query String as value provider so we can pass it as

public IQueryable<AdventureWorksLTModel.Product> GetProducts([QueryString("key")]string parameter)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.Where(p => p.Color == parameter).AsQueryable().OrderBy(i => i.Name);
}

where key is the Query String parameter and it can access the value directly in the method as above.

Similarly other value providers can be used. One more example, we can have some control’s value as value provider. For that in my example, I have created a drop down and I want to use drop down’s selected value for filtering the data it can be used as

<asp:DropDownList ID="ddlColors" runat="server" SelectMethod="GetColors" AutoPostBack="true" ></asp:DropDownList>

Above one is my dropdown. And as you can see, It also has SelectMethod, I have assigned it a GetColors method and it is also written as

public IEnumerable<string> GetColors()
{
var colors = (from c in dbcontext.Products
where c.Color != null
select  c.Color).Distinct();
return colors.ToList();
}

Now my SelectMethod method for gridview is

<pre>public IQueryable<AdventureWorksLTModel.Product> GetProducts([Control]string ddlColors)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.Where(p => p.Color == ddlColors).AsQueryable().OrderBy(i => i.Name);
}

You can see the parameter name and it is ddlColors is Id of the dropdown.

Now this is not all. You can also create your own custom value provider. To create your very own Value provider, you need to implement IValueProvider. Here you need to implement a method GetValue which takes a key (string) as a parameter. It returns an instance of ValueProviderResult . It contains the value returned by the ValueProvider.

I created a value provider which takes a value from querystring based on it fetch some data from database and return it. As

public class MyCategoryProvider : IValueProvider
{
private HttpContextBase context;
private string value;
private int limit;
public MyCategoryProvider(HttpContextBase hcb, string val)
{
context = hcb;
value = val;
}

public bool ContainsPrefix(string prefix)
{
throw new NotImplementedException();
}

public ValueProviderResult GetValue(string key)
{
string category = context.Request.QueryString[this.value] as string;
GetPriceLimit(category);
return new ValueProviderResult(limit, limit.ToString(), System.Globalization.CultureInfo.CurrentCulture);
}
}

Now this can not be used directly. Because ValueProvider is used as an Attribute. So now, you need to create a custom attribute which returns the your Value provider.

To Create a Custom attribute you need to inhert from ValueProviderSourceAttribute which is available in namespace System.Web.ModelBinding . Here override the method GetValueProvider which returns the valueprovider. It is wrtitten as

[AttributeUsage(AttributeTargets.Parameter)]
public class CategoryAttribute : System.Web.ModelBinding.ValueProviderSourceAttribute
{
private string code;
public CategoryAttribute(string _code)
{
this.code = _code;
}

public override IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
{
return new MyCategoryProvider(modelBindingExecutionContext.HttpContext, this.code);
}
}

Now your custom value provider is ready for use. Let’s use this

public IQueryable<Product> GetProducts([Category("cat")]int parameter)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.AsQueryable().Where(p => p.ListPrice <= parameter).OrderBy(i => i.Name);
}

So, you can see that I have used Category as a Value Provider.

Hope you all have enjoyed the post. I’ll discuss more on Validation and other things in my next post.

Cheers,
Brij