Wednesday, November 23, 2011

What is difference between ViewData,ViewBag and TempData in MVC 3.0

ViewData: ViewData is a dictionary of objects that are accessible using strings as keys Eg.
1.ViewData[“JustLearn”]=”Just Learn on Beyond relational is rock!!”
ViewBag:ViewBag uses the dynamic feature that was added in to C# 4.0 It allows an object to dynamically have properties added to it. We can say viewBag=ViewData + dynamic wrapper around the ViewData dictionary. Eg.
1.ViewBag.JustLearn =”Just Learn on beyondrelational is rock!!”
TempData: Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. Eg.
view source
print?
1.TempData[“JustLearn”]=”Just Learn on beyondrelational is rock!!”
Hold Up

Search and Filters in Error List Window – Visual Studio 2011 Developer Preview

The Visual Studio “Error List Window” helps you display the errors, warnings, and messages produced during compiling code, build, code analysis or even some other scenarios as well. We can click on the particular error, warning or message to get the exact details and cursor moves to location where error or warning causes. When we are dealing with multiple project in a single solution, it is very much difficult to find out exact error within a specific file or with in a solution. We need to scroll through entire error list to get the file, errors, messages or warnings. Visual Studio 2011 introduced search and filtering with in error list window.

Visual Studio 2011 added a search box to the Error List to help you find the error, warning, or message. Just for example, if you are looking for an error with in a specific file, just enter the file name in search box, Error list will display the error, warnings and messages from the given file.

New Color Picker in Visual Studio 2011 Developer Preview for CSS

CSS editor in Visual Studio 2011 introduced many new features for web developers and it helps developers to work with CSS more efficiently and organize way. One of the nice features of the new CSS Editor is Color Picker. While designing styles for web applications, web developers refers different tool to choose the color and color code. But now, there is an integrated Color Picker that helps developer to pick up the color within editor itself.

In CSS Editor, locate the cursor next to any color attribute and press Space. A color pickup automatically popups up. You can select the color as per your requirements.

Hold Up

Creating Custom HTML Helpers in ASP.NET MVC

List of built-in HTML Helpers provided by ASP.NET MVC.

ActionLink() – Links to an action method.
BeginForm() – Marks the start of a form and links to the action method that renders the form.
CheckBox() – Renders a check box.
DropDownList() – Renders a drop-down list.
Hidden() – Embeds information in the form that is not rendered for the user to see.
ListBox() – Renders a list box.
Password() – Renders a text box for entering a password.
RadioButton() – Renders a radio button.TextArea() – Renders a text area (multi-line text box).
TextBox () – Renders a text box.

How to develop our own Custom HTML Helpers?

For developing custom HTML helpers the simplest way is to write an extension method for the HtmlHelper class. See the below code, it builds a custom Image HTML Helper for generating image tag.

using System;
using System.Web.Mvc;
namespace MvcHelpers
{
public static class CustomHtmlHelpers
{
public static TagBuilder Image(this HtmlHelper helper, string imageUrl, string alt)
{
if (!String.IsNullOrEmpty(imageUrl))
{
TagBuilder imageTag = new TagBuilder("img");
imageTag.MergeAttribute("src", imageUrl);
imageTag.MergeAttribute("alt", alt);
return imageTag;
}
return null;
}
}
}

TagBuilder represents a class that is used by HTML helpers to build HTML elements.
TagBuilder.MergeAttribute(String, String) method adds an attribute to the tag by using the specified key/value pair.

The next step is in order to make it available to Views, we should include the name space of out custom HTML helper class into Web.config

Build the solution to make sure the helper method is available to views. Goto any view in the solution access the newly created HTML image helper method.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>


Home




<%= Html.Encode(ViewData["Message"]) %>


<%=Html.Image("/Images/logo.png","logo") %>





<%=Html.Image(“/Images/logo.png”,”logo”) %>

The image HTML helper generates the following HTML.

”logo”/

Image Tag Helper is simple example of HTML helpers, we can put any sort of complex logic into HTML Helpers & access them with in the views with a simple method call. in turn which makes the view simpler.

How To Create Session-less Controller in MVC3

How to manage the controller’s session state?

Simply we can decorate the controller class with “SessionState” attribute. [SessionState()] attribute accepts SessionStateBehaviour enumeration.

SessionStateBehaviour enumeration has the following constants.

SessionStateBehavior.Default - ASP.NET default logic is used to determine the session state behavior for the request.
SessionStateBehavior.Required – Full read-write session state behavior is enabled for the request.
SessionStateBehavior.ReadOnly – Read only session state is enabled for the request.
SessionStateBehavior.Disabled – Session state is not enabled for processing the request.

How to return 404 Http status code from ASP.NET MVC Application?

ASP.NET MVC3 includes a new class HttpNotFoundResult in System.Web.Mvc namespace.

HttpNotFoundResult: Instance of HttpNotFoundResult class indicates to client(browser) that the requested resource was not found. It returns a 404 HTTP status code to the client. Generally we return 404 status code if a requested webpage is not available. In case of MVC applications we return 404 status code is in terms of resources, for example we are searching for particular user profile in the portal, if the user profile is not found, we can return 404.

How to return 404 status code from a MVC application?

First way is to instantiate HttpNotFoundResult class and return the object.

public ActionResult Index()
{
var result = new HttpNotFoundResult();
return result;
}

Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.

public ActionResult Index()
{
return HttpNotFound();
}

we can return 404 along with custom status code description,using the overloded version of HttpNotFound(string statusDescription).

public ActionResult Index()
{
return HttpNotFound("can not find requested resource");
}

How to select Block of Code in Visual Studio?

You can select line by line code very easily using mouse or keyboard. But if you want to copy some code block where you don’t to select all part of line or something like that, here is a Quick TIP For you. Press and Hold “Alt” Key, and select the code region..

Generate Method Stubs using Shortcut Key in Visual Studio

Ctrl + .” Or “ALT + SHIFT+F10” is one of the very useful shortcut key in Visual Studio. You can use that shortcut key to generate the methods stubs. Like, If you want to create method which will add to number, you can write like AddTwoNumber() and press “Ctrl+.” and Enter to generate the Stub for your methods automatically

Tuesday, November 22, 2011

Automatic Tag Update in Visual Studio 2011 Developer Preview

Visual Studio 2011 Developer Preview introduced a nice features that helps you to update HTML Start and End tag automatically. In previous version of Visual Studio If you wanted to update any html tags in markup you have had to update both start and end tags manually but, Visual Studio 2011 developer preview automatically update the tag with change of any one.

Monday, November 21, 2011

Clean up after Visual Studio

As programmer’s we know that if we create a temporary file during the running of our application we need to make sure it is removed when the application or process is complete. We do this, but why can’t Microsoft do it? Visual Studio leaves tons of temporary files all over your hard drive. This is why, over time, your computer loses hard disk space. This blog post will show you some of the most common places where these files are left and which ones you can safely delete.

.NET Left Overs

Visual Studio is a great development environment for creating applications quickly. However, it will leave a lot of miscellaneous files all over your hard drive. There are a few locations on your hard drive that you should be checking to see if there are left-over folders or files that you can delete. I have attempted to gather as much data as I can about the various versions of .NET and operating systems. Of course, your mileage may vary on the folders and files I list here. In fact, this problem is so prevalent that PDSA has created a Computer Cleaner specifically for the Visual Studio developer. Instructions for downloading our PDSA Developer Utilities (of which Computer Cleaner is one) are at the end of this blog entry.

Each version of Visual Studio will create “temporary” files in different folders. The problem is that the files created are not always “temporary”. Most of the time these files do not get cleaned up like they should. Let’s look at some of the folders that you should periodically review and delete files within these folders.

Temporary ASP.NET Files

As you create and run ASP.NET applications from Visual Studio temporary files are placed into the :\Windows\Microsoft.NET\Framework[64]\\Temporary ASP.NET Files folder. The folders and files under this folder can be removed with no harm to your development computer. Do not remove the "Temporary ASP.NET Files" folder itself, just the folders underneath this folder. If you use IIS for ASP.NET development, you may need to run the iisreset.exe utility from the command prompt prior to deleting any files/folder under this folder. IIS will sometimes keep files in use in this folder and iisreset will release the locks so the files/folders can be deleted.

Website Cache

This folder is similar to the ASP.NET Temporary Files folder in that it contains files from ASP.NET applications run from Visual Studio. This folder is located in each users local settings folder. The location will be a little different on each operating system. For example on Windows Vista/Windows 7, the folder is located at :\Users\\AppData\Local\Microsoft\WebsiteCache. If you are running Windows XP this folder is located at :\ Documents and Settings\\Local Settings\Application Data\Microsoft\WebsiteCache. Check these locations periodically and delete all files and folders under this directory.

Visual Studio Backup

This backup folder is used by Visual Studio to store temporary files while you develop in Visual Studio. This folder never gets cleaned out, so you should periodically delete all files and folders under this directory. On Windows XP, this folder is located at :\Documents and Settings\\My Documents\Visual Studio 200[5|8]\Backup Files. On Windows Vista/Windows 7 this folder is located at :\Users\\Documents\Visual Studio 200[5|8]\.

Assembly Cache

No, this is not the global assembly cache (GAC). It appears that this cache is only created when doing WPF or Silverlight development with Visual Studio 2008 or Visual Studio 2010. This folder is located in :\ Users\\AppData\Local\assembly\dl3 on Windows Vista/Windows 7. On Windows XP this folder is located at :\ Documents and Settings\\Local Settings\Application Data\assembly. If you have not done any WPF or Silverlight development, you may not find this particular folder on your machine.

Project Assemblies

This is yet another folder where Visual Studio stores temporary files. You will find a folder for each project you have opened and worked on. This folder is located at :\Documents and Settings\Local Settings\Application Data\Microsoft\Visual Studio\[8|9].0\ProjectAssemblies on Windows XP. On Microsoft Vista/Windows 7 you will find this folder at :\Users\\AppData\Local\Microsoft\Visual Studio\[8|9].0\ProjectAssemblies.

Remember not all of these folders will appear on your particular machine. Which ones do show up will depend on what version of Visual Studio you are using, whether or not you are doing desktop or web development, and the operating system you are using.

ASP.NET 4.5 Preview: Using model binding to update data

one of my current projects I have to show reports based on SQL Server views. My code should be not aware of data it shows. It just asks data from view and displays it user. As WebGrid didn’t seem to work with DataTable (at least with no hocus-pocus) I wrote my own very simple view that shows contents of DataTable.

I don’t focus right now on data querying questions as this part of my simple generic reporting stuff is still under construction. If the final result is something good enough to share with wider audience I will blog about it for sure.

My view uses DataTable as model. It iterates through columns collection to get column names and then iterates through rows and writes out values of all columns. Nothing special, just simple generic view for DataTable.
@model System.Data.DataTable
@using System.Data;

Report






@foreach (DataColumn col in Model.Columns)
{

}



@foreach (DataRow row in Model.Rows)
{

@foreach (DataColumn col in Model.Columns)
{

}

}

@col.ColumnName
@row[col.ColumnName]


In my controller action I have code like this. GetParams() is simple function that reads parameter values from form. This part of my simple reporting system is still under construction but as you can see it will be easy to use for UI developers.
public ActionResult TasksByProjectReport()
{
var data = _reportService.GetReportData("MEMOS",GetParams());
return View(data);
}

Before seeing next silver bullet in this example please calm down. It is just plain and simple stuff for simple needs. If you need advanced and powerful reporting system then better use existing components by some vendor.

Friday, November 18, 2011

Why should we use MVC vs normal ASP.NET

There are various positive points to moving towards MVC

1. SEO friendly URL by design (though now this is possible in ASP.NET 4 as well)
2. No ViewState (this may seem a bit of moving backward to some), but overall a good design decision.
3. Clean View Markup (no additional HTML emitted)
4. 100% extensible. You can add your own controller with IOC, switch view engines at will, control model binding at wish etc.
5. Rich UI support (possible through client side JS libraries like jQuery UI and others). Telerik has released some controls for MVC which includes Grid control as well (which are merely HTMLHelpers)
6. Session, JS, Ajax works. Validation is even more powerful with DataAnnotations and jquery.
7. Is MVC faster? Yes by default because of lack of viewstate and clean markup. But performance is subject and MVC by design is more performant that traditional ASP.NET webforms (though webforms can be made as fast as required.
8. Out of the box support for mitigating antiforgery attacks and XSS vulnerability (though asp.net does has this to some extent)
9. Out of the box minimal IOC support.
10. Full control over rendered HTML

MVC 3 dynamic authorization of multiple roles and users

[Authorize(Roles="Admin")]
public ActionResult UpdateArticle(ArticleModel model, int articleid)
{
return View();
}

Friday, November 4, 2011

.Net Shorcut

F6 / Shift+F6 / Ctrl+Shift+B : Build solution / Build project /
Build solution
Shift+Alt-C : Add a new class to your project
Ctrl+K+C : Comment a selected block of code
Ctrl+K+ U : Un-comment a selected block of code
Ctrl+M+O / Ctrl+M +P : Collapse all code to definitions /
Expand all code (stop collapsing)
Ctrl+Alt+L : Show the solution explorer
Ctrl+Shift+A / Alt+Shift+A : Add a new item to your project /
add an existing item to your project
Ctrl+K+F and CRTL+K+D : These two will format the code in the
window to be nicely indented. using "d" will format all the
document while using "f" will format only selected text. The
formatting is for all types of documents, HTML, Xaml, XML,
C#… This one is my favorite
Sift+Del : It’s just a regular cut (exactly the same as ctrl-x). This
one will cut the entire row from the document and past it to
the clipboard. No need to select the row, just put the marker
there and click SHIFT+Del and it is gone
Ctrl+K+S : This one opens up the code snippets dialogue within
the code
Ctrl+Space: Completes the symbol you're currently typing or
gives you a choice of various possibilities
F12 : This is the shortcut for the "Go to definition" command
which will take you to the definition of the object your marker
is currently on
F9 : This will add a breakpoint to the code line your marker is
currently at. Clicking F9 again will remove this breakpoint from
that line
Ctrl-M-M : This will expand or collapse based on where the
cursor is. Useful when everything is collapsed and you just
want to expand one of them.