Monday, November 24, 2014

ASP.NET MVC from ASP.NET developer's view

This post is about having first look at the ASP.NET MVC from ASP.NET developer’s view. If you are ASP.NET developer and trying to understand ASP.NET MVC for the first time then this is right post to read. This contains basic understanding for difference between ASP.NET and ASP.NET MVC at very high level. Learn to create first ASP.NET MVC application step by step with explanation. At end will understand some basic difference between ASP.NET and ASP.NET MVC

As an ASP.NET developer wanted to understand why to use ASP.NET MVC. When searching on internet found many article, blog and documentation about MVC and how it works. There are very few that ramps up ASP.NET developer on ASP.NET MVC. Being ASP.NET developer can understand how comfortable it is to create one page with rich set of user controls, wire up with C# code and manage state using different state management techniques. It has full control of events on each element on UI and smooth way to handle each event in code behind. ASP.NET with AJAX add one more point to this list.

Consider requirement to develop simple login page in ASP.NET. Very simple to add controls, Validation controls, JavaScript and code behind to handle database operations. In just few hours one can build quality login page. It should be safe to assume that every ASP.NET developer heard about ASP.NET MVC but not really sure how it works and what is take to build same login page just discussed.

Let’s quickly take an overview of what does MVC means to ASP.NET developer. To understand it think of ASP.NET HttpHandler. ASP.NET MVC is using HttpHandler to make things work. For example, consider creating ASP.NET HttpHandler accepting query string parameter. A query string parameter is nothing but static method returning HTML. So, http://testsite/myhandler.aspk?m=RenderInput will render HTML output on browser by executing code from static method named RenderInput. Similarly other method will return different HTML. So here single HttpHandler (say page) is able to render different HTML based on URL. ASP.NET MVC is built on same concept. Every URL is structure similar to RESTful service. ASP.NET Handler gives great control over HTML rendering in browser but require configuration to register handler, error handling, state management and security. Inside methods, once can use ASP.NET Rich UI control to render expected output.


Here is how to create simple ASP.NET MVC application from scratch?

Let’s skip ASP.NET HttpHandler implementation and straight forward get into practical by creating simple ASP.MVC application. This example is done using ASP.NET MVC 4 but it really does not matter for understanding concept. Below are simple steps to create ASP.NET MVC application having one page displaying “This is my First ASP.NET MVC Application” in browser.

  1. Start Visual Studio (Example is using VS.NET 2012)
  2. Go to File | New | Project
  3. Select ASP.NET MVC 4 Web Application. (Choose project name location to save as per your machine settings) and click OK
  4. Next Select an Empty Template as shown below. Leave View Engine to Razor as default. View Engine is separate topic not converting here. Click OK. We have selected Empty Project Template to build sample from scratch without any readymade stuff. This will give a clear understand of building block of ASP.NET MVC application
  5. Empty Template will have default pages and project structure as shown below. Things to note are is the folders with fixed name. Every ASP.NET MVC application have 3 main folders Controllers, Models and Views.
  6. Open RouteConfig.cs, the default code is Please note default values here. We will see what does it mean as we build the application
  7. To create simple page displaying “This is my First ASP.NET MVC Application”, first we need to create controller. Please watch naming convention carefully because it must be followed for application to work
  8. Right Click Controller folder and select Add | Controller. In Add Controller dialog give name HomeController. Things to note here is that every controller files must end with “Controller”. We gave name HomeController because Home is default controller as specified in RouteConfig.cs
  9. HomeController.cs will have following default content
  10. Update this code as below. This complete our controller
  11. Next step is to create a View. To create View right click Views folder and select Add | New Folder. Give Folder Name same as Controller. i.e. Home. Controller name and folder name inside View folder must match. In this case Home.
  12. Right Click Home folder and select Add | View. In view name enter Index. The name must be Index as it is default action in RouteConfig. Click Add
  13. This will create Index.cshtml file. Update content of file as shown below. @Viewbag.ResponseContent will print content set in HomeController.cs
  14. Run Application and see application is ready
What we have done here is created simple ASP.NET MVC application using empty template to print simple text. So as a ASP.NET developer we have many questions and top most question is what is going on here? Let us look at sequence of events happened when we access http://localhost:49331 in browser in above example
  1. Browser sends request to ASP.NET Server
  2. ASP.NET interrupts request and tries to match with URL structure specified table(s) created in RouteConfig.cs. Remember line url: "{controller}/{action}/{id}"? This URL structure has 3 portions. Controller, Action Inside Controller and Id as optional parameter. Because Home is specified as default controller, it executes even though no controller name is given in URL means Home is Default Controller. Same way Index is default action of controller
  3. So now URL match is done so it time to pass execution to appropriate Controller. This is the time where MVC HttpHandler comes in to picture. HttpHandler will create controller instance, execute action and bring back data
  4. After executing controller’s Action, MVC looks for matching View in Views folder with same name as Controller. Since default view is Index, Index.cshtml is picked up from Home folder
  5. It renders view and sends HTML to Browser
Does it sounds like ASP.NET HttpHandler is working here? It is more than that. It has deferent architecture built on top of ASP.NET.

Here are some basic difference between ASP.NET and ASP.NET MVC

ASP.NET

ASP.NET MVC

ASP.NET ASP.NET MVC Supports View States which renders part of page No View State
UI/View and Code behind is tightly coupled. UI/View and Code are separate. Controller can be used independently
Master pages are for consistent Layout Layouts are for consistent layout
Server and User controls for reusability No server control but partial view and HTML rendering helpers
ASP.NET Forms and Controls renders additional JavaScript and HTML so less control on client side Renders only required HTML so full control on client side
ASP.NET is based on event driven model Follows MVC development model
Every URL point to physical file URL are dynamic and HTML is rendered based on structure
Fixed URL with query string parameter for dynamic are not SEO friendly SEO friendly URLs
Support Web Form based rendering Support ASP.NET and new Razor view engine. Customized view engine can also be created

So, it easy to understand ASP.NET MVC as ASP.NET HttpHandler at high level. Once can surely argue on many detailed difference but this makes easy to understand. It is very easy to create simple ASP.NET MVC application with single page rendering text. There are many difference between ASP.NET and ASP.NET MVC. But keep in mind that ASP.NET MVC is built on top of ASP.NET so all basic feature of ASP.NET is available.

Hope this was useful. Please provide your comments, suggestion and question below.

Tuesday, November 18, 2014

Telerik RadDatePicker control - DisplayDateFormat and Culture

This blog talks about RadDatePicker especially its behaviour, DisplayDateFormat format and relation with ASP.NET culture settings.

Telerik offers very good controls and RadDatePicker is one of them. RadDatePicker belong to group of controls dealing with Time, date, calendar, schedule, etc. These are RadDatePicker, RadTimePicker, and RadDateTimePicker. In this post we going to focus only on RadDatePicker. Using this control requires ScriptManager on page as it has to deal with AJAX. This control is useful to capture date from user and highly configurable. Configuration allows to control display format, input format, styling, validation and appearance. Like any other telerik control, this offers flexible client side API. One of the great feature is sharing calendar. Imagine a page where there are more than 10 RadDatePicker controls are rendering. This will result in too much HTML and JavaScript rendering on client side. To solve this problem, sharing calendar feature comes into picture. This allow sharing calendar among many Data Picker control making page light weight and improve performance.  Coming back to point, we are focusing on two properties DateInput.DisplayDateFormat and DateInput.Culture. DisplayDateFormat is actually property of DateInput sub-object of type RadDateInput. RadDateInput basically controls user input and so RadDateInput.DisplayDateFormat controls how to display post user input. DateInput.Culture is again property of same sub-object.  Culture can be set from code explicitly or can be defaulted from (ASP.NET Context) Thread.CurrentThread.CurrentUICulture. So if Culture not set then it is same as Thread.CurrentThread.CurrentUICulture

There is always confusion around this two properties in multi-lingual ASP.NET application. Consider a case where IIS Server Time Zone is set to US EST and client is in UK using this application. The system is built to display date in  US date format and user is entering date in UK date format. So after entering date, month and date does not display as expected. User trying to enter 01/12/2014 will display as 1/12/2014 which is Jan 12, 2014. User wanted 1st Dec 2014.

Let us get into more details by looking at code and example. The ASP.NET application is designed to display date in specific format and it is set to ‘M/d/yyyy’ to RadDateInput.DisplayDateFormat throughout the application for each RadDatePicker. This means 1st December 2014 will display as 12/01/2014 everywhere in system. User from UK is using this system so the DateInput.Culture is automatically set to en-US which has date format ‘M/d/yyyy’. This can be simulated by setting properties as show in code below

<telerik:RadDatePicker DateInput-DisplayDateFormat="M/d/yyyy" DateInput-Culture="en-US" ID="RadDatePicker1" runat="server"></telerik:RadDatePicker>

Now, entering 01/12/2014 will be interpreted as Jan 12, 2014. You may confirm by clicking on Calendar icon.

So what is best way? Culture property plays import part here. Date enter by user will be broken into 3 parts. Date, Month and Year. This will be taken as input to generate actual date value. In above case Culture is set to en-US and so the date format is ‘M/d/yyyy’. The inputs are January as month, 01 as Date and 2014 as year. This will be arranged as 1/12/2014 instead of 01 December 2014.

To work in synch with end user culture, set culture based on user locale. So in this case, user using system from UK should have Culture = en-GB. This way date will interpreted way user inputs. Display format can be anything, once date parts (day, month, year) are captured correct, it can be display in any format.

Enjoy!



Thursday, November 13, 2014

Radajaxloadingpanel not showing with Custom / Composite User Control

There are times when code does not work as expected and everything looks great in HTML and code behind. This is example of such case where Telerik RadAjaxLoadingPanel and RadAjaxManager are set as expected but still loading panel is not visible. The behaviour is strange where loading panel is working for some control on page but not working for others. One control performing Ajax operation and functionality is working as expected but no loading panel. 

Problem can be described as
RadAjaxLoadingPanel is not showing for but Ajax request is firing
RadAjaxLoadingPanel is not showing for some control on page

Situation:
We have Custom / Composite ASP.NET control which renders HTML as multiple controls

For example,
CustomUserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" 
CodeFile="WebUserControl.ascx.cs" 
Inherits="WebUserControl" %>

<asp:HyperLink ID="HyperLink1" runat="server">
    <asp:Image ID="Image1" ImageUrl="test.jpg" runat="server" />
</asp:HyperLink>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">
    LinkButton
</asp:LinkButton>



Renders HTML as
<div class="RadAjaxPanel" id="WebUserControl1Panel" style="display: block;">
                <a id="WebUserControl1_HyperLink1"><img id="WebUserControl1_Image1" src="test.jpg"></a>
               <a id="WebUserControl1_LinkButton1" href="javascript:__doPostBack('WebUserControl1$LinkButton1','')">
               LinkButton
             </a>
</div>


This control is used on Test.aspx page
<%@ Page Language="C#" AutoEventWireup="true"
 CodeFile="test.aspx.cs" Inherits="test" %>
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" 
TagPrefix="telerik" %>
<%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" 
TagPrefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <telerik:RadAjaxLoadingPanel runat="server" ID="RadAjaxLoadingPanel">
            This is Loading Panel
        </telerik:RadAjaxLoadingPanel>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" 
               LoadingPanelID="RadAjaxLoadingPanel">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="WebUserControl1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="WebUserControl1"
                       LoadingPanelID="RadAjaxLoadingPanel" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
        <uc1:WebUserControl ID="WebUserControl1" runat="server" />
    </form>
</body>
</html>



Problem:
On clicking Link button Ajax request is fired but Loading Panel now showing. This can be confirmed by debugging or update link test on server side

Cause:
This is composite control rendering multiple control in HTML. In AJAX setting, AjaxControlID is the name of container control not the actual control doing Ajax.

Solution:
Update Ajax setting to the actual control ID as follows
<AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="LinkButton1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="LinkButton1" 
                        LoadingPanelID="RadAjaxLoadingPanel" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
 

That is it!
Enjoy!

Friday, November 7, 2014

SharePoint 2013 Error: This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

What is this error?
This error indicates something wrong in connectivity with SQL database and it is related to account accessing it. (The error in SharePoint 2013 says “…2010 Product”!!)

Problem found:
The Managed Account used in SharePoint was Domain account. The password for account was expired so, everything stopped working. SharePoint stores this password in database.

Solution:
  1. Change password for account in Domain Controller 
  2. Update Password in IIS Application Pools, if used
  3. From SharePoint Central Admin, update password for Managed Account

In step 3, Central admin may throw error
“The password for the account domainname\username, as currently stored in SharePoint, is not the same as the current password for the account within Active Directory”

To resolve this, open SharePoint PowerShell command prompt. Run as domainname\username (not local administrator). If local administrator is used then may get access denied


  1. Do IISRESET
  2. Set-SPManagedAccount - UseExistingPassword -Identity domainname\username
  3. This will ask for password, enter latest password. Follows rest of the commands

That’s it!
Enjoy!