Using Highcharts JavaScript Library

by Jaz 27. November 2011 15:14

There are some great JavaScript graph libraries out there and one that’s recently come to my attention is Highcharts.com which is compatible with both the jQuery and Mootools frameworks. To get started point your browser here where you can download all the files you need including examples. Highcharts features include slick tooltips to reference points on your charts, it’s compatible with all standard web browsers, the setup for a graph as demonstrated below is simple and uses the JSON data type, there are also multiple types of graph type, from line, spline, area, areaspline, column, bar, pie and scatter chart.

graph

The Code

Here’s how to setup a simple chart. you need to include the jQuery framework as well as the highcharts.js file and excanvas.js file for IE users which you’ll get in the download from Highcharts. once you’ve got that setup simply paste this into your document head, and create a div with the id ‘graphDiv’, this is where the graph will render to. Note in the first few lines of setup code at the top of the script we specify this along with the chart type. In this case we’re using a bar chart. Below that we have the setup title parameter which is the main label for the graph along with the labels for the x and y axis.

You should be left with a graph as shown below.

HighCharts Fruit Chart

01
$(document).ready(function() {

02
var chart1 = new Highcharts.Chart({

03
chart: {

04
renderTo: 'graphDiv',

05
defaultSeriesType: 'bar'

06
},

07
title: {

08
text: 'Fruit Consumption'

09
},

10
xAxis: {

11
categories: ['Apples', 'Bananas', 'Oranges']

12
},

13
yAxis: {

14
title: {

15
text: 'Fruit eaten'

16
}

17
},

18
series: [{

19
name: 'Anne',

20
data: [1, 0, 4]

21
}, {

22
name: 'Martin',

23
data: [5, 7, 3]

24
}]

25
});

26
});

NOTE: the demo below is not of the code above. If you want to play around with the code for the demo you can simply copy the source from your web browser whilst viewing the demo

original article at:http://papermashup.com

Tags: ,

jquery | HighCharts

Knockout .JS:build dynamic JavaScript UIs

by Jaz 27. November 2011 15:05

Speakers: Steve Sanderson

Knockout.js 1.2.0 released

Posted on April 20, 2011

Earlier today I published the final 1.2.0 build of knockout.js. This is a big release with stacks of new goodness since 1.1.2:

  • Changed the license to MIT (more permissive than the previous license, MS-PL)
  • Added useful new bindings: event, attr, html
  • Enhanced some existing bindings: options, checked
  • Enhanced templating features (now supports jquery.tmpl 1.0.0pre as well as previous versions, template polymorphism, passing additional data via options)
  • Various performance improvements (e.g., now precompiles and caches templates, and ensures all data/subscriptions associated with DOM elements are cleaned immediately when those elements are removed) plus bugfixes
  • Better compilation style (ensures Closure Compiler no longer adds any extra variables to global namespace)
  • Various new extensibility points requested by plugin authors
  • Minor syntactical improvements (e.g., added zero-arg constructor for observable arrays)
  • All documentation updated to match 1.2.0

Thanks very much to the many people who have contributed ideas, pull requests, bug reports, and support to make this release possible! I’m really enjoying the community that’s growing around this.

Hang on, what’s Knockout.js?

In case you’ve never heard of it, here’s tekmaven’s explaination: Smile

image

(By the way, for Visual Studio developers: Install-Package knockoutjs)

More specifically, Knockout is a JavaScript library for building rich, responsive user interfaces. It uses automatic dependency tracking and declarative bindings to update your UI whenever your data model changes, letting you cleanly structure your code around the MVVM pattern.

No, that’s just marketing blather… show me something real

OK then, to learn more:

 

Video at: http://channel9.msdn.com/Events/MIX/MIX11/FRM08

Tags: , ,

jquery | MVVM | asp.net | knockout.js

Silverlight toolkit Accordion control tutorial

by Jaz 26. November 2011 01:37

The Accordion control was developed by Ruurd Boeke, a member of the Silverlight team. He’s created a great set of guides on the control, I invite you to check them out:

  • Part 1 – accordion
  • Part 2 – accordion item
  • Part 3 – expandable content control
  • Part 4 – retemplating, real world example
  • Part 5 – accordion button

To get the control, download and install the latest Silverlight Toolkit release. The Accordion control is available for both Silverlight 2 and Silverlight 3 development.

Tags:

silverlight

Multiple-Constructor Injection using Unity IOC

by Jaz 26. November 2011 01:27
Unity, and the dependency injection design pattern itself, really becomes useful is when the container generates instances of objects that have dependencies. It can automatically resolve the dependent object types required by the objects it creates, generate the appropriate concrete types, and then inject these concrete instances into the object it is creating.

The following shows a schematic view of the dependency injection process that Unity can accomplish.

Cc816062.9444d795-6e6e-4d23-ab27-77467e20123a(en-us,MSDN.10)

The following are the types of injection together with descriptions of how they are applied using Unity:

  • Constructor injection. This type of injection occurs automatically. When you create an instance of an object using the Unity container, it will automatically detect the constructor with the largest number of parameters and execute this, generating instances of each object defined in the constructor parameters. It resolves each parameter type through the container, applying any registrations or mappings for that type. If you want to specify a particular constructor for Unity to use, you can add the InjectionConstructor attribute to that constructor in the target class.
  • Property (setter) injection. This type of injection is optional. You can add the Dependency attribute to any property declarations that you want Unity to resolve through the container. Unity will resolve that property type and set the value of the property to an instance of the resolved type.
  • Method call injection. This type of injection is also optional. You can add the InjectionMethod attribute to any method declarations where you want Unity to resolve the method parameters through the container. Unity will resolve each parameter type and set the value of that parameter to an instance of the resolved type, and then it will execute the method. Method call injection is useful if you need to execute some type of initialization method within the target object.

Via http://msdn.microsoft.com/en-us/library/cc816062.aspx

Multiple-Constructor Injection Using an Attribute

When a target class contains more than one constructor with the same number of parameters, you must apply the InjectionConstructor attribute to the constructor that the Unity container will use to indicate which constructor the container should use. As with automatic constructor injection, you can specify the constructor parameters as a concrete type, or you can specify an interface or base class for which the Unity container contains a registered mapping.

e.g.

public class MyObject {

public MyObject(SomeOtherClass myObjA)   { …  }

[InjectionConstructor]
public MyObject(MyDependentClass myObjB)  {  … }
}

In your run-time code, use the Resolve method of the container to create an instance of the target class. The Unity container will instantiate the dependent concrete class defined in the attributed constructor and inject it into the target class. For example, the following code shows how you can instantiate the example target class named MyObject containing an attributed constructor that has a dependency on a class named MyDependentClass.

e.g.

IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve<MyObject>();
How Unity Resolves Target Constructors and Parameters

When a target class contains more than one constructor, Unity will use the one that has the InjectionConstructor attribute applied. If there is more than one constructor, and none carries the InjectionConstructor attribute, Unity will use the constructor with the most parameters. If there is more than one such constructor (more than one of the “longest” with the same number of parameters), Unity will raise an exception.

Constructor Injection with Existing Objects

If you use the RegisterInstance method to register an existing object, constructor injection does not take place on that object because it has already been created outside of the influence of the Unity container. Even if you call the BuildUp method of the container and pass it the existing object, constructor injection will never take place because the constructor will not execute. Instead, mark the constructor parameter containing the object you want to inject with the Dependency attribute to force property injection to take place on that object, and then call the BuildUp method. This is a similar process to property (setter) injection. It ensures that the dependent object can generate any dependent objects it requires. For more details, see Annotating Objects for Property (Setter) Injection.

Via http://msdn.microsoft.com/en-us/library/cc440940.aspx

Tags: , ,

IoC | Unity | Dependency Injection

Setup SVN(subversion) Local Repository – Step by Step

by Jaz 26. November 2011 01:23
0. FAQ First

Q: I heard that Subversion is an Apache extension? Does this mean I have to set up Apache to use Subversion?

A: The short answer: no. The long answer: if you just want to access a repository, then you only need to build a Subversion client. If you want to host a networked repository, then you need to set up either Apache2 or an “svnserve” server.

for more faq: http://subversion.tigris.org/faq.html

1. Creating The Repository With TortoiseSVN 

  1. Open the windows explorer
  2. Create a new folder and name it e.g. SVNRepository
  3. Right-click on the newly created folder and select TortoiseSVN → Create Repository here….

A repository is then created inside the new folder. Don’t edit those files yourself!!!. If you get any errors make sure that the folder is empty and not write protected.

2. Local Access to the Repository

To access your local repository you need the path to that folder. Just remember that Subversion expects all repository paths in the form file:///C:/SVNRepository/. Note the use of forward slashes throughout.

To access a repository located on a network share you can either use drive mapping, or you can use the UNC path. For UNC paths, the form is file://ServerName/path/to/repos/. Note that there are only 2 leading slashes here.

3. Repository Layout

Before you import your data into the repository you should first think about how you want to organize your data. If you use one of the recommended layouts you will later have it much easier.

There are some standard, recommended ways to organize a repository. Most people create a trunk directory to hold the “main line” of development, a branches directory to contain branch copies, and a tags directory to contain tag copies. If a repository holds only one project, then often people create these top-level directories:

/trunk

/branches

/tags

If a repository contains multiple projects, people often index their layout by branch:

/trunk/paint

/trunk/calc

/branches/paint

/branches/calc

/tags/paint

/tags/calc

…or by project:

/paint/trunk

/paint/branches

/paint/tags

/calc/trunk

/calc/branches

/calc/tags

Indexing by project makes sense if the projects are not closely related and each one is checked out individually. For related projects where you may want to check out all projects in one go, or where the projects are all tied together in a single distribution package, it is often better to index by branch. This way you have only one trunk to checkout, and the relationships between the sub-projects is more easily visible.

So if you haven’t already created a basic folder structure inside your repository you should do that now:

  1. create a new empty folder on your hard drive (NOT INSIDE THE Already created repository – SVNRepository)

  2. create your desired top-level folder structure inside that folder – don’t put any files in it yet!

  3. import this structure into the repository via a right click on the folder and selecting TortoiseSVN → Import… This will import your temp folder into the repository root to create the basic repository layout.

Note that the name of the folder you are importing does not appear in the repository, only its contents. For example, create the following folder structure:

C:\Temp\New\trunk
C:\Temp\New\branches
C:\Temp\New\tags

Import Layout C:\Temp\New into the repository root, which will then look like this:

/trunk
/branches
/tags

You can also use the repository browser to create new folders directly in the repository.

4. Import Content

Before you import your project into a repository you should:

  1. Remove all files which are not needed to build the project (temporary files, files which are generated by a compiler e.g. *.obj, compiled binaries, …)

  2. Organize the files in folders and subfolders. Although it is possible to rename/move files later it is highly recommended to get your project’s structure straight before importing!

Now select the top-level folder of your project directory structure in the windows explorer and right click to open the context menu. Select the command TortoiseSVN → Import which brings up a dialog box for you to enter the URL of the repository into which you want to import your project. 

As soon as you press OK TortoiseSVN imports the complete directory tree including all files into the repository. As before, the name of the folder you import does not appear in the repository, only the folder contents. The project is now stored in the repository under version control. Please note that the folder you imported is NOT under version control! To get a version-controlled working copy you need to do a Checkout of the version you just imported.

Tags:

SVN

Using The Silverlight DataGrid with MVVM

by Jaz 26. November 2011 01:20

image_thumb24

View Model and the Silverlight DataGrid

The Silverlight DataGrid is a powerful control that allows inline editing, paging, sorting, and drag and drop re-ordering of columns. It can be challenging to understand when using normal code behind techniques, but sometimes downright baffling when using View Model / MVVM style programming.

In the following examples, we will not directly reference the DataGrid in the View Model. The code we will create can be consumed by any collection control such as a ListBox.

It’s Not The DataGrid You Want to Manipulate – It’s the Collection Bound To The DataGrid

 

For more -> Using The Silverlight DataGrid with View Model / MVVM – CodeProject

In conclusion – View Model – Less Code, Really!

Hopefully you can see that View Model is not hard at all. It really is not complicated once you see how it is done. Expression Blend was designed to work in "View Model Style", so you should have an easier time using Expression Blend when you use this simple pattern.

While it may seem easier to implement a DataGrid using code behind, you will usually find that you will need to create a lot of code to locate and modify values and properties in the DataGrid.

Controls such as the DataGrid are designed to Bind to collections. View Model is designed to implement binding. It’s the Binding that saves you code. Once a Binding is created, it will perform functionality automatically. you do not have to explicitly write code for each piece of functionality. Most importantly, you will Bind to, and gather parameters, directly from the DataGrid element that you are ultimately concerned with, rather than hooking into an event and then hunting for the real value you are looking for.

Furthermore, you will realize that a lot of programmatic functionality, is best implemented, on the underlying data source not the DataGrid it’s self.

Also note, this example uses standard web services, you can easily use WCF or WCF RIA Services. The View and the View Model would still be exactly the same.

Tags: , , ,

MVVM | LINQ | silverlight

Microsoft Unity IoC(inversion of control) in 30 seconds

by Jaz 26. November 2011 01:16
Object Factory
Container-Configured Registration of Types

As an example of using the overloads of the RegisterType and Resolve methods, the following code registers a mapping for an interface named IMyService, and specifies that the container should return an instance of the CustomerService class (which implements the IMyService interface).

IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType<ILoggingService, LoggingService>();
ILoggingService myServiceInstance = myContainer.Resolve<ILoggingService>();
Container-Configured Registration of Existing Object Instances

As an example of using the overloads of the RegisterInstance and Resolve methods, the following code registers an existing instance of a class named LoggingService that implements the interface IMyService and then retrieves that instance.

IUnityContainer myContainer = new UnityContainer();
LoggingService myExistingObject = new LoggingService();
myContainer.RegisterInstance<ILoggingService>(myExistingObject);
ILoggingService myServiceInstance = myContainer.Resolve<ILoggingService>();
Constructor Injection

As an example of constructor injection, if a class that developers instantiate using the Resolve method of the Unity container has a constructor that defines one or more dependencies on other classes, the Unity container will automatically create the dependent object instance specified in parameters of the constructor. For example, the following code shows a class named CustomerService that has a dependency on a class named ILoggingService.

public class CustomerService
{
  public CustomerService(ILoggingService myServiceInstance)
  {
    // work with the dependent instance
    myServiceInstance.WriteToLog("SomeValue");
  }
}
Property (Setter) Injection

In addition to constructor injection, described earlier, the Unity Application Block supports property and method call injection. The following code demonstrates property injection. A class named ProductService exposes as a property a reference to an instance of another class named SupplierData (not defined in the following code). To force dependency injection of the dependent object, developers must apply the Dependency attribute to the property declaration, as shown in the following code.

public class ProductService
{
  private ISupplierData supplier;

  [Dependency]
  public ISupplierData SupplierDetails
  {
    get { return supplier; }
    set { supplier = value; }
  }
}
Highlights of the Unity Application Block

The Unity Application Block includes the following features:

  • It provides a mechanism for building (or assembling) instances of objects, which may contain other dependent object instances.
  • It exposes RegisterType methods that support configuring the container with type mappings and objects (including singleton instances) and Resolve methods that return instances of built objects that can contain any dependent objects.
  • It provides inversion of control (IoC) functionality by allowing injection of preconfigured objects into classes built by the application block. Developers can specify an interface or class type in the constructor (constructor injection), or apply attributes to properties and methods to initiate property injection and method call injection.
  • It supports a hierarchy for containers. A container may have child container(s), allowing object location queries to pass from the child out through the parent container(s).
  • It can read configuration information from standard configuration systems, such as XML files, and use it to configure the container.
  • It makes no demands on the object class definition. There is no requirement to apply attributes to classes (except when using property or method call injection), and there are no limitations on the class declaration.
  • It supports custom container extensions that developers can implement; for example, methods to allow additional object construction and container features such as caching.

Tags: , ,

Unity | IoC | Dependency Injection

Windows Phone 7-Using Authentication Service With Membership/Role Provider

by Jaz 25. November 2011 21:01

ComputerThose of you who have been building ASP.NET applications for a while now are no doubt familiar with the provider model, which includes provider abstractions for membership (authentication), roles (authorization), profiles (user data), and session state. These providers make it incredibly easy to provide a secure framework for your application. In fact, with an ASP.NET application template right out of the box, you can have a fully functioning authenticated, secure website in minutes.

What a lot of people have less familiarity with is the notion of provider services. You can actually create a WCF service head that sits on top of the ASP.NET membership system. This allows client applications to authenticate against your ASP.NET website using exactly the same authentication scheme that your users use. This means that a user who has access to your website should also be able to have access to the client application seamlessly.

To see how this works, create yourself a new ASP.NET MVC app (you can do this with a regular ASP.NET app, but I just happened to use MVC). Before doing anything, run the app, go to the “Log On” area, register yourself as a user and then quit the app. If you’ve got SQL Express installed properly and everything else is in order, your app now knows who you are.

Next, add a new WCF service to this application (call it Authentication.svc). Delete the files Authentication.svc.cs and the IAuthentication.cs. Open up the Authentication.svc file and replace it’s contents entirely with the following:

  1: <%@ ServiceHost Language="C#"
  2:     Service="System.Web.ApplicationServices.AuthenticationService" %>
 
Note here that there’s no code-behind. All we’re doing is exposing a service that is 
already part of the ASP.NET framework at a specific endpoint. You’re not quite ready 
yet – we have to make this service ASP.NET compatible, so open up your Web.config file 
and make sure that your system.servicemodel section looks like this:
 
  1: <system.serviceModel>
  2:  <services>
  3:  <service name="System.Web.ApplicationServices.AuthenticationService"
  4: behaviorConfiguration="AuthenticationServiceBehaviors">
  5:  <endpoint contract="System.Web.ApplicationServices.AuthenticationService"
  6:      binding="basicHttpBinding" />
  7:  </service>
  8:  <service name="Wp7AspNetMembership.HelloService"
  9:      behaviorConfiguration="AuthenticationServiceBehaviors">
 10:  <endpoint
 11:      contract="Wp7AspNetMembership.IHelloService"
 12:      binding="basicHttpBinding"/>
 13:  </service>
 14:  </services>
 15:  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
 16:      multipleSiteBindingsEnabled="true" />
 17:  <behaviors>
 18:  <serviceBehaviors>
 19:  <behavior name="AuthenticationServiceBehaviors">
 20:  <serviceMetadata httpGetEnabled="true" />
 21:  </behavior>
 22:  <behavior name="">
 23:  <serviceMetadata httpGetEnabled="true" />
 24:  <serviceDebug includeExceptionDetailInFaults="false" />
 25:  </behavior>
 26:  </serviceBehaviors>
 27:  </behaviors>
 28:  </system.serviceModel>
 29:  
 30:  <system.web.extensions>
 31:  <scripting>
 32:  <webServices>
 33:  <authenticationService enabled="true" requireSSL="false"/>
 34:  </webServices>
 35:  </scripting>
 36:  </system.web.extensions>

 

What’s going on in this Web.config file is pretty interesting. First, we’re exposing Authentication.svc and HelloService.svc (not yet created) over HTTP, with metadata allowed, with ASP.NET compatibility enabled. We’ve also used the system.web.extensions element to indicate that the authentication service is being enabled. In a production environment, you would set requireSSL to true.

At this point, you should be able to hit the URL /Authentication.svc and see the standard metadata page. Now let’s create HelloService.svc by creating a standard WCF service. Change the interface so it only has a single method called HelloWorld() that returns a string. The following is the implementation of HelloService.svc.cs:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Runtime.Serialization;
  5: using System.ServiceModel;
  6: using System.Text;
  7: using System.Web;
  8: using System.ServiceModel.Activation;
  9:  
 10: namespace MvcApplication1
 11: {
 12:  [AspNetCompatibilityRequirements(
 13:     RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
 14:  public class HelloService : IHelloService
 15:  {
 16:   public string HelloWorld()
 17:   {
 18:    if (HttpContext.Current.User.Identity.IsAuthenticated)
 19:      return HttpContext.Current.User.Identity.Name;
 20:    else
 21:      return "Unauthenticated Person";
 22:   }
 23:  }
 24: }

This is a pretty simple service. Just pretend that instead of returning the name of the authenticated user, we’re actually performing some vital business function that requires a valid user context.

Now, we can get to the good stuff : the WP7 application :) In this WP7 application we’re going to create a login form, submit user credentials over the wire, get validation results and, if the user was authenticated, we’re going to call the HelloWorld() method with a validated, secure context – all of this with an incredibly small amount of work on the part of the WP7 client.

Add a new WP7 application (just the stock one, not the list view) to the solution, I called mine TestMembershipClient but you can pick whatever you like. Add service references to Authentication.svc and to HelloWorld.svc (I named the reference namespaces MvcWebAppReference for authentication and AspNetMvcRealReference for the service that simulates doing real work).

On your main page, drop a couple text block labels, two text boxes, and a submit button. When you run the app at this point, it should look like this screenshot:

wp7_aspnetauth_1

Now rig up a click handler for the submit button with code that looks like this:

  1: private void LoginButton_Click(object sender, RoutedEventArgs e)
  2: {
  3:  MvcWebAppReference.AuthenticationServiceClient authService =
  4:    new MvcWebAppReference.AuthenticationServiceClient();
  5:  cc = new CookieContainer();
  6:  authService.CookieContainer = cc;
  7:  authService.LoginCompleted +=
  8:    new EventHandler<MvcWebAppReference.LoginCompletedEventArgs>(
  9:  authService_LoginCompleted);
 10:  authService.LoginAsync(UsernameBox.Text, PasswordBox.Text, "", true);
 11: }
 12:  
 13: void authService_LoginCompleted(object sender,
 14:  MvcWebAppReference.LoginCompletedEventArgs e)
 15: {
 16:  if (e.Error != null)
 17:  {
 18:  MessageBox.Show("Login failed, you Jackwagon.");
 19:  }
 20:  else
 21:  {
 22:    AspNetMvcRealReference.HelloServiceClient helloService =
 23:     new AspNetMvcRealReference.HelloServiceClient();
 24:    helloService.CookieContainer = cc;
 25:    helloService.HelloWorldCompleted +=
 26:    new EventHandler<AspNetMvcRealReference.HelloWorldCompletedEventArgs>(
 27:      helloService_HelloWorldCompleted);
 28:    helloService.HelloWorldAsync();
 29:  }
 30: }
 31:  
 32: void helloService_HelloWorldCompleted(object sender,
 33:  AspNetMvcRealReference.HelloWorldCompletedEventArgs e)
 34: {
 35:  MessageBox.Show("You're logged in, results from svc: " + e.Result);
 36: }

Most of this is pretty straightforward. When the user clicks the submit button, it calls the LoginAsync method on the membership service (remember that all service calls in Silverlight are asynchronous). When we get the results of that call, we either tell the user that their login has failed, or we invoke the HelloWorld method (also asynchronously). When the hello world method comes back from the server, we display the results of the execution in a message box that looks like the one in the screenshot below:

wp7_aspnetauth_2

One thing to take very careful note of is the CookieContainer. Because we’re using two different proxies: 1 to talk to the authentication service and 1 to talk to the hello world service, we have to ensure that these two proxies are using the same cookie container so that the auth cookie can be used by subsequent method calls on other services. You can do this for an unlimited number of services that are on the same DNS domain, so long as they all share the same cookie container. To enable the use of cookie containers in WCF services in Silverlight (it’s disabled by default), you have to set the enableHttpCookieContainer property to true. in the binding element in the ServiceReferences.ClientConfig file.

On the surface you might not think this is all that big of a deal. You might also think this is difficult but, keep in mind that I provided a pretty detailed walkthrough. This whole thing only took me about 15 minutes to set up from start to finish once I’d figured out how the CookieContainer thing worked. So why bother with this?

Consider this: If you already have an ASP.NET application that is using the membership provider, role provider, and profile provider you can quickly, easily, and securely expose services to a mobile (WP7) client that allow that client to have secured, remote access to services exposed by that site. In short, any user of your existing web application can use their existing credentials to log in from their WP7 device and access any services you decide to make available.

ASP.NET provider services, coupled with WP7 and the fact that Silverlight has access to WCF client proxy generation, means you can very easily prep your site for a rich WP7 experience.

(reference:http://www.kotancode.com)

NEXT I WILL BE COMING UP WITH ARTICLE HAVING A CERTIFICATE BASED AUTHENTICATION FOR WCF BASED SERVICES.

Tags: , , ,

windows mobile | windows phone 7 | WCF | web services

ASP.NET MVC 3 – Remote Validation with jQuery

by Jaz 22. November 2011 00:29

Create below html document as a basic HTML form.

  1: <!DOCTYPE html>
  2: <html>
  3: <head>
  4:     <title>jquery validate</title>
  5:     <!-- javascript will come here -->
  6: </head>
  7: <body>
  8:     <form id="userform" action="/Create" method="post">
  9: 
 10:     <div><label for="FirstName">First name</label></div>
 11:     <div><input id="FirstName" name="FirstName" type="text"/></div>
 12: 
 13:     <div><label for="LastName">Last name</label></div>
 14:     <div><input id="LastName" name="LastName" type="text"/></div>
 15: 
 16:     <div><label for="Email">Email</label></div>
 17:     <div><input id="Email" name="Email" type="text"/></div>
 18: 
 19:     <div><input type="submit" value="Create" /></div>
 20:     </form>
 21: </body>
 22: </html>
 
And then add below javascript code between "head" tags of the HTML document. 
 
  1: <script src="/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
  2:     <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
  3:     <script type="text/javascript">
  4:         $(function () {
  5:             $("#userform").validate({
  6:                 rules: {
  7:                     FirstName: { required: true, maxlength: 64 },
  8:                     LastName: { required: true, maxlength: 64 },
  9:                     Email: { maxlength: 32,email:true, }
 10:                 }
 11:             });
 12:         });
 13: </script>

This code demonstrates a basic jQuery validation sample, jQuery Validate plugins validates the form before it submitted, if form is valid it submits the form, otherwise form doesn’t get submitted.

As you can see from the sample, basic idea of form validation in jQuery Validate plugin is defining rules in jQuery code and execute them.

But what we do if we need a validation rule that needs some data, business, any input from server side?

jQuery Validate plugin provides a remote validation rules for this kind of requirements. Basically it invokes a server endpoint in validation process and uses that response to decide forms validation.

In this scenario, say, we want to checks availability of email address, we will not validate the form if this email address already registered in our user database.

You just need to add “remote” attribute to validation rules in email for remote validation.

  1: <script src="/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
  2:     <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
  3:     <script type="text/javascript">
  4:         $(function () {
  5:             $("#userform").validate({
  6:                 rules: {
  7:                     FirstName: { required: true, maxlength: 64 },
  8:                     LastName: { required: true, maxlength: 64 },
  9:                     Email: { maxlength: 32,email:true, remote:"/users/checkemailexists" }
 10:                 }
 11:             });
 12:         });
 13: </script>
When jQuery Validate plugin validates our form it will call /users/checkemailexists endpoint with a 
querystring that contains current email input, jquery validates the form when we are typing, after 
each key press. In this sample jQuery know this field is an email input (email:true 
rule provides that) and it will not call remote endpoint until we enter a valid text for email 
pattern that jQuery checks.
 

if you change the rule like below it will first make remote call and validate the input against email regex pattern.

Email: { maxlength: 32, remote:"/users/checkemailexists", email:true}

For now, I haven’t created an endpoint for validation of email address so it returns and 404 Not Found error message and jQuery accepts it as invalid.

I want to move to ASP.NET MVC part and create that endpoint afterwards.

We will use ASP.NET Razor Page Engine to create all HTML outputs and validation logics.

First create a view model under the model folder in your ASP.NET MVC 3 project.

  1: using System.ComponentModel;
  2: using System.ComponentModel.DataAnnotations;
  3: using System.Web.Mvc;
  4: 
  5: namespace RemoteValidation.Models
  6: {
  7:     public class UserInfoViewModel
  8:     {
  9:         [Required, StringLength(20)]
 10:         [DisplayName("First name")]
 11:         public string FirstName { get; set; }
 12: 
 13:         [Required, StringLength(20)]
 14:         [DisplayName("Last name")]
 15:         public string LastName { get; set; }
 16: 
 17:         [Required]
 18:         [Remote("IsEmailAvailable", "User" /*points to UserController*/)]
 19:         public string Email { get; set; }
 20:     }
 21: }
As you can notice from above code snippet Remote attributes defines remote validation 
settings for Email property, it will call IsEmailAvailable action on UserController. 
We will pass this step for now, firstly we will create and endpoint named as “Create” 
under “UserController”. Create a ”UserController” class under controllers folder.
 
  1: namespace RemoteValidation.Controllers
  2: {
  3:     public class UserController : Controller
  4:     {
  5:         [HttpGet]  // GET: /User/Create
  6:         public ActionResult Create()
  7:         {
  8:             return View();
  9:         }
 10: 
 11:         [HttpPost]  // POST: /User/Create
 12:         public ActionResult Create(UserInfoViewModel userInfoViewModel)
 13:         {
 14:             // TODO: Add insert logic here
 15:             // Nothing is required for now, we are not focused on create part,
 16:             return RedirectToAction("Create");
 17:         }
 18:     }
 19: }
And now it’s time to create Razor view page, we will create a strongly-typed Razor 
view page for UserInfoViewModel model.
  1: @model RemoteValidation.Models.UserInfoViewModel
  2: @{
  3:     ViewBag.Title = "Create";
  4:     Layout = "~/Views/Shared/_Layout.cshtml";
  5: }
  6: <h2>
  7:     Create</h2>

8: <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"

type="text/javascript"></script>

9: <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"

type="text/javascript"></script>

 10: @using (Html.BeginForm())
 11: {
 12:     @Html.ValidationSummary(true)
 13:     <fieldset>
 14:         <legend>UserInfoViewModel</legend>
 15:         <div class="editor-label">
 16:             @Html.LabelFor(model => model.FirstName)
 17:         </div>
 18:         <div class="editor-field">
 19:             @Html.EditorFor(model => model.FirstName)
 20:             @Html.ValidationMessageFor(model => model.FirstName)
 21:         </div>
 22:         <div class="editor-label">
 23:             @Html.LabelFor(model => model.LastName)
 24:         </div>
 25:         <div class="editor-field">
 26:             @Html.EditorFor(model => model.LastName)
 27:             @Html.ValidationMessageFor(model => model.LastName)
 28:         </div>
 29:         <div class="editor-label">
 30:             @Html.LabelFor(model => model.Email)
 31:         </div>
 32:         <div class="editor-field">
 33:             @Html.EditorFor(model => model.Email)
 34:             @Html.ValidationMessageFor(model => model.Email)
 35:         </div>
 36:         <p>
 37:             <input type="submit" value="Create" />
 38:         </p>
 39:     </fieldset>
 40: }
ASP.NET MVC 3 support unobtrusive Javascript for jQuery validation plugin. 
To activate this 
you need to enable a setting from web config and add jquery.
validate.unobtrusive.min.js script file (obviously min part is optional) 
to your web page.
 
<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

Request is successfully made by jQuery Validate plugin, let’s create the action for remote validation.

I will create a basic repository for users and inject it to the controller and will create the controller method.

Let’s create repository interface and dummy in-memory repository.

 

  1: namespace RemoteValidation.Repositories
  2: {
  3:     public interface IUserRepository
  4:     {
  5:         bool EmailExists(string email);
  6:     }
  7: }
  8: 
  9: namespace RemoteValidation.Repositories
 10: {
 11:     public class InMemoryUserRepository : IUserRepository
 12:     {
 13:         public bool EmailExists(string email)
 14:         {
 15:             //dummy implementation for demo
 16:             //all emails are available except 'cengiz at cengizhan.com'
 17:             return email == "cengiz[@]cengizhan.com";
 18:         }
 19:     }
 20: }

InMemoryUserRepository.EmailExists will return false for all emails except one sample email address, my email address.

Now inject repository to controller and create controller action method.

  1: using System.Web.Mvc;
  2: using RemoteValidation.Models;
  3: using RemoteValidation.Repositories;
  4: 
  5: namespace RemoteValidation.Controllers
  6: {
  7:     public class UserController : Controller
  8:     {
  9:         private readonly IUserRepository userRepository;
 10: 
 11:         public UserController()
 12:             : this(new InMemoryUserRepository())
 13:         {
 14: 
 15:         }
 16: 
 17:         public UserController(IUserRepository userRepository)
 18:         {
 19:             this.userRepository = userRepository;
 20:         }
 21: 
 22:         public JsonResult IsEmailAvailable(string email)
 23:         {
 24:             if (!userRepository.EmailExists(email))
 25:                 return Json(true, JsonRequestBehavior.AllowGet);
 26: 
 27:             return Json("Email address in use", JsonRequestBehavior.AllowGet);
 28:         }
 29: 
 30:         [HttpGet]  // GET: /User/Create
 31:         public ActionResult Create()
 32:         {
 33:             return View();
 34:         }
 35: 
 36:         [HttpPost]  // POST: /User/Create
 37:         public ActionResult Create(UserInfoViewModel userInfoViewModel)
 38:         {
 39:             // TODO: Add insert logic here
 40:             return RedirectToAction("Create");
 41:         }
 42:     }
 43: }
IsEmailAvailable action methods will return validation  result, true in 
available case, error
 message in not available case.

quote from jQuery web page

The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead"to display as the error message.

It’s done. jQuery will call endpoint and get the JSON response from action method to decide validation. This how remote validation works in ASP.NET MVC. For more information about jQuery Validate plugin’s remote validation feature go to jQuery web site.

(oRIGINAL aRTICLE AT http://develoq.net)

Tags: , , ,

JSON | MVC | asp.net | jquery

Two Models in One View in MVC

by Jaz 12. November 2011 20:37

Often we bump into situations where we require more than one Model in our view.

So i have suggested the following solution

 

I have 2 Models

public class Person
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
}
public class Order
{
    public int OrderID { get; set; }
    public int OrderTotal { get; set; }
}

In order to access both models in Single view,we can create a ViewModel

public class MainModel
{ public
Person PersonModel{get; set;} public Order OrderModel{get; set;} }

then in View we can use

@model MainModel

@using(Html.BeginForm()) { @Html.EditorFor(x => x.PersonID) @Html.EditorFor(x => x.PersonName) @Html.EditorFor(x=>x.OrderID) @Html.EditorFor(x => x.OrderTotal) }

and later on if we need more views ,we can easily add to Main ViewModel.....

Tags: , ,

asp.net | MVC | MVVM

Powered by BlogEngine.NET 1.6.0.0 - FunkyGrunge Theme by n3o Web Designers

 

About Me

As a Senior freelancer software Developer,I spend a lot of time using shiny new technologies to solve business problems. I’m passionate about emerging technologies of all flavours and helping development teams use them practically and successfully. I remain very hands on and strongly believe practical competence is the key to designing quality software....!Gurjeet S.