Monday, November 21, 2011

Introduction to jQuery for ASP.NET

If you are keeping yourself updated with the latest in the .NET sphere, you are probably aware that Microsoft has provided an inbuilt support for jQuery in Visual Studio 2010. Though it was possible to use jQuery with ASP.NET even before VS 2010, formally including jQuery as a part of website created using VS2010 means that more and more developers are going to learn and use it. If you haven't tried jQuery yet this article series will teach you everything needed to master jQuery and use it in ASP.NET applications. What is jQuery?

The official website for jQuery defines jQuery as follows: "jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript." Let's try to understand this description of jQuery in a bit detail.

jQuery is a JavaScript library As a ASP.NET developer you must have used JavaScript in one way or the other. The standard JavaScript no doubt helps you code rich and responsive web pages but the amount of code that you need to write is often too much. For example, if you wish to write a fancy popup menu from ground up using JavaScript it might be a time consuming task. To simplify such development and make you more productive several JavaScript libraries are available and jQuery is one of them. There are others such as Mootools, Prototype and Dojo. The fact that Microsoft is supporting jQuery in its products and investing resources into it clearly indicates its popularity. As you would expect jQuery is cross-browser and supports all leading browsers including IE 6+, FF 2+, Chrome, Safari 3+ and Opera 9+. jQuery is fast and concise

jQuery is highly optimized library. Moreover it is compact. The production version of jQuery 1.4.3 is just 26 KB and development version 179 KB. This compactness means less data to be downloaded at client side without compromising stunning UI effects. Scope of jQuery jQuery simplifies HTML DOM navigation considerably. For example, document.getElementById("Text1") becomes just $("#Text1"). Simple. Isn't it? Most of the JavaScript functionality goes in client side event handlers. jQuery is handy when it comes to event handling. If you are thinking about your AJAX functionality don't worry. jQuery allows you to make AJAX calls to ASP.NET Web Services, WCF services or even page methods.

If needed jQuery can be used along with ASP.NET AJAX. jQuery is designed to change the way that you write JavaScript That's true! jQuery dramatically changes the way you write JavaScript code. Initially you may find syntax of jQuery bit odd but once you get hang of it you will probably never look at any other library (or at least to the traditional way of writing JavaScript).

For example, a common JavaScript file contains too many small to huge functions and you keep calling them individually whenever required. With jQuery the "chain" of operations makes your code compact and handy. Ok. Enough of introduction. Now, let's complete the "hello world" ritual :-) In next section you will build a simple ASP.NET webform with some server controls on it that perform a trivial job of displaying "Hello world". Download jQuery Before you start any development with jQuery you need to download its latest version. You can do so by visiting http://jquery.com and then downloading "Development" version.

If you are using VS2010 then you need not download anything because when you create a new website by default jQuery library is already added for you (see screenshot below) In the above screenshot jquery-1.4.1.js is the development version, jquery-1.4.1.min.js is minified production version and jquery-1.4.1-vsdoc.js is the VS2010 IntelliSense file that enables IntelliSense for jQuery (see below). In the remainder of this article I will be using VS2008. If you are using VS2010 then just cleanup the default website by removing master page and other unwanted stuff. Design a simple web form Create a new website in VS2008 and create a new folder named Scripts. Copy the downloaded jQuery file in the Scripts folder. Though you can place it anywhere inside your website it is recommended to keep all JavaScript files under one folder typically named Scripts. The default name for the jQuery file is jquery-1.4.3.js but you can change it to something else if you so wish. Now open the default web form and add a Now place a TextBox and a Button web control on the web form. Switch back to HTML source view and add another The first line is where jQuery magic starts. The $ sign is a shortcut to base object jQuery. So, $(...) is actually same as jQuery(...).

If you ever coded in ASP.NET AJAX this concept should be familiar to you. The ready() is an event that fires when the wen page under consideration is fully loaded and its various elements are ready to be accessed. The event handler for ready event is supplied in the parenthesis as OnPageReady. OnPageReady() is a normal JavaScript function that wires an event handler for the client side click event of the button. It does so again by using $ shortcut. This time, however, ID of the button control is specified prefixing it with #. The click is an event and you specify its handler as OnButtonClick. The event handler receives an event object giving more information about the event. The OnButtonClick() is another function that simply displays "Hello World from jQuery!" using JavaScript alert. The OnButtonClick function also calls event.preventDefault() method so as to prevent web form postback that normally would have happened due to Button web server control. Ok.
If you run the web form you should see something like this : Easy! Isn't it? Now let's modify the above code as shown below:

$(document).ready( function()
{ $("#Button1").click(function(event)
{ alert("Hello world from jQuery!");
event.preventDefault(); } ) }
)

This is a compact version of the code that achieves the same functionality. Here, instead of defining separate functions you have written all the code there itself. You may compare this code with anonymous methods of C#. Adding something more... Now that the "Hello world" ritual is over let's add some extra features to our code. Begin by defining the following CSS class in your web form: The CSS class NoFocus will be applied to the textbox when it doesn't have focus whereas CSS class Focus will be applied when the textbox receives the focus. To accomplish this change the preceding code (compact version) as shown below:

$(document).ready ( function()
{ $("#Button1").click( function(event)
{ alert($("#TextBox1").val()); return false; } ) ,
$("#TextBox1").addClass("NoFocus") ,
$("#TextBox1").focus( function(event) { $("#TextBox1").removeClass("NoFocus"); $("#TextBox1").addClass("Focus"); } ), $("#TextBox1").blur( function(event) { $("#TextBox1").removeClass("Focus"); $("#TextBox1").addClass("NoFocus"); } ) } )


Notice the lines marked in bold letters. The click event handler of the button now displays whatever has been entered in the textbox. To retrieve textbox value you use val() method. Initially the textbox won't have focus and its CSS class should be NoFocus. This is done using addClass() method. The focus() and blur() event handlers simply add and remove the appropriate classes using addClass() and removeClass() methods respectively.

Wednesday, November 16, 2011

Entity FrameWork in DAL

The data access layer provides a centralized location for all calls into the database, and thus makes it easier to port the application to other database systems. There are many different options to get the Data Access Layer built quickly. In my effort to build the DAL, I would have chosen from many different model providers, for example: NHibernate LINQ to SQL Or else I would have chosen any other model provider, possibly: SubSonic LLBLGen Pro LightSpeed ..or who knows This means that we will be using an ORM (Object Relational Mapping) tool to generate our Data Access Layer. As you can see, there are many tools, but all having their advantages and disadvantages. In order to select the right tool, you need consider your project requirements, the skills of the development team, and if an organization has standardized on a specific tool etc. However, I am not going to use the tools listed above, instead decided to use Microsoft Entity Framework (EF), which is something Microsoft has newly introduced. The ADO.NET Entity Framework (EF) is an object-relational mapping (ORM) framework for the .NET Framework. ADO.NET Entity Framework (EF) abstracts the relational (logical) schema of the data that is stored in a database and presents its conceptual schema to the application. However the conceptual model that EF created fail to meet my requirements. Therefore I had to find a work around to create the right conceptual model for this design. You will see few adjustments that I have made to achieve my requirement in later part of this Article. The selection of EF (Entity Framework) for my ASP.NET MVC front end is not a blindfolded decision. I do have few affirmations... ASP.NET MVC Framework is Microsoft, so as ADO.NET Entity Framework. They tend to work well together than any other tool. Latest version of EF (Entity Framework) has many promising features, and has addressed many issue had in its initial version. In general Microsoft seems serious about EF. That made me thinks that EF would have a significant share in the future of ORM tools. The community has raised concerns over what has been promised and is being delivered with EF. You can read this ADO .NET Entity Framework Vote of No Confidence for more details about it. Microsoft and the Entity Framework team have received a tremendous amount of feedback from experts in entity-based applications and software architectures on the .NET platform. While Microsoft’s announcement of its intention to provide framework support for entity architectures was received with enthusiasm, the Entity Framework itself has consistently proved to be cause for significant concern. However the second version of Entity Framework (known, somewhat confusingly, as 'Entity Framework v4' because it forms part of .NET 4.0) is available in Beta form as part of Visual Studio 2010, and has addressed many of the criticisms made of version 1. The Entity data model (which is also called the conceptual model of the database), which ADO.NET Entity Framework auto created for our DMS is given below. This has a 1:1 (one to one) mapping between the database tables and the so called conceptual models. These models or objects can be used to communicate with the respective physical data source or the tables of the database. I hope you can understand my conceptual model quite easily.
The Data Access Layer project, which is given below, has three folders namely Models, Infrastructure and Interfaces (You will later notice that this project template is being reused in other projects of this system too). Outside of those folders, you find few classes such as one base class and two concrete classes. These are the main operational classes of the data access layer (DAL) project. This project template made it possible to directly access all commonly used main operational classes without worrying about navigating in to directories. "The inherent complexity of a software system is related to the problem it is trying to solve. The actual complexity is related to the size and structure of the software system as actually built. The difference is a measure of the inability to match the solution to the problem."
In the Data Access Layer (DAL) design, I thought of using a variant of repository pattern. The Repository pattern is commonly used by many enterprise designers. It is a straight forward design that gives you testable & reusable code modules. Furthermore it gives flexibility and separation of concerns between the conceptual model and business logics too. In my design there are two Repositories namely ‘DocumentRepository’ and ‘FileRepository’, which will mediates between the domain (also called Business Logic Layer) and data mapping layers (also called Data Access Layer) using domain objects (also called Business Objects or Models). In general it is recommended having one repository class for every business object of the system. Among the few folders that you see in that project, the folder named 'Interfaces' is important. So let's check inside the 'Interfaces' folder and see what interfaces that we have in it... IRepository - The generic interface that abstractly defines the behavior of all the repositories of our system. This is the super repository. This is what extends to create the abstract repository with the name 'RepositoryBase'. IDocumentRepository – This is a specialized repository, which defines the behavior specific to 'Document'. IFileRepository – Just like it was with 'IDocumentRepository', this defines the behavior of the 'File' repository. IRepositoryContext - This defines the behavior of the context of our repositories. IPagination - This defined the definition for pagination related operations. 'IUnitOfWork' and 'IUnitOfWorkFactory' were there but removed from the design later. Initially, I was planning to write some codes for dependency injection (DI) too. But later I found that Microsoft enterprise library has everything done for us. They have an application block called 'UnityApplicaitonBlock', which does what I was initiated with those two interfaces. Therefore I removed unity and inversion of control related implementations from the project. Now the source code you download now will not have those implementations. I have used interfaces in the DAL design, and that might made you ask questions like 'why we need these interfaces?' and 'why not just have the concrete implementation alone?'. There are many reasons for having interfaces in a design. They allow implementation to be interchangeable (One common scenario is, when unit testing, you can replace the actual repository implementation with a fake one). Additionally, when carefully used, they help to better organize your design. The interface is the bare minimum needed to explain what a function or class will do. It's the lease amount of code you can write for a full declaration of functionality and usability. For this reason, it's (more) clearer for a user of your function or class to understand how the object works. The user shouldn't have to look through all of your implementations to understand what the object does. So, again defining interfaces is the more organized approach. In some instances, I have seen designers add interfaces for every class, which I thought is a too extreme design practice. In my design I have used interfaces not only to organize the design but also to interchange implementation too. Later in the article you will see how these interfaces are being used to assist 'unity application block' to inject dependencies too. You can see in the screen above that I have set of interfaces define for pagination too. The pagination (of business objects/ entities) is something that developers code in many different layers. Some code it in the UI (User Interface) layer, while others do it in BLL (Business Logic Layer) or DAL (Data Access Layer). I thought of implementing it inside DAL to avoid unwanted network round trips that would occurred otherwise in a distributed multi-tier deployment setup. Additionally when keep it inside DAL, I will have the option of using some of the built-in EF (Entity Framework) functions for pagination works. The figure below summarizes the overall DAL design with its main components and their relations. I think it is clear how the three interfaces and their concrete implementations are being defined.
I think it is important for you to know how this design evolves. So let me talk about that here. Initially, I had the 'IRepository' interface. That was used to implement the two specialized 'Document' and 'File' repositories. That time I noticed that the two was having many common operations. So I thought of abstractly define them with a abstract class. Thus, decided to add a new generic abstract class called 'RepositoryBase'. Once all these were done, the final system had the generic 'IRepository' interface right at the top, then the abstract 'RepositoryBase' class, and then two concrete implementations of 'File' and 'Document' repositories. I thought it is done, and had a final look before closing-up the design, but that made me realized that the design is still having issues. So let me talk about that in the next paragraph. The design I had made it impossible to interchange implementation of either of the specialized repository. As an example, if I have a test/ fake version of the 'DocumentRepository' implemented with the name 'TestDocumentRepository' and wanted to interchange that with the 'DocumentRepository', then it is not possible with my design. So I decided to do few more adjustment to the design by introducing two specialized interfaces called 'IDocumentRepository' and 'IFileRepository'. This made it possible to fully hide the special implementations, hence gain the required interchangeability. That final change concludes my DAL design.