Session: Web Development using ASP.NET MVC

Yesterday, on 26th March, I was invited to talk on Web Development using ASP.NET MVC organized by Microsoft Pakistan in collaboration with Higher Education Commission (HEC).
I am really glad to see the video conference setup by HEC. The session was broadcasted LIVE to around 10 Universities across Pakistan connecting hundreds of students with live Q&A session.

Universities connected via Video Con facility
With folks who attended session in-person at HEC

I really enjoyed connecting with many students especially Universities in other than major cities.

You can find the slides below I used as reference:

MVP Summit 2013 Summary and Take Away

Hello folks!
I am at the Seattle Airport (SEATEC) leaving for home via Dubai waiting for boarding to start. So I thought to utilize the time and share my summit experience.
As I mentioned in a blog post earlier, this was my third time attending the MVP Summit and yet it’s always good to attend the summit, interact with product teams at Microsoft and take something out of it.

Complimentary copies from Practices & Patterns teamTypeScript with Mads togerson
Scott Hanselman on Future of ASP.NETSummit attendee party
But I am not going to share about usual happenings occurred at Summit instead I would like to share some technology updates and good tools I came across at MVP Summit. While much of the content at MVP Summit was under NDA (Non-Disclosure Agreement) yet there are many things that I can share with you and are publicly available as of today. I am going to glimpse through them.

1) ASP.NET and Web Tools 2012.2 Released

One of the recent update announced this week from ASP.NET team is the tooling update for web development. This includes bunch of updates such as support of LESS framework (.less extension), enhancements in Web API, SignalR templates, new template for Facebook application and updated reference to libraries. Note that some of the feature I mentioned in my earlier blog post as part of Web Essential extension are now graduated to Visual Studio as part of this update. Check out detail update on ScottGu blog.

2) PerfView

PerfView is a performance-analysis tool that helps isolate CPU- and memory-related performance issues. It’s a very handy tool if you are into to investigating performance bottle necks so things like blocking time, memory allocation, GC collection time etc. can be identified from using this tool.

This tool is developed by CLR team. It doesn’t have very good UI, but I am impressed by its data and benefits. Also please note that with default options, it’s not very heavy and can be used in production environment as well. Summary: If you are facing performance challenges in your .NET server side apps, give it a try.

3) Visual Studio DevLabs Extensions

DevLabs extensions are experiments/trials of potential upcoming features in Visual Studio. But guess what? you can try them today. I can’t explain much about this, you can check it out on Visual Studio Gallery. Please note that this is in addition to Productivity Power Tools available for Visual Studio which I mentioned in an earlier blog post.
View DevLabs Extensions on Visual Studio Gallery

4) TypeScript

TypeScript is typed super-set of JavaScript and it helps you write JavaScript with static type checking and some sort of benefit of static typed language. For example, it let’s you define interfaces, object type, method type rather than everything as ‘var’. If you write a lot of JavaScript, consider evaluating it. However it’s still in preview version.

Tutorial | Playground

That is all for now, the boarding is about to start in next five minutes.

Keep Exploring!

ASP.NET MVC 4 Redirects Incorrect Login URL /login.aspx

When working with ASP.NET MVC and WebMatrix.WebData.SimpleMembershipProvider, I faced an issue of ASP.NET redirecting to incorrect login page i.e. “/login.aspx” in case of unauthorized access. As a result, got server error something like below snapshot

Solution: 

The resolution is simple and somewhat intuitive. Somebody needs to tell ASP.NET my LoginUrl. There are two workaround for that which I have tried and worked for me.
  • Add a LoginUrl key in appSettings in web.config
<add key="LoginUrl" value="~/Account/Login"/>
  • OR Set the form loginUrl in   in web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="3000" />
authentication>
Another way around I found on stackoverflow is to set FormAuthenticationSettings but I didn’t give it a shot.
Finally, if you faced issue of redirect to ~/Account/Logon instead of ~/Account/Login in MVC 4 then make sure to check the PreserveLoginUrl is added and set true in your appSettings as mentioned in ASP.NET MVC 4 release notes
Hope it helps.

 

Web Development Goodies in Visual Studio 2012

Visual Studio 2012 and it’s extensions ecosystem brings excited enhancements for web developers. I am glad to see that web platform team is giving attention to open source, adapting industry trend faster than ever and making developer life easy and standard-complaint.
In this post I am going to share some of web development goodies that ships with Visual Studio 2012 (including Visual Studio Update 1 along with ASP.NET and Web Tools 2012.2 RC update) as well as some popular and must have extensions.

 

HTML5/CSS3/JavaScript Editor Enhancement Support:

 

The Visual Studio 2012 IDE includes great tooling update for supporting HTML5/CSS3/JavaScript intellisense. This includes new HTML5 tags and CSS3 properties. This helps in writing code relatively faster.


 
And who said to work on color hex codes? CSS color picker is now supported directly in CSS editor in Visual Studio. Makes it super easy to select and customize colors.
Further, JavaScript editor has improved significantly supporting better intellisense including for jQuery library.

An important point for JavaScript intellisense is to add reference path to js files. If you have noticed in ASP.NET MVC 4 project templates there is a js file “_references.js”

This file add references of common scripts referred in project to support their intellisense. However the reference to “_references.js” is added as global references in Visual Studio -> Options -> Text Editor -> JavaScript -> Intellisense -> References

It’s not the case that you cannot develop HTML5/CSS3 application without it. It’s just a editor support. Part of the features were also made available for Visual Studio 2010 SP1.

Page Inspector:

Page Inspector is a new feature in Visual Studio 2012. If you have developed web layout using HTML/CSS, you must have came across situation to give hit and try web layout for example, setting the right position, padding, selecting the color and see what best suited. I previously used to do this using FireBug, a Firefox browser extension. Page Inspector one feature is to answer this scenario. Scott Hanselman has produced a great animation to show what page inspector does. So I have copied it below.

Paste JSON as Classes 

A new feature to convert JSON into classes. A copied JSON can be pasted using Edit -> Paste Special -> Paste JSON As Classes

{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}

is pasted as

 

NuGet

NuGet is a popular extension of Visual Studio that makes it easy to manage third party libraries and dependencies in Visual Studio. In fact it’s so good that it now ships with Visual Studio 2012.
You can open up NuGet Package Manager using user interface or Package Manager console window available in View -> Other Windows -> Package Manager Console.

The way it works is that if you develop third party libraries and want to share with other developers then you create a package in NuGet. Other developers can retrieve package from NuGet repository and download the library along with required configuration, such as entry in web.config. See an example blog post, where I demonstrated configuring ELMAH using NuGet.

Web Essentials

If you are currently working on web application front-end in VS and you don’t have web essential extension installed then you are simply missing something essential. Web Essential is an visual studio extension created by Mads Kristensen and its like playground for the web tools team. It has a bunch of great features which provide help in development, I am just going to highlight few of them. Complete feature set is explained at http://vswebessentials.com/
LESS Editor/Preview: LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. If you write CSS and don’t know about LESS, you are missing something really handy. Web essential extension supports .less extensions file in a way that it previews the output CSS and some refactoring as well.


Vendor Specifics Generation: Many of the CSS3 properties required vendor specifics properties to work across web browsers. These include -moz, -webkit, -ms and -o. Consider following example below:

would result in:
 
There are many other goodies for web developers, TypeScript, CoffeeScript, advance intellisense in HTML, JS and CSS editors, ZenCoding etc. Go get it. This extension is also available for Visual Studio 2010 as well.

Productivity Power Tools

Productivity Power Tools is another must have extension of Visual Studio developed by some engineers at Microsoft Visual Studio team but they are not yet part of the Visual Studio official shipment. Some of the feature has graduated to official shipment over the time yet there are many good to have feature in productivity power tools. Some of the features I like are:
  • Ctrl + Click for Go To Definition
  • Remove unused Using from code editor context menu
  • Power Commands
  • Quick Tasks. Quick Tasks is nothing revolutionary rather it brings out most commonly used settings in Visual Studio to your finger tips. (see snapshot below)

For details, check out the Productivity Power Tools page on Visual Studio Gallery. This extension is also available for Visual Studio 2010 having relatively different feature set.

Open Source Web Platform

Over the last two years, I am glad to see the interest and shift of Microsoft Web and Azure team towards open source. Since then they have started publishing some of their source code on codeplex and github. This really helps developer community in contributing towards frameworks and understanding code which is good to have in case you faced any issue and wanted to know internals.
That is all for now. I have tried to highlighted some of good stuff available in Visual Studio ecosystem, which are helpful for web developers. I recommend you to check out details of each item.
Happy Coding!
 

Beginning Web Development using ASP.NET MVC

Yesterday I had an opportunity to talk on web development using ASP.NET MVC for students at AIOU.
I wanted to make sure that students have good concept of “Web” and the HTTP transactions. Plus in the start, it takes a little time for beginners to understand the Model-View-Controller (MVC) pattern and the convention over configuration style in ASP.NET MVC. So I started the session with web fundamentals and moving to demonstrating ASP.NET MVC project.
For those asking for presentation slides, which I think are not very important here but may be helpful, are shared on slideshare.

IIS 7 not loading CSS and Image

Yesterday, I faced a wired yet crazy issue. My machine has a bit freshly installed windows 7 and so while running web site hosted on local IIS, I was getting a pretty plain asp.net pages without CSS and Images being loaded properly.

After a little investigation, it appears to be a problem with Windows feature installation. All you have to do is run ‘optionalfeature’ command and make sure ‘Static Content’ option is checked.

Windows Features - Static Content

Hope this would help you, if you face similar kind of issue.





Configuring ELMAH with WCF using NuGet

I am sure most of you have used Error Logging Module and Handlers (ELMAH) for ASP.NET. ELMAH is one great open source project and real blessings for ASP.NET developers. If you don’t know about it, It’s a MUST SEE tool and in that case I would recommend you to read out Scott Ha introductory blog post on ELMAH.

BUT, in this post we are going to see how to configure ELMAH to work with WCF services because if you do that in a typical way then ELMAH is probably not going to work as expected and it won’t show you any unhandled exception.

So let’s get started!

ElmahWithWcfSolution

I have created a new WCF Application project ElmahWithWcf containing one contract IDemoService and service implementation class DemoService.

To add ELMAH, you can either download it from project host site and configure it or you can simply use NuGet to download and automatically install/configure ELMAH.

NuGet is a Visual Studio extension that makes it easy to install and update open source libraries and tools in Visual Studio. Perhaps it really does simplify the life of developer when it comes to configure third party open source libraries. If you haven’t used NuGet, I would strongly encourage you to install it from Visual Studio Extension Manager (Tools –> Extension Manager). It’s free. You can also read NuGet documentation on CodePlex.com for further help or ping me back.

Once you have installed it, you can Add/Configure ELMAH via “Add Library Package Reference” in context menu of references folder.

In Add Library Package Reference, search elmah in online packages and click install, which will automatically download the required assemblies and configure entries in web.config as well. Isn’t it cool?

Add Library Package Reference

Just in case if you don’t believe, with NuGet you get all the config entries automatically!!!

Config Entries by NuGet

With this ELMAH is now configured as you would typically do in ASP.NET web application, however, in contrast to ASP.NET app, it won’t log any unhandled exception that is raised in WCF service. For this, to work correctly, you need to create custom Error Handler implementing IErrorHandler as demonstrated in code snippet below:

public class ElmahErrorHandler: IErrorHandler 
{
    #region IErrorHandler Members
    
    public bool HandleError(Exception error) 
    {
        return false;
    }
    public void ProvideFault(Exception error, MessageVersion version, ref Message fault) 
    {
        if (error == null) 
        {
            return;
        }
   
        if (HttpContext.Current == null) 
        {
            return;
        }
   
        Elmah.ErrorSignal.FromCurrentContext().Raise(error);
    }
  
    #endregion
 }
 
 //Further in addition to that, you need to create a Service Behavior Attribute implementing Attribute and IServiceBehavior 

  public class ServiceErrorBehaviorAttribute: Attribute, IServiceBehavior 
  {
    private readonly Type errorHandlerType;
    public ServiceErrorBehaviorAttribute(Type errorHandlerType) 
    {
        this.errorHandlerType = errorHandlerType;
    }
    
    #region IServiceBehavior Members 
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection < ServiceEndpoint > endpoints, BindingParameterCollection bindingParameters) 
    {
    }
    
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    {
        IErrorHandler errorHandler;
        errorHandler = Activator.CreateInstance(errorHandlerType) as IErrorHandler;
        if (errorHandler != null) 
        {
            foreach(ChannelDispatcherBase dispatcher in serviceHostBase.ChannelDispatchers) 
            {
                ChannelDispatcher cd = dispatcher as ChannelDispatcher;
                cd.ErrorHandlers.Add(errorHandler);
            }
        }
    } 
  
    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    {    
    }
    
    #endregion
 } 
 
 //And finally you need to apply the custom attribute on your service implementation class   
 [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 public class DemoService: IDemoService 
 {
     #region IDemoService Members 
     public string GetData(int value) 
     {
        throw new Exception("TEST");
        return string.Format("You entered: {0}", value);
    }
    
    #endregion
 }

That is all you need to do for ELMAH to work with WCF.

 

At this point, ELMAH must show all unhandled exception in log file. For example, line number 9 throws an exception with message “Test”. If we invoke the service method, the ELMAH should log this exception. The log file can be browsed at http://ServerPath/elmah.axd

In fact, ELMAH is so convenient that we decided not to use Enterprise Library Logging Block and utilized ELMAH to log even handled exception as well (Yes another reason was timelines as well).

Did I hear How? Well, in that case you simply need to manually add one line in catch block.

image

This will inform/raise about the exception to ELMAH and so it will log the handled exception as well.

Hope this Helps!

In case of any feedback/experience, please do share…

Happy Coding!

ValidateRequest=”false” in ASP.NET 4

If you are someone like me who have recently upgrade to ASP.NET 4.0, you may have come across Yellow Screen of Death with Http Request Validation Exception, something like:

“A potentially dangerous Request.Form value was detected from the client”


Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client
Surprisingly, you will still see this exception even if you have set ValidateRequest to false in either the Page Tag or Web.Config.
ValidateRequest="false" or  <pages validateRequest="false" />
This may end you being freak out identifying the problem.
The solution is perhaps very simple. I would recommend to go and read ASP.NET 4 Breaking Changes.
“In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.and therefore request validation errors might now occur for requests that previously did not trigger errors.”
In order to revert to the behavior we had previously, you need to add the following setting in Web.config file:
<httpRuntime requestValidationMode="2.0"/>
And this should work!
Hope this helps!

Sessions on Web Development

Good Job NED Volunteers Thumbs up 


Source: http://www.devnextug.org/2011/04/sessions-on-web-development-using.html

On request of students from NED University of Engineering and Technology, DevNext User Group recently organized two day sessions on Web Development using ASP.NET at NED University. The sessions were held on 12th and 19th March, 2011.

The purpose of facilitating such sessions was to provide students firm understanding of web architecture and development using HTML, JavaScript, CSS and ASP.NET.

We would like to thank speaker and our volunteers at NED University for organizing such useful sessions.

About Speaker:

Mr. Anas Raza is a graduate in Computer and Information System from NED University and currently working as Software Engineer at ITIM Pakistan.

About DevNext User Group:

DevNext is a user group which has been created with the intention of providing a platform for the Next Generation Designers & Developers sharing and discussing knowledge regarding different tools and technologies. Our mission from inception has been to develop a peer group of developers, designers, architects, and managers who are interested in learning, sharing and growing their knowledge and capabilities. The group’s vision is to provide members with a forum to hear top industry experts speak, learn and teach others who are interested in the same technologies as you and are facing the same challenges.

Interested in organizing technology sessions in your University? Please contact us at contact@devnextug.org and we will be happy to assist you.

Event Summary: Visual Studio 2010 Ultimate LoadFest

Reference: http://edotnetdevs.wordpress.com/2010/12/04/event-summary-visual-studio-2010-ultimate-loadfest/

Visual Studio 2010

THANK YOU FOR ATTENDING VISUAL STUDIO 2010 ULTIMATE LOADFEST!

4th December 2010, we had another exciting event “Visual Studio 2010 Ultimate LoadFest”. The event was held at FAST- National University of Computer and Emerging Sciences, Karachi. We would like to thank all the organizers, speakers, participants and volunteers for making this event successful. Especially to our speakers Adil Ahmed Mughal, Jibran Jamshed and Munir Usman for their valuable time and attention to this event.

Agenda:

  • What’s New in Visual Studio 2010 Ultimate? by Adil Mughal
  • Application Life cycle Management (ALM) by Jibran Jamshed
  • Refreshment
  • Mastering Debugging in Visual Studio 2010 by Munir Usman
  • Lucky Draw [Visual Studio 2010 Ultimate with MSDN Subscription, Pluralsight subscription, Microsoft Bag]

    Adil on New IDE ImprovementsThe first session focused more on the new features in Visual Studio 2010 IDE. The speaker started discussion on the New Project Dialog improvements and Start Page customization in Visual Studio 2010 then moving towards Core IDE improvements that includes WPF based editor, easy code navigation, improved IntelliSense, column selection, call hierarchy etc.

    Adil then talked about how Visual Studio supports “Test Driven Development” and Code Focused development approach. Then ASP.NET improvements such as ASP.NET/HTML mark up snippets, Cleaner HTML, automatic HTML encoding were discussed. Finally, Visual Studio Extensibility (VSX) was discussed and some powerful/highly rated extensions such as Productivity Power Tools, Power commands etc were demonstrated to the audience.

    Jibran on ALMThe second session was about application life cycle management with major focus on Team Foundation Server 2010.

    Jibran highlighted the issues faced by software development teams in the overall application life cycle and how Team Foundation Server (TFS), along with its numerous features and integration with other tools, can address those issues. He also demonstrated creating new team projects, selecting MSF process, code version control, work items and test cases execution against those work items in Visual Studio 2010 Ultimate and TFS.

    Munir on Debugging in Visual StudioThe third session was on mastering debugging in Visual Studio 2010. The speaker started discussion from basic debugging, such as usage of debugging points, stack trace, immediate window etc, to advance debugging features offered by Visual Studio such as conditional debugging, hit count, filter, macros, data tips, debug labels etc.

    In the end the Munir talked about the historical debugger (IntelliTrace) in VS 2010 ultimate and demonstrated how useful this feature is for developers.

    In the end goodies were distributed via lucky draw. Following were the winners:

    • Sheeraz Sheikh – Winner of Visual Studio 2010 Ultimate with MSDN subscription
    • Winner of Visual Studio 2010 Ultimate with MSDN subscription
    • Fahad Khan – Winner of 1 Month of free training of Pluralsight on-demand
    • Hassan Zahid – Winner of 1 Month of free training of Pluralsight on-demand

    Adil & Munir - Lucky Draw MVP Bag SpottedVS LoadFestVisual Studio Pamphlet

    For more picture, please visit photo album on Emerging .NET Devs Facebook Page. If you have attended the event, please take out few minutes to fill the feedback form here.

    In the end, we would like to thank our sponsors without them it would not be possible to organize this event. INETA, Wrox, Pluralsight, DevNext, Fast.NET

    Sponsors