ASP.NET MVC 3 - Asynchronous Controller Action Made Easy

by Faris Zacina 3. November 2011 11:46

Working with Asynchronous controllers In ASP.NET MVC 3 is just a pain right now. There is some boilerplate code we must write over and over. Here is some code to make things easier. I wrote an extension method for the AsyncManager to Queue and Run an action using a TPL Task. You can use any async mechanism in your implementation.

namespace MVC.AsyncMagic { public static class AsyncManagerExtensions { /// <summary> /// Queue task to execute on the async manager /// </summary> /// <param name="asyncManager"></param> /// <param name="task"></param> public static void QueueAction(this AsyncManager asyncManager, Action action) { // Increment the async operations counter asyncManager.OutstandingOperations.Increment(); // Use TPL Task to process the action asynchronously Task task = Task.Factory.StartNew(action); // Add a continuation to decrement the async operations counter task.ContinueWith((t) => { asyncManager.OutstandingOperations.Decrement(); }); } } }
 

 

Using this code is very easy. In your async controller just call the QueueAction operation to perform the actual async call and do your magic. Use the AsyncManager.Parameters dictionary to pass the results in the Completed operation.

 

namespace MVC.AsyncMagic.Controllers { public class HomeController : AsyncController { public void IndexAsync() { AsyncManager.QueueAction(() => { WebClient client = new WebClient(); String data = client.DownloadString(new Uri(@"http://www.google.com")); AsyncManager.Parameters["Data"] = data; }); } public ActionResult IndexCompleted() { ViewBag.Data = AsyncManager.Parameters["Data"]; return View(); } } }
 

Tags: , ,

.NET | ASP.NET MVC

One book at a time principle

by Faris Zacina 10. September 2011 07:06

The average software developer today has hundreds or even thousands of technical books. According to some sources the average person reads one book per year, but developers read much more than this. The question is how many books do we actually read from beginning to the end? i would say not many. The main reason why we don't read books til the end, is multitasking, which in this context is reading multiple books at the same time. Another reason could be that software developers often search for specific knowledge in books, and often "forget" to read the other chapters.

In my opinion reading multiple books and reading them partially it is definitely a bad practice. This is why we need to introduce the "One book at a time principle" which i would define as: "Read one and only one book at a time from beginning to the end". Following this principle builds quality knowledge, and also builds a habit to finalize work in progress. In addition, if we read only one book at a time, we need to carefully choose what we read, which means that we will not read all kinds of crap. Here is a nice list of must-read books:

Joel's list of books to read

Tags: , ,

General

Software development principles - DRY (Don't repeat yourself)

by Resad Zacina 24. August 2011 08:37

Real life example no.1:

Today, while working on one of my tasks, i realized once again how important it is to blindly follow the DRY principle. I generally not like finding duplicate code of any kind, and i believe it is the same for many developers. The project i'm currently working on is an MVC 3 Razor portal with a lot of JQuery bells and whistles around. While digging through some interesting code, and doing some HTTP level debugging with Fiddler, i noticed that some Ajax requests were being sent twice. I found out that, some partial views, rendered in parent views, contained duplicate JQuery code (already existing at other locations) causing selectors with the same name to execute .js code twice. Logically, performance was deteriorated because every request took twice as long to execute, and scripts were also loaded twice.

Real life example no.2:

Two views with almost the same HTML, used for Add/Update operations over an entity. About a month ago we had a conversation about it and i pointed out that these views should be merged into one, because they have 95% the same structure. In the mid-time the user story has been closed and marked as completed, even if the duplication issue was not corrected. Everything would be somewhat acceptable, if some functionality was not implemented on only one view instead of both!. Clear example of violation of the DRY principle.

These examples are giving an insight in what can happen if the DRY principle is violated. Of course, the DRY principle is not only about code duplication, here is the definition from Wikipedia:

"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. It includes "database schemas, test plans, the build system, even documentation." When the DRY principle is applied successfully, a modification of any single element of a system does not require a change in other logically-unrelated elements. Additionally, elements that are logically related all change predictably and uniformly, and are thus kept in sync."

I recently finished reading "The Pragmatic Programmer" book by Andy Hunt and Dave Thomas, the fathers of the DRY term. Even if the book is more than 10 years old, it shares some good ideas on how to avoid duplication in all areas of software engineering. I Recommend this book, especially for copy-paste lovers Smile

Tags:

Design patterns | General

New Technology Skepticism

by Faris Zacina 24. July 2011 07:19

When a new technology emerges from the Microsoft development teams (or Opensource caves) you can hear about it everywhere. "Microsoft Magic Unicorn 2 CTP 5" is on Channel 9, PDC, MIX, Blogs, News, Feeds, Tweets and you get bombarded with a huge amount of information and you often struggle to get up to speed with it.

The average developer will google it to find basic overview, tutorials and samples to gather at least minimal knowledge, but from my personal experience i know that 80% of software developers will not dig very deep to get to the juice and instead will remain on the basic level of knowledge. When i say basic level of knowledge, i mean the level of knowledge where you can actually produce some code only supported by a search engine, handbook or similar. Only 20% of the developers will dig deeply, build prototypes, test, explore all the scenarios and find hidden traps.

I think that is pretty important to be a Skeptic when you get to know about a new technology, but i also think it is important to know what Skepticism actually means and how it could be applied as a process. Here is a definition from our always trusted Wikipedia:

"Skepticism (or scepticism) has many definitions, but generally refers to any questioning attitude of knowledge, facts, or opinions/beliefs stated as facts, or doubt regarding claims that are taken for granted elsewhere."

In our context, this would map to questioning the new technology to prove it's usefulness and verify vendor claims. The goal is to discover the true face of the technology and conclude if it will fit into your technology toolbelt. It is very important to systematically investigate the technology, to communicate with experts and not rely only on the cool blog post that you have read or the PDF from codeplex.

One approach to systematically investigate the technology could include the following steps:

  1. Recognize the areas where the technology can be applied
  2. Gather relevant information about the new tecnology from relevant sources
  3. Gather relevant information about technologies (include Opensource technologies as well) that could be an alternative
  4. Interpret gathered data to appraise evidence and evaluate arguments
  5. Draw warranted conclusions and generalizations about the tecnology
  6. Put to test the conclusions and generalizations  (eg. by building a full prototype which can be thouroughly evaluated)
  7. Apply on a real world project

 

I think that these steps form the essential process that is required to get a grasp of the new technology.

This list is not a definite guide or anything similar, and instead is just a reminder to the "false skeptics" that they should not skip some of the very important steps like for example step 3. (gather information about alternatives) and step 6. (prototyping a solution to apply the conclusions and generalizations). I am pretty confident that 80% software developers skip 2 or more steps from this list, and that is why we have a lot of "false skeptics" that turn down technology based on a very low level of knowledge and experience with it. Even worse, the same developers will use technology on production projects without a deep evaluation. 

Even if we could follow all the steps from 1 to 6, we have no warranties that it will do the job in production. We have assumptions based on our gathered knowledge/experience, but the truth is that the technology will show the true face only in production (step 7.) A test based approach could definitely prevent some headaches.

And finally, who is responsible to evaluate the new technology? is it the architect or the developer? i would say all of them (it will not harm anybody) but in fact it is primarly an architect or technical leader responsibility.

Tags: ,

.NET | General

Big File Upload in ASP.NET - Configuration

by Faris Zacina 12. April 2011 00:05

When posting large files to an asp.net server you must make sure that you set the proper settings in your web.config file. The httpruntime tag is used to set those options and there are two important attributes to set:

maxRequestLength - The max size of the request (file) that you send to the IIS server. The default value is 4096 KB

executionTimeout -The max number of seconds after which the request times out and gets aborted by asp.net. The default is 100 seconds.

However, these values are not enough for large file upload so you should set them to bigger values. For example:


 <httpRuntime maxRequestLength="40960" executionTimeout="240" />

 

if you are deploying to IIS6 or IIS7 you must make sure the URLScan (IIS6) or the Request filtering (IIS 7+) options are also set up correctly. You must set the request size to an appropriate value.


 <requestFiltering>

    <requestLimits

       maxAllowedContentLength="50000000"

       maxUrl="260"

       maxQueryString="25" />

   </requestFiltering>

 

If you set these settings correctly you should be able to post big files to a web server without issues.

 

 

Tags: , , ,

ASP.NET | Configuration

Logging vs Auditing vs Tracing - The difference matters

by Faris Zacina 10. December 2010 01:02

It is hard to completely separate these terms, but i think that the difference matters, so let's define the three:

Logging is a common term describing software development technique used for error logging, operational monitoring and post-development troubleshooting. Logging is a cross-cutting concern in modern software.

Common logging tools: Log4Net, Enterprise Library Logging block, Log4Net..

Tracing is a term describing the developer efforts to track/analyze/debug program execution during the development process using tracing tools and techniques.

Common tracing tools: Visual Studio Intellitrace

Auditing is a process of obtaining evidence about software usage.

Common auditing tools: -

What do u think? please post your comments!

Tags: , , ,

.NET | .NET | .NET | .NET | Visual Studio | Visual Studio | Visual Studio | Visual Studio

Silverlight / WPF best practices - MVVM pattern

by Resad Zacina 24. November 2010 22:55

Introduction

Building applications in a professional way has always been a challenge, one of the best thing to do is extensively use design/architectural patterns, as the Silverlight/WPF communities are growing larger and there are more and more applications built using these great technologies new patterns are emerging  and being adopted very quickly, one of the cool/new architectural patterns for the presentation layer is the MVVM.
I will try to explain in a what/why/how manner the advantages and good sides of using this UI pattern.

What is MVVM?

The MVVM is an architectural pattern, the acronym stands for Model View View Model and basically it's a Microsoft flavour of the Presentation Model pattern (Martin Fowler 2004) primarily targeted towards the modern MS application platforms, and in fact many blogs/forums/communities use the PM and MVVM names as synonyms for the same pattern.
It is highly reccomended to use the MVVM pattern in any kind of Silverlight/WPF business application going beyond the canonical hello world application.

The word MVVM is very obscure at first, let's try to clarify it:

Model: Object model or data access layer

View: GUI elements such as buttons, windows, graphics, and other controls (.xaml pages)

ViewModel: The ViewModel classes bind the previous two and act as mediators between them, the ViewModel class tipically exposes properties, commands, and abstractions. 

Controller: Some implementations of the MVVM pattern also include an additional controller layer to sharpen the separation of concerns level.

Why to use MVVM?

Let's say you are building a business application using Silverlight, you created a simple page TestPage.xaml, added a simple click handler and now you are planning to get dirty and code some stuff,
so you basically have two choices:

- Put the application logic for the click handler in the code behind
- Create new classes that will support the MVVM pattern

Writing application logic directly in the code behind class is very tempting and easy to do, but it's not a good idea from the testability point of view,
it is very hard to test code incorporated directly in the code behind of a view class because the whole view must be instantiated in order to test it and the code cannot be run in isolation without the xaml.

So it is all about SoC (separation of concerns) and fragmenting/separating the different types of tasks each part of the application has. All the components of your architecture should be very loosely coupled, in MVVM the View never knows implementation details about the underlying model, the main function of the View is to render UI elements and communicate to the ViewModel to get needed data blocks,
the Model is not dependent on the ViewModels because they're only using exposed methods and respectively ViewModels are also unaware of the View implementations.

What are the "real" benefits?

1. Your code will be very easy to test because the ViewModels can be tested in isolation.
2. After achieving such a level of SoC, you can easily give the UI tasks of your project to a UI designer using Expression Blend or similar tools.
3. You get a pluggable UI architecture, you can plug in different Views with new design, ViewModels can be consumed by multiple Views and the Model can be used by one/more ViewModels or even different projects.
4. You gain great benefits from databinding making it very easy to connect UI elements to the corresponding constructs in the ViewModel


In the next part of this blog i will bring implementational details about this great pattern, stay with us! :)

 

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Architectural patterns | WPF | WPF | Silverlight | Silverlight | WPF | WPF | Silverlight | Architectural patterns | WPF | WPF | Silverlight | WPF | WPF | Silverlight | WPF | Silverlight | Silverlight | WPF | Architectural patterns | Silverlight | Architectural patterns | WPF | Silverlight | Architectural patterns | WPF | Silverlight | WPF | WPF | WPF | Silverlight | WPF | Silverlight | WPF | WPF | WPF | WPF | WPF | WPF | WPF | WPF | Silverlight | Silverlight | WPF | WPF | WPF | Architectural patterns | Silverlight | WPF | Architectural patterns | Architectural patterns | WPF | Silverlight | Silverlight | WPF | WPF | WPF | Architectural patterns | Silverlight | WPF | WPF | WPF | WPF | WPF | Silverlight | Silverlight | WPF | WPF | Silverlight | WPF | Architectural patterns | Silverlight | WPF | WPF | Silverlight | Silverlight | Silverlight | WPF | WPF | WPF | Silverlight | WPF | WPF | WPF | WPF | WPF | Silverlight | WPF | Silverlight | WPF | WPF | Silverlight | Silverlight | WPF | WPF | Silverlight | WPF | Silverlight | Silverlight | Architectural patterns | WPF | Silverlight | Silverlight | WPF | Architectural patterns | WPF | WPF | Silverlight | WPF | WPF | Silverlight | WPF | Architectural patterns | WPF | Architectural patterns | Silverlight | WPF | WPF | WPF | WPF | WPF | Silverlight | WPF | WPF | WPF | Silverlight | Architectural patterns | WPF | WPF | Silverlight | WPF | WPF | WPF | WPF | WPF | Silverlight | Silverlight | WPF | Silverlight | Silverlight | WPF | WPF | Silverlight | WPF | WPF | WPF | Silverlight | WPF | Silverlight | WPF | WPF | Silverlight | Silverlight | Silverlight | Architectural patterns | WPF | WPF | WPF | Silverlight | Silverlight | WPF | Architectural patterns | WPF | Architectural patterns | WPF | WPF | WPF | WPF | WPF | WPF | WPF | Silverlight | WPF | WPF | Silverlight | Architectural patterns | Silverlight | WPF | WPF | WPF | Silverlight | WPF | WPF | Architectural patterns | WPF | WPF | Silverlight | WPF | WPF | Silverlight | WPF | WPF | WPF | WPF | WPF | Silverlight | WPF | Silverlight | WPF | WPF | WPF | Silverlight | WPF | Silverlight | WPF | Silverlight | WPF | WPF | WPF | WPF | WPF | WPF | Silverlight | Silverlight | Silverlight | WPF | Silverlight | WPF | Architectural patterns | WPF | WPF | WPF | WPF | WPF | Silverlight | Silverlight | WPF | WPF

.NET Application Error Handling

by Faris Zacina 19. November 2010 11:03

Error Handling

What happens when a runtime error (exception) occurs in a .NET application? how do we want to handle those situations? The ideal response would be to optimize the code to prevent any runtime errors, but let's be honest and admit that this is impossible. There will always be a spot in our application where an exception is possible, and the only valid option we have to handle it is to use try-catch-finally blocks and handle all different kind of errors that could happen. However we should only catch exceptions that we can handle, and by handling i mean logging to the database, notifying an administrator by e-mail, bubbling up to upper layers, running some error recovery routine and similar.

Here is a typical example of a try-catch expression in a LINQ to SQL data access scenario:

public Role GetRoleById(int id) { Role dbRole = null; try { // Data access - get role by id dbRole = _dataContext.Roles.Single(r => r.RoleId.Equals(id)); } catch (InvalidOperationException ex) { // Bubble up to upper layer for handling throw new DataAccessException("Could not get role by id! Invalid operation!", ex); } catch (Exception ex) { // Bubble up to upper layer for handling throw new DataAccessException("Could not get role by id!", ex); } finally { // Cleanup code } return dbRole; }

Exception handling improves code robustness and allows us to carry rich error information to the layers that handle the exception (log to the database, form a user error display).

Feel free to create custom exceptions that inherit the base exception classes and implement your error handling logic using those classes

For Dummies

Here is a brief explanation of the try-catch-finally keywords and how to use them.

Try - In the try code block put code that could possibly cause an unhandled exception at runtime. Typical scenarios: Database access, File system access and other.

Catch - The catch section will catch all the exceptions of a specified type. This is the error handling zone, and here you should put all the exception handling logic (logging, error recovery, bubbling up..). You can use as many catch blocks as needed in your error handling logic.

Finally - The finally section will always execute when execution leaves the try statement. This is an ideal spot to insert resource cleanup code (close DB connections, file handles and similar..)

Exception Handling Best Practices

When you implement exception handling code in your application you should consider the following guidelines:

  • Report execution failures by throwing exceptions
  • Build explanatory, grammatically correct exception messages to be able to debug easily
  • Exclude security-sensitive information from exception messages
  • Capture specific exceptions first, general exceptions last
  • Do not swallow exceptions, instead pass them as a inner exception to ensure stack trace integrity
  • Use as few try-catch blocks as possible on each processing layer to centralize the exception handling code and avoid performance issues
  • Never display exception messages to the user, instead log them in the DB and build custom error messages for UI display
  • Never log Exception.Message, use Exception.ToString() instead
  • Use a logging library to do the dirty stuff (Enterprise library, Log4Net..)

Logging Frameworks

If you develop a small application you can easily develop custom database logging, notification and similar code, but in other scenarios, where you have mission critical applications and tight deadlines you need a framework to do the exception handling dirty work. There are several good frameworks to use for logging, and i will list just a couple of them for reference:

Enterprise Library Logging - This library is part of the enterprise library package and it is very easy to setup. On the other hand it has powerful configuration, logging and instrumentation options, it supports all the log details you will ever need and multiple logging targets.

Log4Net - This library is an open source project, and it is a very powerful logging library, widely adopted in the .Net world.

NLog - It is opensource, Cross-platform, configurable, supports routing and multiple targets

Personally, i prefer the enterprise library, but the other contenders are great as well, so don't wait anymore, start using a logging framework in your application!


Please send your comments!

Tags: , , , ,

.NET Best Practices | .NET Best Practices

Powered by BlogEngine.NET 2.0.0.36 - FunkyGrunge Theme by n3o Web Designers

 

TextBox

Tag cloud