RAZOR: View Engine In ASP.NET MVC 3

6. September 2010 16:26

ASP.NET MVC Visual Studio 

A new view engine is introduced in ASP.NET MVC 3 called RAZOR. You can download Preview 1 from Microsoft's download center and get it running on your machine to check the new features in MVC 3. Just in case if you are thinking that installing MVC 3 will mess your current MVC 2 installation....No, it won't. I came across a Webcamp video where Phil Haack with James Senior demonstrate this view engine. My this post is also based on the same talk.

So when you install MVC 3 Preview 1 on your machine, jump start by creating a new project in Visual Studio 2010. You will not be able to use this view engine with .NETFX 3.5 (SP1).

Now when you select new project and under Web templates you will now see ASP.NET MVC 3 application twice. The one template with (ASPX) is using normal web forms as your view engine and the other one with (Razor) is the new view engine. This is only for preview 1, these options will not be present in the final release of the MVC 3, instead you will have an oprion to select the view engine for your application later, I am not very sure how, but it will be more likely the way you select tests.

Time to check the Solution Explore. No .aspx files only .cshtml

The drawback in Preview 1 is that there is no syntax highlighting and no intellisense. Now that would have made you think "OMG! how am I going to write the code now!?". But Razor is easy and more over it too light-weight, more then I thought before I used it. Check out Index.cshtml, the markup code looks like this.

Time to take a look at Home Controller. Take a look at the Index() action method, the syntax is bit different with the one we have used previously.

 public ActionResult Index()
{      
       ViewModel.Message = "Welcome to ASP.NET MVC!";
       return View();
}

The line ViewModel.Message = "Welcome to ASP.NET MVC!"; is equivalent to:

public ActionResult Index()
{      
       ViewData["Message"] = "Welcome to ASP.NET MVC!";
       return View();
}


The ViewModel basically is of type dynamic which means that its operations will be resolved at runtime. Hover your cursor over ViewModel and Message to know about it.

If you need to show some addtional information related your current project you can set it too with ease. In the Index method you can add antoher line like this which says something about your project:

NOTE: As ViewModel is of Dynamic type, so when you press dot (.) after writing ViewModel don't expect that something will come up and as said before all expressions will be resolved at runtime.

public ActionResult Index()
{
      ViewModel.Message = "Welcome to ASP.NET MVC!";
      ViewModel.AboutApp = "This is a sample ASP.NET MVC 3 Preview 1 application!";
      return View();
}

To show this message on the Index view you will just call it by prefixing it with '@' symbol. To show the value on the page you simply write below line and prefix it with @ symbol(If you say this is simple, I would rather prefer to say it effortless).

@View.Message 
@View.AboutApp

Moving further, add a new class called Contacts (or what ever name you like) with 3 peoperties.

public class Contacts
{
    public string Name{ get; set; }
    public int Age{ get; set; }
    public string Email { get; set; }
}

Moving back to the HomeController add the below lines of code to the Index action method.

var ctc = new Contacts[] {
          new Contacts{Name="Prashant", Age = 23},
          new Contacts{Name="Arvind", Age = 24},
          new Contacts{Name="Max", Age = 23}
};

The view should not be empty this time. And therefore your Index action method return the Contacts we have just created.

public ActionResult Index()
{
ViewModel.Message = "Welcome to ASP.NET MVC!";
ViewModel.AboutApp = "This is a sample ASP.NET MVC 3 Preview 1 application!";             
var ctc = new Contacts[] {
          new Contacts{Name="Prashant", Age = 23},
          new Contacts{Name="Arvind", Age = 24},
          new Contacts{Name="Max", Age = 23}
          return View(ctc);
};
}

This time also Razor makes it simple to view the the data you returned from the controller. In the Index.cshtml you can do it pretty simply and you will still have a pretty looking markup of the view page. Create a list of contacts you have just created. As they are in a set of array, we can then enumerate the array with a foreach loop and show it on the page.

<ul>
@foreach (var c in Model){
<li> My name is @c.Name and I am @c.Age years old. </li>
}</ul>

You can easily get the data in a jiffy without writing a lot of markup. No problem in concatenating the data, the @ symbol and MVC compiler is pretty intelligent and does this for us. So what if we want to add e-mail addresses also. How this view engine will handle this ambiguity? Well let see. Just add an e-mail property to the array of contacts.

var ctc = new Contacts[] {
          new Contacts{Name = "Prashant", Age = 23, Email = "prashant@midnightprogrammer.net"
}

And on the view page the line will be something like this

<ul>
@foreach (var c in Model){
<li> My name is @c.Name and I am @c.Age years old. You can email me at @c.Email.</li>
}</ul>

Hit F5 and see it by yourself. There are lot of features described by Scott Guthrie and Phil Haack on their blog. Well I can go on writing and writing about Razor, so I think I should take a pause now and you can go to below links for more deep information about Razor view engine and to know what's new in the upcoming release of ASP.NET MVC 3.

Recommend Reading:

 No Rating

Add OpenID Login Support In Your ASP.NET Application

29. August 2010 14:50

API ASP.NET Visual Studio 

Few days back I was looking at Scott Hanselman and friend's Open Source Nerddinner project, learning and grabbing some new things from there. Apart from looking some internals I looked at the OpenID implementation. This was all a week ago and now it's time for me to write and give some thoughts on DotNetOpenAuth. For folks who are new to OpenID I am going to demonstrate how you can implement one in your project with ease.

To get started download the DotNetOpenAuth API and extract the contents from the zip file. The download also includes some samples for you to get you started. Kickstart by creating a new ASP.NET webforms project. I am just using a default template for my application, you can use the one you like or start by creating a new page. Why I am using the default template for ASP.NET webform project? well you get to know later. So now when we are done creating a new ASP.NET webform project, time to add OpenID stuff in the project. Right click References  and select Add Reference. Browse to the bin folder where you have extracted the contents of the downloaded zip file. Select DotNetOpenAuth.dll and click OK.

Changing the web.config:

A minor change in the web.config is required. Find the below lines in your web.config file:

 <authentication mode="Forms"><forms loginUrl="~/Account/Login.aspx"
timeout="2880" /></authentication>

and replace it with:

<authentication mode="Forms"><forms defaultUrl="/default.aspx"
loginUrl="~/Account/login.aspx"/></authentication>

In the above configuration, loginUrl will always point towards to the login page and the defaultUrl will always point towards the page/URL which will be displayed when the authentication is successfull.

Implemeting OpenID support:

To implement OpenID support, open login.aspx page in the design view and then drag the OpenIdLogin from the toolbox on the page just after the default login implementation ends or where you want to have OpenID login. If you are not able to view the control, then you can browse the same dll you have add a reference in the above step.

If you want to implement this manually then register the control at the top of the page and then use it on the page.

Register the control:

<%@ Register Assembly="DotNetOpenAuth" Namespace="DotNetOpenAuth.OpenId.RelyingParty"
TagPrefix="rp" %>

To use the control on the page you can then simply write:

<rp:OpenIdLogin ID="OpenIdLogin1" runat="server"></rp:OpenIdLogin>

All done now and it's time to test our application. Hit F5 and login with your openID. The page rendered in front of you is

Enter your openID and click login. You will be redirected to the official OpenID login page

Enter your password for openID account and after the authentication is successfull you will be re-directed to the default page. Remember the web.config configuration we did!!? If everything goes well you can see your openID name login name on the top of the page.

This is the simplest way to implement openID. You can also implement openID on your ASP.NET MVC project to add some flexibility for you site users. Apart from this you can also download the Visual Studio 2010 template

Download: DOTNETOAUTH.zip (542.85 kb)

Related Links:

Currently rated 4.0 by 2 people

Deprecated APIs In .NET 4.0

20. July 2010 11:10

.NET Framework API Visual Studio 

A number of existing APIs are deprecated in .NET Framework 4.0. A complete listing of deprecated APIs in .NET Framework 4.0 can be found here at MSDN:

 

 No Rating

Build “Out of Browser” Applications with Silverlight

20. June 2010 09:30

Silverlight Visual Studio 

If you think that Silverlight applications are only intended to be run on web browsers, then you are wrong! Silverlight is now widely used to build Rich Internet Application (RIA) allowing users to work more efficiently and make a working session more interactive and attractive. As we all know a customer will always seek for a short-cut method, he will never listen to your comments or suggestions and wants everything to be done in few mouse clicks. A lazy customer! You build an application with a lot of effort and upload it to the user or customer’s website. Now the customer wants the same application for his desktop - he doesn’t want to open browser and work. Writing the same application again for his desktop won’t help and will also waste a lot of development time, why can’t we make the same Silverlight application to run from his machine?

Silverlight gives you an option to install the Silverlight application from the browser to your desktop called “Out of Browser” application support. Consider if you have built a game on Silverlight and upload it to your blog/website allowing you reader or visitors to play the game. It’s not just the case with games but same can be done with applications or with some general web utility like URL shortening service using Bit.ly API.

To get started create a new Silverlight application in Visual Studio 2010.

Give the name to your application and click OK.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 Design your application put the business logic in (if any). Once you are done designing and building the application go to the project properties. Click Project > APPNAME Properties. APPNAME represents the name of your application. In the project properties check the “Enable running application out of browser”.

Out-of-Browser Settings button will get enabled which will let you choose out of browser application settings.

The settings dialogue box is quite self-explanatory. You can set the name of the application which you want to put on the window when it runs out of the browser. You can also set the icon for you application in different sizes. Click OK to save settings.

Now, run you application. You will see your Silverlight application running inside your browser. If you want the application to run out of the browser then right-click anywhere in the browser and click “Install <APPNAME> onto this computer”.

This will prompt you to install the application and place the application icons on your desktop or on your start menu or both. It will give your application the default application install icon. If you have set your own in the Out of Browser Settings then you will see your icon.

 

Now your Silverlight application is on your system and can be executed at user’s desktop. Check out the same demo here. It's just a demo anyway!

 No Rating

How To Build UAC Compatible Application In .NET

23. May 2010 21:01

C# Utils Visual Studio Windows 

We all know about a feature called User Account Control (UAC) which introduced with the launch of Windows Vista. By default, UAC is enabled and provides users a better and safer computing experience, but most of the users find it irritating when the UAC prompts everytime they try to run a program. Disabling UAC is not recommended at all.

With UAC enabled programmers find it difficult to access some of the locations on the local drive. Programatically you cannot write or create a file or directory in root partition, inside Program Files, System32 folder and some other locations. Recently I ran into a same problem where I have to access System32 folder, create new folders and copy files from one location on my system to this folder. With UAC disabled this is pretty easy, no security settings and no runtime errors or exceptions. Usually you cannot ask the users to disable UAC and then use the application, so therefore I made my application compatible with UAC and YES!!! you will be prompted with the confirmation box to run the application with administrator privileges. In Windows Vista and Windows 7, even if you are an administrator of your machine you do not have the complete access to resources even if you are an administrator. So in order to make your application run with full administrator rights follow the steps below. This will work the same if you run your application with "Run as Administrator" option which you see when you right-click the application.

Create a new application in Visual Studio. Right-click project and add a new item.

From the Add New Item box select Application Manifest File.

In the manifest file un-comment the following line:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Build your applicaton....and when the build is complete you will see the security shield icon accompanying your application icon. A dialogue box appear in front of the user to run the application with full administrative privileges.

Currently rated 4.5 by 2 people