Our Recommendation

Showing posts with label model. Show all posts
Showing posts with label model. Show all posts

Thursday, December 16, 2010

model jQuery with ASP.NET MVC (Weblogs @ ASP.NET)

In my three previous blogs, I showed how to use templates in your ASPX Web site.

Introduction to jQuery templates - tmpl() template(), tmplItem (jQuery) model - TemplatesjQuery {supported the tags}

Now, I am going to show a concrete example that you can use in your everyday work developing applications with ASP.NET MVC and jQuery.

In this example I'll use pubs database so I retrieves the values from the authors table. To access the data, I use the Entity Framework.

Say pass along every step of the scenario:

1. Create the new ASP.NET MVC Web application

2. Add the new view to the home folder but step select a master page and add the controller for your view

3 BODY code in the HTML code



Authors of pubs




As you can see in the body we do as a single tag H1 and a div with id authorsList where we will add the database.

4 Now I created the pubs model which is linked to the publication database, and I chose only the authors table in my EDMX model. You can use your own database.

5. Then, to create a JsonResult method will get the database data and serialize JSON string.

public JsonResult GetAuthors()
{
pubsEntities pubs = new pubsEntities();
authors of var = pubs.authors.ToList ();
return Json (authors, JsonRequestBehavior.AllowGet).
}

Therefore, I am creating an instance of the object of pubsEntities and get all the authors in the authors list. And then returning the list of the authors by JSON serialization in Json method. JsonRequestBehaviour.AllowGet parameter is used to GET the client queries are allowed. By default in ASP.NET MVC 2 get is not allowed by the security with JSON hijacking problem.

6. Then, to create AJAX jQuery function that calls the GetAuthors method. We will use jQuery method $.getJSON.

Once the web page is downloaded, the method will be called. The first parameter of $. getJSON() is the url string in our case, the method name. The second parameter (which, in the example, is the empty string) is the key value pairs will be send to the server, and the third function is the callback function or the result will be returned by the server.

Inside the callback function, we have code that makes the data model that has id # authorsTemplate and adds it to the element that has # authorsList.

7. The model of jQuery

As you can see, I have tags containing fields (au_lname, au_fname…, etc.) that corresponds to the table in EDMX model which is the same as in the database.

One thing more than noted here is that I printMessage function (state) which is called inside the tag of ${expression/function/field}.

Function printMessage

Therefore, if the State is "CA" impression "is the author of California" else "the author is not California"

HERE IS THE COMPLETE ASPX CODE



Sample database: jQuery templates


    

    



Authors of pubs



Thus, in the complete sample, you also have the CSS style I use for my page output.

Here's the final result displayed on the web page screen printing:

You can download the full source, including examples presented in my previous blog posts on jQuery templates and presentation PPT my last session, I got to the local .NET UG meeting at the following DOWNLOAD LINK.

Let me know your comments.

With respect,
Hajan

Tuesday, December 14, 2010

IBM modeling and tool for Java Garbage Collector (IBM) model

A tool that parses verbose GC trace analysis using Java heap and recommends key configurations based on the modelling of the pattern of use of java heap.

Posting date: April 12, 2005

Update: 19 October 2010
Version 4.0.3 fixes simultaneous generation policy Analyzer

Profile of your organization and Analysis Tool for IBM ® Java ™ Garbage Collector (PMAT) verbose GC trace analysis analyzes the use of Java heap and recommends key based on the java heap usage pattern modeling configurations.

When the JVM (Java virtual machine) cannot allocate an object of the current heap due to lack of space, an allocation fault memory occurs and the Garbage Collector is invoked. The first task of the Garbage Collector is to collect all waste that is located in the heap. This process begins when any thread calls the Garbage Collector, either as a result of failed allocation, either by a specific System.gc () call directly indirectly. The first step is to get all the locks required by the garbage collection process. This step ensures that other threads are suspended not while they hold critical locks. All other threads are then suspended. Garbage collection can then begin. It occurs in three phases: mark, scanning and compaction (optional).

Verbose GC is a command line option that may provide for the fair market value at the time of startup. The format is: -verbose: gc or -verbosegc. This option toggles on a substantial trace each garbage collection cycle. The format of the generated information is not intended and therefore varies between different platforms and releases.

This trace is expected to see the use of crude stockpiles in each garbage collection cycle operation. For example, can monitor output to see changes in the free heap space and space total heap. This information may be used to determine if garbage collections take too long to run; If too many garbage collections are produced; and if the JVM crashed during garbage collection operation.

PMAT analysis trace GC verbose by analyzing traces and constructing models of pattern. PMAT recommends key configurations running engine diagnosis and pattern modeling algorithm. If there are errors related to exhaustion of heap fragmentation or Java in the verbose GC trace, PMAT can diagnose the cause of failures. PMAT provides rich chart that graphically displays features use java heap.

The following features are included:

The tool can also analyze Java HotSpot garbage collector traces, including the following:

Additional information is available in this Webcast replay: "how to analyze verbosegc trace with IBM Pattern Modeling and Analysis Tool for IBM Java Garbage Collector".

Read Jinwoo Hwang, finalizer "Anatomy of a Java" section in the java developers journal.

Jinwoo Hwang

Jinwoo Hwang is a software engineer, team leader and a technical team of technical support for WebSphere Application Server, which is based in Research Triangle Park, N.C. leader He joined IBM in 1995 and has worked with IBM Global Services learning, IBM Consulting Services and development prior to his current position. Mr. Hwang is an IBM Certified Solution Developer as well as a SUN Certified Programmer for the Java 2 platform. He is the architect and developer of the following tools:

Mr. Hwang is also the author of C programming for novices (Yonam Press, 1995), as well as numerous articles technology aggregated on his personal website: http://jinwoohwang.sys-con.com/.

Trade-marks

Friday, December 10, 2010

Class-level validation of the model with EF code first and ASP.NET MVC 3 (Weblogs @ ASP.NET)

Earlier this week the data team released the CTP5 build of the new Entity Framework Code-First library. 


In my blog post a few days ago I talked about a few of the improvements introduced with the new CTP5 build.  Automatic support for enforcing DataAnnotation validation attributes on models was one of the improvements I discussed.  It provides a pretty easy way to enable property-level validation logic within your model layer.


You can apply validation attributes like [Required], [Range], and [RegularExpression] – all of which are built-into .NET 4 – to your model classes in order to enforce that the model properties are valid before they are persisted to a database.  You can also create your own custom validation attributes (like this cool [CreditCard] validator) and have them be automatically enforced by EF Code First as well.  This provides a really easy way to validate property values on your models.  I showed some code samples of this in action in my previous post.


DataAnnotation attributes provides an easy way to validate individual property values on your model classes. 


Several people have asked - “Does EF Code First also support a way to implement class-level validation methods on model objects, for validation rules than need to span multiple property values?”  It does – and one easy way you can enable this is by implementing the IValidatableObject interface on your model classes.


IValidatableObject.Validate() Method


Below is an example of using the IValidatableObject interface (which is built-into .NET 4 within the System.ComponentModel.DataAnnotations namespace) to implement two custom validation rules on a Product model class.  The two rules ensure that:

New units can’t be ordered if the Product is in a discontinued state New units can’t be ordered if there are already more than 100 units in stock

We will enforce these business rules by implementing the IValidatableObject interface on our Product class, and by implementing its Validate() method like so:


image


The IValidatableObject.Validate() method can apply validation rules that span across multiple properties, and can yield back multiple validation errors. Each ValidationResult returned can supply both an error message as well as an optional list of property names that caused the violation (which is useful when displaying error messages within UI).


Automatic Validation Enforcement


EF Code-First (starting with CTP5) now automatically invokes the Validate() method when a model object that implements the IValidatableObject interface is saved.  You do not need to write any code to cause this to happen – this support is now enabled by default.


This new support means that the below code – which violates one of our above business rules – will automatically throw an exception (and abort the transaction) when we call the “SaveChanges()” method on our Northwind DbContext:


image


In addition to reactively handling validation exceptions, EF Code First also allows you to proactively check for validation errors.  Starting with CTP5, you can call the “GetValidationErrors()” method on the DbContext base class to retrieve a list of validation errors within the model objects you are working with.  GetValidationErrors() will return a list of all validation errors – regardless of whether they are generated via DataAnnotation attributes or by an IValidatableObject.Validate() implementation. 


Below is an example of proactively using the GetValidationErrors() method to check (and handle) errors before trying to call SaveChanges():


image


ASP.NET MVC 2 included support for automatically honoring and enforcing DataAnnotation attributes on model objects that are used with ASP.NET MVC’s model binding infrastructure.  ASP.NET MVC 3 goes further and also honors the IValidatableObject interface.  This combined support for model validation makes it easy to display appropriate error messages within forms when validation errors occur. 


To see this in action, let’s consider a simple Create form that allows users to create a new Product:


image


We can implement the above Create functionality using a ProductsController class that has two “Create” action methods like below:


image


The first Create() method implements a version of the /Products/Create URL that handles HTTP-GET requests - and displays the HTML form to fill-out.  The second Create() method implements a version of the /Products/Create URL that handles HTTP-POST requests - and which takes the posted form data, ensures that is is valid, and if it is valid saves it in the database.  If there are validation issues it redisplays the form with the posted values. 


The razor view template of our “Create” view (which renders the form) looks like below:


image


One of the nice things about the above Controller + View implementation is that we did not write any validation logic within it.  The validation logic and business rules are instead implemented entirely within our model layer, and the ProductsController simply checks whether it is valid (by calling the ModelState.IsValid helper method) to determine whether to try and save the changes or redisplay the form with errors. The Html.ValidationMessageFor() helper method calls within our view simply display the error messages our Product model’s DataAnnotations and IValidatableObject.Validate() method returned. 


We can see the above scenario in action by filling out invalid data within the form and attempting to submit it:


image


Notice above how when we hit the “Create” button we got an error message.  This was because we ticked the “Discontinued” checkbox while also entering a value for the UnitsOnOrder (and so violated one of our business rules). 


You might ask – how did ASP.NET MVC know to highlight and display the error message next to the UnitsOnOrder textbox?  It did this because ASP.NET MVC 3 now honors the IValidatableObject interface when performing model binding, and will retrieve the error messages from validation failures with it.


The business rule within our Product model class indicated that the “UnitsOnOrder” property should be highlighted when the business rule we hit was violated:


image


Our Html.ValidationMessageFor() helper method knew to display the business rule error message (next to the UnitsOnOrder edit box) because of the above property name hint we supplied:


image


ASP.NET MVC and EF Code First enables you to keep your validation and business rules in one place (within your model layer), and avoid having it creep into your Controllers and Views. 


Keeping the validation logic in the model layer helps ensure that you do not duplicate validation/business logic as you add more Controllers and Views to your application.  It allows you to quickly change your business rules/validation logic in one single place (within your model layer) – and have all controllers/views across your application immediately reflect it.  This help keep your application code clean and easily maintainable, and makes it much easier to evolve and update your application in the future.


EF Code First (starting with CTP5) now has built-in support for both DataAnnotations and the IValidatableObject interface.  This allows you to easily add validation and business rules to your models, and have EF automatically ensure that they are enforced anytime someone tries to persist changes of them to a database. 


ASP.NET MVC 3 also now supports both DataAnnotations and IValidatableObject as well, which makes it even easier to use them with your EF Code First model layer – and then have the controllers/views within your web layer automatically honor and support them as well.  This makes it easy to build clean and highly maintainable applications.


You don’t have to use DataAnnotations or IValidatableObject to perform your validation/business logic.  You can always roll your own custom validation architecture and/or use other more advanced validation frameworks/patterns if you want.  But for a lot of applications this built-in support will probably be sufficient – and provide a highly productive way to build solutions.


Hope this helps,


Scott


P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu