Monday, 23 February 2015

Data annotations in MVC

            
                    Data validation is a key aspect for developing web application. In Asp.net MVC, we can 

easily apply validation to web application by using Data Annotation attribute classes to model class. 

Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations 

namespace and are available to Asp.net projects like Asp.net web application & website, Asp.net 

MVC, Web forms and also to Entity framework ORM  models.



DataType---    Specify the datatype of a property

DisplayName-- specify the display name for a property.

DisplayFormat-- specify the display format for a property like different format for Date property.

Required --Specify a property as required.

ReqularExpression---validate the value of a property by specified regular expression pattern.

Range---validate the value of a property with in a specified range of values.

StringLength-----specify min and max length for a string property.

MaxLength---specify max length for a string property.

Bind---specify fields to include or exclude when adding parameter or form values to model properties.

ScaffoldColumn---specify fields for hiding from editor forms.

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Employee.Models
{
[Bind(Exclude = "EmpId")]
public class Employee
{
[ScaffoldColumn(false)]
public int EmpId { get; set; }

[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name is required")]
[StringLength(100,MinimumLength=3)]
public String EmpName { get; set; }

[Required(ErrorMessage = "Employee Address is required")]
[StringLength(300)]
public string Address { get; set; }

[Required(ErrorMessage = "Salary is required")]
[Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
public int Salary{ get; set; }

[Required(ErrorMessage = "Please enter your email address")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[MaxLength(50)]
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
public string Email { get; set; }
}
}

Java script basics

What is JavaScript?

JavaScript is a cross-platform, object-oriented scripting language. It is a small and lightweight language. Inside a host environment, JavaScript can be connected to the objects of its environment to provide programmatic control over them.
JavaScript contains a standard library of objects, such as ArrayDate, and Math, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:

             Client-side JavaScript extends the core language by supplying objects to control a browser and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
            Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.

JavaScript and Java

            JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.
In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.
JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.
Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.
In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.
JavaScript compared to Java
JavaScriptJava
Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.
Variable data types are not declared (dynamic typing).Variable data types must be declared (static typing).
Cannot automatically write to hard disk.Cannot automatically write to hard disk.

Values

JavaScript recognizes the following five types of primitive values:
 
TypeExamples of typed values / Notes
Numbers                                              42, 3.14159,1,2,.................
Logical(Boolean)                                               true / false
Strings                                               "revathi"
null                                     a special keyword denoting a null value; null is also a primitive value. Because JavaScript is case-sensitive, null is not the same as NullNULL, or any other variant
undefined   
a top-level property whose value is undefined; 
undefined is also a primitive value.

Data type conversion

avaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:
var answer = 42;
And later, you could assign the same variable a string value, for example:
answer = "Thanks for all the fish...";
Because JavaScript is dynamically typed, this assignment does not cause an error message.
In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:
x = "The answer is " + 42 // "The answer is 42"
y = 42 + " is the answer" // "42 is the answer"
In statements involving other operators, JavaScript does not convert numeric values to strings. For example:
"37" - 7 // 30
"37" + 7 // "377"


Converting strings to numbers


parseInt() and parseFloat()

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).


Syntax :
parseInt(string, radix);



Parameters

string

The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored. radix

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

Description

           The parseInt function converts its first argument to a string, parses it, and returns an integer orNaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInttruncates numbers to integer values. Leading and trailing spaces are allowed.


If radix is undefined or 0 (or absent), JavaScript assumes the following:
  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed. 
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when usingparseInt. 
  • If the input string begins with any other value, the radix is 10 (decimal).


If the first character cannot be converted to a number, parseInt returns NaN.


For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN.


To convert number to its string literal in a particular radix use intValue.toString(radix).

Examples

Example: Using parseInt


The following examples all return 15:
parseInt(" 0xF", 16);
parseInt(" F", 16);
parseInt("17", 8);
parseInt(021, 8);
parseInt("015", 10);
parseInt(15.99, 10);
parseInt("FXX123", 16);
parseInt("1111", 2);
parseInt("15*3", 10);
parseInt("15e2", 10);
parseInt("15px", 10);
parseInt("12", 13);
The following examples all return NaN:

parseInt("Hello", 8); // Not a number at all
parseInt("546", 2);   // Digits are not valid for binary representations
The following examples all return -15:
parseInt("-F", 16);
parseInt("-0F", 16);
parseInt("-0XF", 16);
parseInt(-15.1, 10)
parseInt(" -17", 8);
parseInt(" -15", 10);
parseInt("-1111", 2);
parseInt("-15e1", 10);
parseInt("-12", 13);
The following example returns 224:
parseInt("0e0", 16);



Sunday, 22 February 2015

Model First Approach in MVC




Step 1: 

Open VS 2010 > File > New Project > Select Visual C# or Visual Basic Windows Template and 

select an Empty Project . I am calling this project ‘ModelFirstEF’. 


Right click the Project in Solution Explorer > Add > New Item > Data Template > ADO.NET Entity 

Data Model. Click Add.


The Entity Data Model Wizard appears. Select ‘Empty Model’ and click on Finish.

Step 2: 

The wizard creates a new conceptual model with an empty Data Model Designer to create your 

Entity Data Model (EDM).


Drag and drop an Entity from the Toolbox to the Designer as shown below. You can even right click 

the designer > Add Entity


Rename ‘Entity1’ to ‘Employee’. The Id property you see above is the Entity Key (Primary Key) of 

this entity. I will rename it to ‘EmployeeId’ in the properties window. Also observe that it’s Type is 

set to ‘Int32’ and since this is an identity key, its ‘StoreGeneratedPattern’ is automatically set to 

‘Identity’.


You can add additional properties like FirstName (string), LastName (string), Age (Int16) etc. by 

right clicking the Entity in the designer > Add > Scalar Property

Step 3: 

Let us add one more entity called ‘Department’. This time we will do it from the designer. Right 

click the designer > Add > Entity


The ‘Add Entity’ dialog appears. Type ‘Department’ in the Entity name field and select the box 

‘Create Key Property’ to create an Entitykey. Call it ‘DepartmentId’ and set its property type as 

Int32.


Click OK and a new Department entity will appear on the design surface. Add two additional 

properties DeptName (string) and EmployeeId (Int32) to the Department Entity.

Step 4:

 Our next step is to create a One-to-many relationship between Employee and Department. Each 

Department can have many Employees, but one Employee can belong to only one Department. 

Using the Association tool in the Toolbox, select the EmployeeId property in the Employee entity, 

hold the left mouse button down and drag it to the DepartmentId property in the Department entity.


Update: I should have added the DepartmentId in the Employee table, but for this example just 

assume the opposite. It is a typo. 


Alternatively, you can also right click the Employee Entity > Add > Association to create a 

relationship.


Your conceptual model is ready now! Our next step is to generate the database from the model


Generate Schema and Database from Model 

Step 5: 

I have gone ahead and created an Empty database called ‘EFDB’ in my SQL Server box. To generate 

a Database from the model, right click the designer > Generate Database from Model..



Note: I find this amusing! Although the option says ‘Generate Database from Model’, an empty or 

an existing database ‘must’ exist before clicking this option. I think the Database must exist due to 

the Connection Settings that we will establish in the next step. We need to specify a target database 

there, so the database must exist beforehand. Also the DDL script that gets generated does not 

include the script to generate a new database.

Step 6:

 The Generate Database Wizard appears. Click on ‘New Connection’ and fill the Connection 

properties as shown below. Test the Connection and Click OK.

Click Next in the wizard to preview the DDL that will be generated

Click Finish to add the generated script to your project. Once you click Finish, an EntityConnection 

string is added to your config file and the DDL, SSDL and MSL files are created (read my previous 

articleExploring the Entity Data Model (EDM) to know what SSDL and MSL are).

Step 7:

 All you need to do now is run the database script by clicking on the Green Arrow in a query window 

(Ctrl+Shift+E) to create the Employee and Department tables in the database EFDB.


If everything’s ok, you will see the message ‘Command(s) executed successfully. 


How did the DDL Scripts get generated from the model?


      If you are wondering what went behind the scenes to generate the database, then I would strongly 

recommend you to read my previous article Exploring the Entity Data Model (EDM) where I 

discussed the role of .EDMX and its files SSDL, CSDL and C-S mapping. These files play a role not 

only in generating a model from the database, but also vice-versa, i.e. generating a database from a 

model. Observe the properties of Model1.edmx as shown below, especially the DDL Generation 

Templateproperty.


   This property specifies a T4 template (.tt) file. The T4 Templates reads the .edmx with the help of 

the TablePerTypeStrategy.xaml (windows workflow file) and generates the T-SQL code (DDL 

script) that we just saw.As given in the msdn documentation “T4 is shorthand for the Text Template 

Transformation Toolkit and is a Microsoft technology explicitly designed to make text file creation 

such as code generation straightforward using templates. It is a mixture of processing logic and text 

to emit with the idea that the text can be created from the template by substituting values in it 

programmatically. This is similar in principle to XSLT but T4 allows the blending of .NET code and 

text mark-up to be combined seamlessly and it is used extensively in Visual Studio 2010”



        The best part is that you can modify this template and customize the DDL generated. You can 

download the Entity Designer Database Generation Power Pack which contains Windows 

Workflows and T4 Templates to manage database generation strategies. Anyways we will explore 

this topic again in one of the future articles. 

Limitations of the Model-First development 

There are two major limitations of the Model-First development that you should keep in mind (we 

will also see how to overcome them)


You cannot update the database and expect the changes to be updated in the model. Currently it’s not

possible out-of-the-box through EF 4.0.


If you go ahead and populate the database with data and then at a later stage change your model, then

the database will be dropped including all your data when you recreate the DDL scripts and execute

them.


          However remember that you can extend the DDL generation capabilities of the Entity Framework. 

The good news is that these two limitation can be overcome using the Entity Designer Database 

Generation Power Pack. Using this power pack, you can update an existing database and synchronize 

the model with it and also make changes to the model and deploy the changes back to the database 

without data loss. Hopefully in the next version, this will be added to the core of EF.







Different Approaches of Enitity Framework



          In this article I will be describing the three approaches to using Entity Framework (EF) – Model First, Database First and Code First.

I will illustrate how to use these techniques using Entity Framework 5.0, which has several performance improvements and new features which will be highlighted as part of the sample implementation. I will then go on to explain the relative advantages of each approach when designing the database.

Model First

In the Model First approach, the database model is created first using the ORM (Object Relational Mapping)designer in Visual Studio. Once the model consisting of entities and relationships has been designed, the physical database will be generated from the model.

Walk through – Creation of Model First

In order to create the model, you should create an empty ASP.Net project in Visual Studio and add a new ADO.Net Entity Data Model, which for this example we’ll call ModelSample.


Figure 1: Add ADO.Net Entity Data Model

This will open the Entity Data Model Wizard. Select the Empty Model from the Model Contents selection.



Figure 2: Choose Model Contents

This loads the entity data model designer. Add Entities from the toolbox to our entity data model designer. Link the entities using the ‘Association from’ Toolbox to complete the model design.



Figure 3: Sample designer with entities

            New feature: Entity Color. As you can see in the above diagram, we can color the entities appropriately for better understanding and grouping. In our sample, leave-related entities are colored with orange, organization details in purple and the employee details in blue.
           Once the entity model design is completed, generate the database from the model using the ‘Generate Database from Model’ context menu. Right-click on the designer to invoke the Context menu, then select the ‘Generate Database from Model’option.

Figure 4:Generate Database from Model

Select an existing database connection or create a new connection to create the sample database from the Model. For this sample, I have used SQLExpress with the SampleDB database connection.


Figure 5: Choose Data Connection

This will generate the DDL statements, and the generated script will be added to the solution as a script file.


Figure 6: Specify DDL file name

The script file generated in the previous step will be opened in Visual Studio. Click ‘Execute’in order to create the database using the generated script.


Figure 7: Execute Script

Now, the database with all tables and relationships is created in the database server. For working with the new database, generate the code using the Code Generation Strategy; set this value as “default”.


Figure 8: code Generation Strategy

This will generate the entity framework code and database context classes corresponding to the defined model. We can use these new classes from the business layer to perform various database operations. Verify the code generated under the Modelname.Designer.cs file.


Figure 9: Designer Code

We can sync the Model with the database either way using the context menu options – ‘Generate Database from Model’ or ‘Update Model from Database’. You can modify the model and then invoke the ‘Generate database from Model’ context menu option to update the database schema. Any modification in database schema can get updated to the model using the ‘Update Model from Database’ context menu option.

New feature: Multiple-diagrams per single Model

Another new feature introduced in EF 5.0 is to allow the use of multiple diagrams for a single model. We can move selected entities to another diagram in order to reduce the complexity of the main diagram. Select the entities by holding shift key and select the “Move to new diagram” option from the context menu.


Figure 10: Move to new diagram

Let us move the entities related to leave to another diagram. This will create a new diagram with selected entities; in our case Leave and Leavedetail.


Figure 11: Multiple diagram for single Model

    As you can see, the relationship between the LeaveDetail entity and the Employee entity has been removed. We can use the new ORM feature to include the related entities in the second diagram by keeping one copy of the same in the first diagram for better readability. We can include the related entities in the second diagram using “Include Related” option. This will create a copy of all the related entities in the second diagram. Select the Leavedetail entity, right-click and select the option “Include Related” to include the employee entities in the second diagram.



Figure 12: Include Related


Figure 13: Multi-diagram with Include Related

Database First

The next approach supported by the Entity Framework is the database-first approach. In the database first approach, we are creating the entity framework from an existing database. We use all other functionality, such as the model/database sync and the code generation, in the same way we used them in the Model First approach.
Create the ADO.Net Entity Data model using the ‘Generate from Database’ option.


Figure 14: Choose Model Content

      Select an existing connection or new connection from the ‘choose data connection’ window. We are using thesampleDB that we created as part of our Model First sample. Now, select the database objects suitable for your project such as Tables, Views and Stored procedures, functions from the ‘Choose your Database Objects’ window.


Figure 15: Choose database objects

This will generate the designer with selected entities and associations as shown below.


Figure 16: Entity data model designer

Create the code using the ‘Code Generation Strategy’ property, and perform the sync between the database and model in the same way that the Model-first approach works. Any sync back to the database will recreate the database and the existing data will be lost.
New feature: There is now support for Table-valued functions. Before using the SampleDB in the database-first approach, we have added a Table-valued function called UpdateLeave to the database. You’ll notice that the new Table-valued function is added under the Complex Type region inside the Designer.cs file. Support for the Table-valued function has been added as part of Entity Framework 5.0 and is available for the database-first approach only.
New feature: Enum properties. Support for enum properties are added as part of Entity Framework 5.0. Add one Integer property, say Relationship to the entity. Right-click on the property and select the “Convert to Enum” option from the context menu.


Figure 17: Convert to Enum

Add the enumeration members and values in the ‘Add Enum Type’ window.


Figure 18: Add Enum Type

Instead of adding each value, we can refer an external type using the ‘Reference external type’ option.
Here is the generated code for the new Enum added inside the Designer.cs file
[EdmEnumTypeAttribute(NamespaceName="SampleDBModel", Name="Relationship")]
   [DataContractAttribute()]
   public enum Relationship : int
   {
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Mother=1,
 
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Father=2,
 
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Spouse=3,
 
      ///<summary>
      ///No Metadat aDocumentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Child=4
   }

New feature: Support for Geography and Geometry types. Support for the DBGeography and DBGeometry types are added as part of Entity Framework 5.0.

Figure 19: Geometry & Geography supports

Code First

In Code-First Approach, we create the classes first and then generate the database from the classes directly. In code first, we won’t use the Entity Designer (for editing .edmx files) at all.

First, create the classes which represent the database table. For this walkthrough I am using the Category and Product classes.

public class Category
   {
      public int CategoryId { get; set; }
      public string Category { get; set; }
      public string Description { get; set; }
   }

   public class Product
   {
      public int ProductId { get; set; }
      public string ProductName { get; set; }
      public float Price { get; set; }
      public int CategoryId { get;set;}
   }

Now, define the custom DbContext class derived from DbContext, which defines the classes that need to be converted to database tables. Here, we have defined both category and Product classes to represent as a table.

public class SampleContext : DbContext
   {
      public DbSet<Category> Categories { get; set; }
      public DbSet<Product> Products { get; set; }
   }

For performing the CRUD operations, define the data access class with proper methods. Here, we are defining only the SELECT operation, but we’ll need to define different methods for UPDATE, DELETE and SELECT options.

public class SampleDataAccess
   {
      SampleContext  context = new SampleContext();
      public List<Product> GetProducts()
      {
         return (from p in context.Products select p).ToList();
      }
   }

Add the connection string to the web.config for accessing the database at run time.

<add name="SampleContext"
   connectionString="datasource=.\sqlexpress;IntegratedSecurity=SSPI;database=SampleDB"
   providerName="System.Data.SqlClient"/>

Build the solution before adding the UI control, GridView, to display the data from the database. Then, add a data source which will point to the SampleDataAccess class. Select 'Object' from the 'Choose a Data Source Type' menu and specify an id for the data source.




Figure 20: Choose a Data source type

Select the SampleDataAccess class from the list. If it is not displayed here, then the solution may not be built properly.


Figure 21: Choose business object

Set the methods for the CRUD operation. We have only one method selected called GetProducts().


Figure 22: Define data methods

We can define the Update, Delete and Insert methods in the same way. Here are the tables available under theSampleDB database before running the application.


Figure 23: SampleDB before running app

Now, run the application, which will display a blank page. You’ll see that the new Categories and Products tables are added in the SampleDB database after running the application.


Figure 24: SampleDB after running the app

To try this out, we’ll insert few records to the database and run the application again.


Figure 25: Code First output


Comparing the Model First, Database First and Code First approaches

So when should one choose one method over the others? Here is a simple comparison of the advantages all three approaches.

Model First:

  • Good support with EDMX designer
  • We can visually create the database model
  • EF generates the Code and database script
  • Extensible through partial classes
  • We can modify the model and update the generated database.

Database First:

  • An existing database can be used
  • Code can be auto-generated.
  • Extensible using partial classes/ T4 templates
  • The developer can update the database manually
  • There is a very good designer, which sync with the underlining database

Code First:

  • There is full control of the model from the Code; no EDMX/designer
  • No manual intervention to DB is required
  • The database is used for data only


The Model First approach is preferable when creating the model using the ORM designer. Powerful features of the ORM designer help in creating a model very easily. The clear representation of the model in visual form is more understandable to all stakeholders involved in product development.


If we have an existing database, like in the case of a maintenance project, we can use the Database First approach to create the Entity Framework objects out of the existing database. Any modification to the Model using the ORM designer requires syncing back to the database. Remember any changes to the model result in the deletion of the entire database so it can be re-created – all existing data will be lost.


Hardcode coders love to code the model using the Code First approach. In this approach, the database is used for storing the data only. The database structure is defined by various classes. One of the advantages of the Code First approach is the same class is used for defining the database table structure and business object. Any changes in the class affect both the business object and the database table. Also, if we have any plans to deploy the project into Azure with Azure Storage, we can reuse the classes to define the Azure Storage objects.