Implementing Validation mechanism in ASP.Net MVC project using Unobtrusive JavaScript for validation

In this article I will walk you through the steps of implementing validation in the ASP.Net MVC project using jquery.validate.unobtrusive.js

What is Unobtrusive JavaScript?

Unobtrusive JavaScript is the best practices to separate the JavaScript code from presentation or html.

For example

<input
type=”button”
id=”btn”
onclick=”alert(‘hello world’)
/>

The above code is obtrusive as we have called the JavaScript alert method within the html control’s input tag. In order to make this unobtrusive we can create a separate JavaScript file and with the help of jQuery we can register a click event for this button like this.

$(document).ready(function () {

$(‘#btn’).click(function (e) {

    alert(‘hello world’);

}

});

For validation there is a JavaScript named jquery.validate.unobtrusive.js which can automatically attach validation with all the input controls that you have in your html file. But those controls should have data-val attribute to true. Otherwise the validation for that particular control does not applied. In ASP.Net MVC, you know that there are many HTML helper functions like @Html.TextBoxFor, @Html.EditorFor, etc. that takes an expression and attributes. By default, when we use these methods in our code, depending on the data annotation attributes we have used in our Model it automatically applies the validation at the time of rendering the html control.

For example

If our model is


public
class
Person : Message

{

[GridColumn("Id", true)]


public
int Id { set; get; }

 

[Required]

[GridColumn("Name", false)]

[StringLength(10, ErrorMessage="Length cannot exceed to 10 character")]


public
string Name { set; get; }

}

In ASP.Net MVC we can associate a model while adding a view and in that view we can call HTML helper functions like this


@Html.EditorFor(model => model.Name)

This will generates an html as follows


<input data-val=”true” data-val-length=”Length cannot exceed to 10 character” data-val-length-max=”10″ data-val-required=”The Name field is required.” id=”Name” name=”Name” type=”text” value=”Ovais” />

You can see that depending on the model it has automatically added the data-val-* properties in the html.

There is no magic, actually in order to make this work

  1. You have to add a jquery.validation.unobtrusive.js in your project.
  2. Then add the file path in the bundle like this

     

    bundles.Add(new
    ScriptBundle(“~/bundles/jqueryval”).Include(


    “~/Scripts/jquery.validate*”));

     

  3. Then add the script reference in the page as within the script section like this

@section scripts{


@Scripts.Render(“~/bundles/jqueryval”)

}

       4. Make sure you have controls place inside a form.

Handling validation in AJAX calls

When using server side post back in ASP.Net MVC validation works smooth. But for example if you want to invoke some AJAXified request on any button click and wanted to know if the form is validated or not you can add a code like this

$(‘#Save’).click(function (e) {


var $val = $(this).parents(‘form’);


if (!($val.valid()))


return
false;


else alert(‘form have no errors’);

}

Hope this helps!    

Sync Calendar Events using CALDAV in C#

In this post I will walk you through the steps of reading calendar events from CALDAV supported servers. Yahoo, Google, etc. supports CALDAV

What is CALDAV?

CALDAV is an internet standard allowing client to access scheduling information on remote server. It’s an extension of WebDAV which is a HTTP-based protocol for data manipulation. The protocol is defined by RFC 4791. As it’s an extension to WEBDAV protocol it uses HTTP verbs to manipulate calendar events some of them mostly used are PROPFIND, SEARCH, etc.

Background Information

  1. Every server has a separate URI to access calendar events.

Yahoo: https://caldav.calendar.yahoo.com/dav/user_name/Calendar/calendar_name/

Google: https://www.google.com/calendar/dav/user_name/events/

  1. Each Calendar folder is a collection and contains many calendar events. Each calendar event is a file and ended with .ics extension. .ics is well understood by many clients and you can easily export data from .ics to local client application.

How to Program

Now let’s see how to write a code to call Yahoo calendar events

  1. First of all create a new project in Microsoft Visual C# .NET
  2. Add reference to DDay.iCal library from Nuget Package manager console. This library will be used to read .ics files and read information about each event.
  3. Write below code to retrieve calendar event on any click event.

     


    In the above code snippet you have to configure your user name, password and modify the calendar URI depending on your calendarname and username.

If you see the code, I specified a content string which contains the request that I am sending it to the server. CALDAV have specific request formats which you can study here

ExecuteMethod is a helper method that sends request to the server and returns the response stream. Once I get the response stream I load the XML document and read the InnerXml of the file to get the complete XML. Then I parse the xml document and search for DAV:href element that contains the calendar event file (.ics) information. Once I get the list of .ics file paths, I call DownloadICS helper method to get the complete event information.

Helper Methods
Following are the helper method that performs specific operations. Please write these in your code to compile the project.

DownloadICS – Downloads .ics files


 

ExecuteMethod: Request calendar and returns response stream


Packt 2000th book Campaign

In the past, I have done few book reviews offered by Packt publishing and found that they have good set of technology related books.

Recently, they have launched an offer in which Packt is giving all its customers a chance to enjoy their books by giving them a free e-book copy for every purchase. This offer is valid from 18th March till 26th March 2014. People who are fond of reading technology related books must check here

 

Certificate error when deploying WCF Azure Service

February 25, 2014 Leave a comment

Last night I was working on some Azure WCF Service and while deploying on the Windows Azure Platform, I continuously faced error that “The certificate with thumbprint was not found in windows azure”. It was a simple WCF service based on BasicHttpBinding and has few operation contracts.

After doing deep research I found that while packaging a service from Package Windows Azure Application window, if you select “Enable Remote Desktop for all roles” or “Enable Remote Debugger for all roles” it expect to have certificates uploaded on azure portal and you should have specified the exact thumbprint in the Certificates section from properties window. Otherwise your deployment does not succeed.

Therefore, I succeeded disabling these two checks while creating a package and also made sure that there were no <certificates></certificates> tags inside service definition (.csdef) file and service configuration (.cscfg) file.

Hope this helps!

Reviewed Book “ASP.NET Web API: Build RESTful web applications and services on the .NET framework” by JoyDip Kanjilal

February 13, 2014 Leave a comment

I have gotten this opportunity to review the book named ‘ASP.NET Web API: Build RESTful web applications and services on the .NET framework‘ from Packt (UK based publishing company specializing in focused IT books).

Following is a review I made for this book

This book is very good to study the concepts of RESTful applications, SOA and ROA. Joydip have used different Microsoft technologies to showcase these terms. However, I found less information related to Web API which is the title of book and few topics like formatters, bindings and self-hosting web APIs are missing. I think there should be some chapter detailing the basic and advanced features of Web API that helps the reader to gain complete information on Web API.

Link to book page: http://www.packtpub.com/aspnet-web-api-build-restful-web-applications-services-on-the-dotnet-framework/book?utm_source=Book&utm_medium=mention.com&utm_campaign=Book_mention

Adding Queryable Support to ASP.NET Web API Controller Action Methods

January 18, 2014 Leave a comment

In this article I will show that how we can make our Web API methods queryable so the user can apply query operators and expressions to filter data.

We will use OData library for ASP.NET Web API that have the [Queryable] attribute provided, which facilitates in issuing queries.

1. Create ASP.Net Web API Project

2. Add sample model class which defines properties

3. In this example, I have created a Session class as follows

4. Now add a SessionController which will contain Get, Post, Put, Delete methods for CRUD operations.

5. It will create an empty controller. Now we will specify Get method and return session list as queryable.

6. Now add OData reference from Nuget Package Manager by searching as web api odata and click Install on Microsoft ASP.NET Web API 2 OData

7. Once you install, It will ask you to accept the license agreement, click I Accept and proceed

8. Now add [Queryable] attribute on GetSession method.

That’s it, build the solution and test.

9. Open fiddler and select GET HTTP Method and navigate to the URL i.e. http://[youraddress:port]/api/Session

10. Once you hit the above URI it will show you the complete session list in JSON format as follows

11. Now you can apply query operators on your request and filter data

Following are some query operators you can use to issue queries

$top=n: Returns only the first n entities in an entity set (or in Atom terms, the first n entries in a feed).

$skip=n: Skips the first n entities in an entity set. Using this option lets a client retrieve a series of distinct pages on subsequent requests.

$format: Determines whether data should be returned in JSON or the XML-based Atom/AtomPub format. (The default is Atom/AtomPub.)

$orderby=: Orders results, in ascending or descending order, by the value of one or more properties in those results.

$filter=: Returns only entities that match the specified expression.

$select=: Returns only the specified properties in an entity.

$inlinecount: Returns the server computed count of the number of entries produced by the query request.

Example

To select top 2, my URI would be like http://[youraddress:portNo[/api/Session?$top=2

Result:

Creating Custom Formatter in ASP.NET Web API for specific formatted response

January 4, 2014 Leave a comment

In this article I will show you how to create a custom formatter in ASP.Net Web API to send formatted response.

Before diving into deep, let me give you a quick introduction to formatters

Formatters in ASP .NET Web API plays an important role, when the request comes to the server, depending on the media-type, determines which formatter has to be used to parse the request and assemble the data into appropriate format as response. In ASP.Net Web API when the request is made by the user, Web API framework checks if it is Simple Type or a Complex Type. All primitive types like string, integers are simple types and by default ASP.Net Web API read those values from URI and uses Model binding. On the other hand for complex types, ASP.Net WEB API framework read it from request body by default (the behavior can be overridden) an depending on the content-type load specific formatter from the list of formatters available in HttpConfiguration list.

When you are creating a custom formatter in ASP.Net Web API, you have two options one is when the request is arrived on server and you want to return the data in specific format or when the request arrives and you want to read/parse the data in specific format.

In this example, we will see how you can return the response in PSV i.e. pipe separated value format.

Create a class that should be derived from BufferedMediaTypeFormatter or MediaTypeFormatter.

The difference is

  • MediaTypeFormatter – This class uses asynchronous read and write methods.
  • BufferedMediaTypeFormatter – This class derives from MediaTypeFormatter but wraps the asynchronous read/write methods inside synchronous methods. Deriving from BufferedMediaTypeFormatter is simpler, because there is no asynchronous code, but it also means the calling thread can block during I/O

In the example, we will use BufferedMediaTypeFormatter 

Following are the methods available in BufferedMediaTypeFormatter class

// Summary:


// Represents a helper class to allow a synchronous formatter on top of the


// asynchronous formatter infrastructure.


public
abstract
class
BufferedMediaTypeFormatter : MediaTypeFormatter

{


// Summary:


// Initializes a new instance of the System.Net.Http.Formatting.BufferedMediaTypeFormatter


// class.


protected BufferedMediaTypeFormatter();

 


// Summary:


// Gets or sets the suggested size of buffer to use with streams in bytes.


//


// Returns:


// The suggested size of buffer to use with streams in bytes.


public
int BufferSize { get; set; }

 


// Summary:


// Reads synchronously from the buffered stream.


//


// Parameters:


// type:


// The type of the object to deserialize.


//


// readStream:


// The stream from which to read


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


//


// formatterLogger:


// The System.Net.Http.Formatting.IFormatterLogger to log events to.


//


// Returns:


// An object of the given type.


public
virtual
object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger);


//


// Summary:


// Reads asynchronously from the buffered stream.


//


// Parameters:


// type:


// The type of the object to deserialize.


//


// readStream:


// The stream from which to read.


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


//


// formatterLogger:


// The System.Net.Http.Formatting.IFormatterLogger to log events to.


//


// Returns:


// A task object representing the asynchronous operation.


public
override
sealed
Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger);


//


// Summary:


// Writes synchronously to the buffered stream.


//


// Parameters:


// type:


// The type of the object to serialize.


//


// value:


// The object value to write. Can be null.


//


// writeStream:


// The stream to which to write.


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


public
virtual
void WriteToStream(Type type, object value, Stream writeStream, HttpContent content);


//


// Summary:


// Writes asynchronously to the buffered stream.


//


// Parameters:


// type:


// The type of the object to serialize.


//


// value:


// The object value to write. It may be null.


//


// writeStream:


// The stream to which to write.


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


//


// transportContext:


// The transport context.


//


// Returns:


// A task object representing the asynchronous operation.


public
override
sealed
Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext);

}

 

When we derive our custom formatter class from BufferedMediaTypeFormatter class we have to override following methods.

 

public
override
bool CanWriteType(Type type)

 

public
override
void WriteToStream(Type type, object value, System.IO.Stream stream, System.Net.Http.HttpContent content)

 

We can put some logic inside CanWriteType method that checks the type and return true or false. If the resultant value is true the framework calls WriteToStream method otherwise the WriteToStream method won’t be called.

Here is the complete code of custom formatter.


public
class
PsvFormatter : BufferedMediaTypeFormatter

{


public PsvFormatter()

{

SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue(“text/pipe”));

 

}


public
override
bool CanWriteType(Type type)

{


if (type == typeof(Session))

{


return
true;

}


return
false;

}

 


public
override
void WriteToStream(Type type, object value, System.IO.Stream stream, System.Net.Http.HttpContent content)

{


using (var writer = new
StreamWriter(stream))

{

 


var singleSession = value as
Session;


if (singleSession == null)

{


throw
new
InvalidOperationException(“Cannot serialize type”);

}

WriteItem(singleSession, writer);

}

stream.Close();

 

}

 


private
void WriteItem(Session session, StreamWriter writer)

{

writer.WriteLine(“{0}|{1}|{2}|{3}”, session.Id,

session.SessionName, session.SessionDateTime, session.Place);

}

 

}

 

In the above code snippet, if you see the constructor I have added the Media type header value in the SupportedMediaTypes list which will be used to pass in the request header information. While invoking WEB API method you can pass text/pipe as ACCEPT header attribute.

In the CanWriteType method I am checking if the type of the object which I am returning is of type Session. In my code example I have a Session whose structure is as follows.

public
class
Session

{


public
int Id { set; get; }


public
string SessionName { set; get; }


public
DateTime SessionDateTime { set; get; }


public
string Place { set; get; }

}

 

In the WriteToStream method I am using the stream writer and writing the object as pipe separated string.

Now in the DataController which is the Web API controller, I have a Get method which fetches the session object from database. After fetching the session object from database, web API framework calls CanWriteType and WriteToStream method and parse the object into Pipe separted string and send that string as the response.

public
class
DataController : ApiController

{


public
Session Get()

{


return repository.All<Session>().Where(i => i.Id == 3).First();

}

}

Using fiddler, I made a request to my data controller and passed text/pipe as ACCEPT attribute this tells the framework that the return response should be text/pipe. Web API framework checks the formatter and uses my custom formatter to serialize the response in pipe separated string.


And the response is here


You can see how easy it is to implement custom formatter in ASP.Net WEB API and in the next series of article I will blog a post about handling custom content type requests in ASP.Net Web API

Follow

Get every new post delivered to your Inbox.

Join 51 other followers

%d bloggers like this: