Yanesh Tyagi writes …

September 27, 2008

My First ASP.Net MVC Appliacation

Filed under: .Net, Programming, Technology, Web Technology — yaneshtyagi @ 4:50 pm
Tags: ,

I was thinking about MVC since I read first post on ScottGu’s blog. Yesterday, on Friday night, I decided to create my first MVC applications. I downloaded Visual Web Developer 2008 Express Edition 2008 last night. That 128 MB download took quite a long time to download. Then I downloaded MVC preview 5. After successful installation of MVC, I was ready to fly…

Finding a suitable example on the web:
Before starting develop a new MVC project,  I needed a good example. After searching the web for a while, I found two links that seems to be useful.

First was a 4 part tutorial written by ScottGu. I was a detailed introduction to MVC framework and how it works. I was like a step by step DIY guide. Scott demonstrated how to create a complete e-commerce site using MVC framework.

The second choice was a simple To Do List application. This application allowed one to enter a list of tasks, save these into database and mark them complete. Both applications used LINQ to SQL for accessing database.

I decided to go with the Task List application as this was simple and small application. This app is like the typical Hello World example with database support. I took only one hour to complete this app and run it properly.

Starting the new project
I opened VWD (Visual Web Developer0 and choose to create new project. MVC applications are developed as web applications. They are different from web sites. In the New Project dialog, I chose ASP.NET MVC Web Application. This automatically created a sample application in the solution explorer with three special meaning folders – Controller, Model and View. I deleted the classes and pages auto-generated by the WVD. The I proceed step by step as instructed in the example application.

Step By Step Progress Through Solving Issues:
Once I completed typing (yes, I preferred to type instead of copy-pasting it) the code and creating all the classes and pages, I was time to see the code in action. But as you know, no code runs for the very first time. Although VWD (and VS as well) minimizes the  chances of syntax errors to zero, many other types of error always occurs in the code. I face following problems for which I again need to do some Googling.

The ViewData Problem:

“The name ‘ViewData’ does not exist in the current context”

Even before compiling the code, my Index.aspx view warned me that ViewData is undefined by placing a red line below this. After some unsuccessful silly adjustment to the code, I go for Googling. I found a post in ASP.net forums asking for the same question. ScottGu answered the post by saying – “Have you tried compiling the project?  It could be that you haven’t done a compile since you added the page, and so intellisense with C# hasn’t picked up that you are deriving from a base-class yet”. This was very strange for me but I decided to go with Scott and compiled the code successfully. But when I run the code, the same problem reappeared.

After 20 minutes of unsuccessful Googling, I decided to use trial-and-error method. And finally I got the solution.

Solution:
The root cause of the problem was that I added a Web Form in my Views folder instead of MVC View Content Page. The normal web form is inherited from System.Web.UI.Page class  while an MVC View Content Page is inherited from System.Web.Mvc.ViewPage class. I change the parent class to ViewPage and it worked fine.

Primary key error in inserting the record:
Now I rum my application without any error. The Index page that displays a list of all tasks appears on the browser. I opened create page to add a new task. On pressing submit button, it gave primary key related error. The error was cause by the InserOnSubmit method of the LINQ generated class. The error was quite obvious that I forgot to define primary key on the table. I had an Id column with its Identity attribute set to on. So, ideally any insert statement should not have issue with the primary key. But to fix the error, I modified the table structure and declare Id column as primary key. But the problem still persisted. Like the above issue, Googling was unsuccessful in this case as well and I had to go for trial-and-error method.

Solution:
The solution was quite simple. I had to open the dbml file which is used for LINQ-to-SQL. I deleted the table from this file and again dragged that table into dbml designer from Server Explorer. Pressed F5 and the page was opened successfully in the browser. Opened the create page, added a task and pressed submit button. No error…
I checked into database table and the record was successfully inserted.

So this was the experience of developing first MVC application. The overall experience was good and exciting. I liked the simple and easy-to-read URLs that were displayed in the browser’s address bar.

Keep watching for more in ASP.Net MVC

Technorati Tags: ,

kick it on DotNetKicks.com

Scott Guthrie’s ASP.net MVC Tutorial Links

Filed under: .Net, Programming, Technology, Web Technology — yaneshtyagi @ 12:13 pm
Tags: ,

ASP.NET MVC Framework
One of the things that many people have asked for over the years with ASP.NET is built-in support for developing web applications using a model-view-controller (MVC) based architecture. Last weekend at the Alt.NET conference in Austin I gave the first…

ASP.NET MVC Framework (Part 1)
Two weeks ago I blogged about a new MVC (Model View Controller) framework for ASP.NET that we are going to be supporting as an optional feature soon. It provides a structured model that enforces a clear separation of concerns within applications, and…

ASP.NET MVC Framework (Part 2): URL Routing
Last month I blogged the first in a series of posts I’m going to write that cover the new ASP.NET MVC Framework we are working on.  The first post in this series built a simple e-commerce product listing/browsing scenario.  It covered the high…

ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views
The last few weeks I have been working on a series of blog posts that cover the new ASP.NET MVC Framework we are working on.  The ASP.NET MVC Framework is an optional approach you can use to structure your ASP.NET web applications to have a clear…

ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios
The last few weeks I have been working on a series of blog posts that cover the new ASP.NET MVC Framework we are working on.  The ASP.NET MVC Framework is an optional approach you can use to structure your ASP.NET web applications to have a clear…

ASP.NET MVC Preview 5 and Form Posting Scenarios
This past Thursday the ASP.NET MVC feature team published a new “Preview 5″ release of the ASP.NET MVC framework.  You can download the new release here .  This “Preview 5″ release works with both .NET 3.5 and the recently…

Technorati Tags: ,

kick it on DotNetKicks.com

August 10, 2008

VB.net to c# converter

Filed under: .Net, Programming, Technology — yaneshtyagi @ 9:58 am
Tags: , ,

Many times we need to convert VB.net code to c#. There are many utilities to do this. but none of these is perfect as these have one or other shortcomings. Most of these utilities are the windows apps written in c# language. The draw back of windows app is that you need to upgrade the app at times.

I was looking for an online app for the conversion. And after some googling I found a cool online tool from the Developer Fusion Lab. This conversion tool is quite accurate in conversion and if it could not convert any code then it inserts the error message into the code. So one can easily identify the error message and do the manual conversion.

Link:
Convert VB.NET to C# – A free code conversion tool from Developer Fusion

June 3, 2008

True / False in classic VB

Filed under: Programming, Technology — yaneshtyagi @ 10:03 am
Tags: ,

In classic VB (and classic ASP as well), zero is considered as false and any other non-zero integer is considered as true.

While debugging an asp page, I come across following line:

If Not Request.Form.Count Then

Now form count was 2 (true) so the condition should evaluate as false (Not true). But this was always evaluating as true. It took me half an hour to find the catch.

What actually happening here was that Not is a bit-wise operator in VB. It flips the bits. So,

2 is 0000 0010 in binary.
NOT 2 is 1111 1101 in binary.

Considering that the last bit is sign bit, this becomes -3.

Now our condition If NOT (2) becomes If (-3), which always evaluates to true (non-zero integers are always true in VB).

Technorati Tags: ,,,

May 26, 2008

Automatic Formatting of Markup (HTML) in ASP.NET

Daniel at dimebrain did a really fantastic work writing a plug-in for VS that can format the markup in asp.net. When you build a web page using the VS designer, it auto generates the markup. But the auto generated code so clustered and impossibly hard to read.  You have to manually format the markup (HTML) code by hand. This is always very tiresome and boring job. Also this is wastage of time.

Daniel also felt the same. After being inspired by the Joe Stagner, he developed this plug-in. It provides an additional Edit menu item and hotkey (Ctrl+K, Ctrl+Z) to automatically line up attributes in a selection of text, or format the entire document if no text is selected. The meat of the add-in is a handful of regular expressions that parse tags (XAML, HTML, and ASP.NET directives) and a few IDE tools to line them up according to their indent level.

Download Links:

Screen Shots:

November 28, 2007

Effective Use Of Visual Studio 2005 – Handling Open Documents

Filed under: .Net, Programming, Technology — yaneshtyagi @ 12:48 pm
Tags: , , ,
Visual Studio 2005 provides some excellent document management capabilities. Most of the we are not aware of these features. One of the feature is open document tab groups. Unlike VS 2003, it shows only as much tabs as fits in the window width. There is no scrolling. Instead, VS 2005 provides dropdown menu to select from all open documents. Inseated of selecting open documents, you can also do some other functions.
I am planning to write a series on useful-but-less-known features of VS 2005. This is second post in the series. (read first post)

In continuation to my previous post on managing open documents, here are some more tricks.

Right click on the open document tab group. A context menu will appear with following options:
  1. Save default.aspx.vb
  2. Close
  3. Close all but this
  4. Copy full path
  5. Open containing folder
  6. New horizontal tab group
  7. New vertical tab group

Save default.aspx.vb

Allows you to save currently selected document. Currently selected document is the one which is open in the window.
Close
Close currently selected document.
Close all but this
Close all open documents except the currently selected document.
Copy full path
Copy full path of the currently selected document to the clipboard.
Open containing folder
Open the folder that contains the currently selected document. The folder is opened in the windows explorer.

New horizontal tab group
Open another document window. The two windows are tiled horizontally. Both window will have document tab group. This is useful when you want to open on two group of documents simultaneously.

New vertical tab group

Same as above option. But this makes the windows tiles vertically instead of horizontally.

November 27, 2007

Effective Use of Visual Studio 2005 – Closing Selected Window

Filed under: .Net, Programming, Technology — yaneshtyagi @ 10:20 am
Tags: , , ,
To close open documents selectively:
1. Go to Window -> Windows.

2. This will show list of all open windows (not just those which you see on the tabs).

3. Select the windows you want to close. Use shift (or ctrl) key for multiple selection. You can also use ctrl+A to select all windows.

4. Click “Close window(s)” button to close selected windows.

I experienced that the speed of loading a project into visual studio is directly proportional to the number of open documents. Generally, we open the document as we need it. And then we don’t close it. Visual studio 2005 displays only a few number of documents on the tabs. Rest remains open but are hidden. You can click on the down arrow near the ‘X’ button of the document window to select the open document. To keep you project loading fast, always keep minimum number of open documents.

November 20, 2007

Visual Studio 2008 and .NET 3.5 Released

Filed under: .Net, Programming, Technology — yaneshtyagi @ 6:44 am
Tags: , , ,

Microsoft shipped Visual Studio 2008 and .NET 3.5 today. Here are some resources for VS 2008:

1. ScottGu’s weblog is the primary and authentic source of information।
२. Somasegar’s Weblog
3. Paul Andrew blogged about a downloadable poster of commonly used types and namespace in .NET 3.5 (in pdf format), which is worth checking out.
4. View ASP.NET 3.5-specific videos at Microsoft’s official asp.net website.
5. Brad Abrams wrote about Design Guidelines, Managed code and the .NET Framework 3.5 in his blog.
6. Here is a 31 minute video at Channel 9.
7. VS 2008 is not shipped with MSDN. You can Download MSDN Library for VS 2008 from here.
8. The details about VS 2008 express edition (free) are available here.

November 15, 2007

Putting ASP.net Application In Offline Mode Using app_offline.htm

Today, I was updating a stored procedure of SQL Server Express Edition 2005 within the Visual Studio 2005. At the same time, I tried to open a page of my application in internet browser using IIS (localhost). And I got the error stating:

‘The application is currently offline. Remove app_offline.htm file from applications root directory.

I never heard of app_offline.htm file before. As a habit I pressed ‘F5′ to refresh the page and it worked fine. ‘What the hell was this?’, I thought. I googled about the file in error message and learned some interesting facts. Here is what I found:

app_offlinne.htm

When ASP.Net found a file names app_offlinne.htm in the root of a web application directory, it shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application. ASP.NET also then respond to all requests for dynamic pages in the application by sending back the content of the app_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

Visual Studio 2005 And app_offline.htm

SQL Server 2005 express edition does not support multiple processes. Only single process can access database at a time. So when a database is accessed through visual studio, ASP.net runtime cannot access the database. This will result into the internal server error.  To prevent this, VS 2005 places app_offline.htm file in the application’s root directory. The file contain above message. This causes ASP.net to put the application in offline mode. Please note the accessing database means opening any component of the database (I.e. table, view, stored procedure etc.) into the design window. When design window is closed, VS 2005 removes app_offline.htm file.

Using app_offline.htm As A Feature

You may use app_offline.htm feature to put your application in offline mope for any purpose. This provides a convenient way to take down your application while you are making big changes or copying in lots of new page functionality (and you want to avoid the annoying problem of people hitting and activating your site in the middle of a content update). It can also be a useful way to immediately unlock and unload a SQL Express or Access database whose .mdf or .mdb data files are residing in the /app_data directory.

You should keep an eye on a feature of IE6 called “Show Friendly Http Errors”.  This can be configured in the Tools->Internet Options->Advanced tab within IE, and is on by default with IE6.  When this is on, and a server returns a non HTTP-200 status code with less than 512 bytes of content, IE will not show the returned HTML and instead substitutes its own generic status code message (which personally I don’t think is super friendly <g>).

So if you use the app_offline.htm feature, you should make sure you have at least 512 bytes of content within it to make sure that your HTML (instead of IE’s friendly status message) shows up to your users.  If you don’t want to have a lot of text show-up on the page, one trick you can use is to just add an html client-side comment with some bogus content to push it over 512 bytes.

Once you remove the app_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and life will continue along as normal.

References:

  1. Andy Gray wrote an interesting story on how his application stops working and starts giving error 404 when he killed visual studio process.
  2. Phill Scott writes his experience about suddenly getting error 404 and finding the app_offline.htm file culprit.
  3. Chris Ullman, author of Beginning ASP.NET 2.0 also had similar experience.

Acknowledgement

I must thank ScottGu for providing useful details about this mysterious file. I could not found any official documentation from Microsoft about this. But ScottGu’s blog is as authentic as Microsoft’s documentation.

kick it on DotNetKicks.com

October 22, 2007

HTTP Modules’ Events and Their Order of Firing

Filed under: .Net, Programming, Technology — yaneshtyagi @ 6:50 pm
Tags: ,

Below is the list of Events raised by HttpHandlers. These events are in the sequence of firing.

OnBeginRequest
OnAuthenticateRequest
OnPostAuthenticateRequest
OnAuthorizeRequest
OnPostAuthorizeRequest
OnResolveRequestCache
OnPostResolveRequestCache
OnPostMapRequestHandler
OnAcquireRequestState
OnPostAcquireRequestState
OnPreRequestHandlerExecute
Page_Load Event of the Page
OnPostRequestHandlerExecute
OnReleaseRequestState
OnPostReleaseRequestState
OnUpdateRequestCache
OnPostUpdateRequestCache
OnEndRequest
OnPreSendRequestHeaders

I wrote a http handler to check the sequence of execution of event handlers. Below is the program. Two events in the program are commented because these require integration with the IIS pipeline. I used Visual Web Developer 2008 Express Edition Beta 2 to write this program. So may be express edition does not support integration with IIS. I haven’t checked it yet. Here is the program:

using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Xml.Linq;

/// <summary>

/// Summary description for AddSign

/// </summary>

public class AddSign: IHttpModule

{

public delegate void MyEventHandler(Object s, EventArgs e);

private MyEventHandler _eventHandler = null;

public event MyEventHandler MyEvent

{

add { _eventHandler += value; }

remove { _eventHandler -= value; }

}

public AddSign()

{

//

// TODO: Add constructor logic here

//

}

#region IHttpModule Members

void IHttpModule.Dispose()

{

//throw new NotImplementedException();

}

void IHttpModule.Init(HttpApplication context)

{

//throw new NotImplementedException();

context.EndRequest += new EventHandler(OnEndRequest);

context.AcquireRequestState += new EventHandler(OnAcquireRequestState);

context.AuthenticateRequest += new EventHandler(OnAuthenticateRequest);

context.AuthorizeRequest += new EventHandler(OnAuthorizeRequest);

context.BeginRequest += new EventHandler(OnBeginRequest);

context.Disposed += new EventHandler(OnDisposed);

context.Error += new EventHandler(OnError);

//context.LogRequest += new EventHandler(OnLogRequest); //This operation requires IIS integrated pipeline mode.

//context.MapRequestHandler += new EventHandler(OnMapRequestHandler); //This operation requires IIS integrated pipeline mode.

context.PostAcquireRequestState += new EventHandler(OnPostAcquireRequestState);

context.PostAuthenticateRequest += new EventHandler(OnPostAuthenticateRequest);

context.PostAuthorizeRequest += new EventHandler(OnPostAuthorizeRequest);

context.PostMapRequestHandler += new EventHandler(OnPostMapRequestHandler);

context.PostReleaseRequestState += new EventHandler(OnPostReleaseRequestState);

context.PostRequestHandlerExecute += new EventHandler(OnPostRequestHandlerExecute);

context.PostResolveRequestCache += new EventHandler(OnPostResolveRequestCache);

context.PostUpdateRequestCache += new EventHandler(OnPostUpdateRequestCache);

context.PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute);

context.PreSendRequestContent += new EventHandler(OnPreSendRequestContent);

context.PreSendRequestHeaders += new EventHandler(OnPreSendRequestHeaders);

context.ReleaseRequestState += new EventHandler(OnReleaseRequestState);

context.ResolveRequestCache += new EventHandler(OnResolveRequestCache);

context.UpdateRequestCache += new EventHandler(OnUpdateRequestCache);

}

#endregion

public void OnEndRequest(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnEndRequest<br />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnAcquireRequestState(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnAcquireRequestState”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnAuthenticateRequest(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnAuthenticateRequest”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnAuthorizeRequest(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnAuthorizeRequest”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnBeginRequest(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnBeginRequest”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnDisposed(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnDisposed”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnError(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnError”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

app.Context.Response.Write(“<BR />”);

_eventHandler(this, null);

}

public void OnLogRequest(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnLogRequest”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnMapRequestHandler(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnMapRequestHandler”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostAcquireRequestState(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostAcquireRequestState”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostAuthenticateRequest(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostAuthenticateRequest”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostAuthorizeRequest(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostAuthorizeRequest”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostMapRequestHandler(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostMapRequestHandler”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostReleaseRequestState(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostReleaseRequestState”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostRequestHandlerExecute(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostRequestHandlerExecute”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostResolveRequestCache(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostResolveRequestCache”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPostUpdateRequestCache(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPostUpdateRequestCache”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPreRequestHandlerExecute(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPreRequestHandlerExecute”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPreSendRequestContent(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPreSendRequestContent”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnPreSendRequestHeaders(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnPreSendRequestHeaders”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnReleaseRequestState(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnReleaseRequestState”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnResolveRequestCache(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnResolveRequestCache”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

public void OnUpdateRequestCache(Object s, EventArgs e)

{

HttpApplication app = s as HttpApplication;

app.Context.Response.Write(“OnUpdateRequestCache”);

app.Context.Response.Write(“<BR />”);

if (_eventHandler != null)

_eventHandler(this, null);

}

}

Blog at WordPress.com.