A New Internet Library: Add Your Website/Blog or Suggest A Website/Blog to our Free Web Directory http://anil.myfunda.net.

Its very simple, free and SEO Friendly.
Submit Now....

Friday, January 30, 2009

Why no var on fields?

In my recent request for things that make you go hmmm, a reader notes that you cannot use "var" on fields. Boy, would I ever like that. I write this code all the time:

private static readonly Dictionary<TokenKind, string> niceNames =
  new Dictionary<TokenKind, string>()
  {
    {TokenKind.Integer, "int"}, ...

Yuck. It would be much nicer to be able to write

priva...Full Article.

Why no var on fields?

In my recent request for things that make you go hmmm, a reader notes that you cannot use "var" on fields. Boy, would I ever like that. I write this code all the time:

private static readonly Dictionary<TokenKind, string> niceNames =
  new Dictionary<TokenKind, string>()
  {
    {TokenKind.Integer, "int"}, ...

Yuck. It would be much nicer to be able to write

priva...Full Article.

Long division

A thing that makes a reader go hmmm is why in C#, int divided by long has a result of long, even though it is clear that when an int is divided by a (nonzero) long, the result always fits into an int.

I agree that this is a bit of a head scratcher. After scratching my head for a while, two reasons to not have the proposed behaviour came to mind.

First, why is it even desirable to have the result fit into an int? You'd be saving merely four bytes of memory and ...Full Article.

Long division

A thing that makes a reader go hmmm is why in C#, int divided by long has a result of long, even though it is clear that when an int is divided by a (nonzero) long, the result always fits into an int.

I agree that this is a bit of a head scratcher. After scratching my head for a while, two reasons to not have the proposed behaviour came to mind.

First, why is it even desirable to have the result fit into an int? You'd be saving merely four bytes of memory and ...Full Article.

Tip #44: Did you know.How to view the Project File while still in Visual Studio?

If you are developing a web site using the Web Application Project model, then you know that the Project File is an integral part of this model.  In order for a file to be considered part of the Web Application Project, it must be included within the project file.  This is also true of Assembly References and other project metadata settings.  If a file exists in the web's file-system root, but i...Full Article.

Tip #44: Did you know.How to view the Project File while still in Visual Studio?

If you are developing a web site using the Web Application Project model, then you know that the Project File is an integral part of this model.  In order for a file to be considered part of the Web Application Project, it must be included within the project file.  This is also true of Assembly References and other project metadata settings.  If a file exists in the web's file-system root, but i...Full Article.

Enterprise Library 5.0 kick-off! Spend your $100 wisely!

It's that time again - the kick-off for the next major release of Enterprise Library. I can't believe we're already up to version 5.0 - it doesn't seem like that long ago when we were planning version 1.0.

Anyway, you should know the drill by now. The patterns & practices team needs your input to decide what new features and scenarios go into each new release. Despite the tough economic times, Grigori has been kind enough to give each and...Full Article.

Enterprise Library 5.0 kick-off! Spend your $100 wisely!

It's that time again - the kick-off for the next major release of Enterprise Library. I can't believe we're already up to version 5.0 - it doesn't seem like that long ago when we were planning version 1.0.

Anyway, you should know the drill by now. The patterns & practices team needs your input to decide what new features and scenarios go into each new release. Despite the tough economic times, Grigori has been kind enough to give each and...Full Article.

ASP.NET MVC Release Candidate

At long last I am happy, relieved, excited to announce the release candidate for ASP.NET MVC. Feel free to go download it now. I'll wait right here patiently.

There have been a lot of improvements made since the Beta release so be sure to ASP.NET MVC. Feel free to go download it now. I'll wait right here patiently.

There have been a lot of improvements made since the Beta release so be sure to Release Candidate for ASP.NET MVC is available. In this post, I say mea culpa for a known bug within this release.

This bug is a consequence of a change we made in our default template. We know have a content placeholder in the <head> section of the Site.master page.

ASP.NET MVC 1.0 Release Candidate Now Available

Today we shipped the ASP.NET MVC 1.0 Release Candidate (RC).  Click here to download it (note: the link just went live so if it isn't working wait a few minutes for the server you are hitting to refresh).  It works with both Visual Studio 2008 and Visual Web Developer 2008 (which is free).

Today's RC is the last public release of ASP.NET MVC that we'll...Full Article.

Monday, January 26, 2009

SQL Tip: Displaying a Padded Number

A common requirement for reports is to left or right pad a number so that it conforms to a certain format or so that all the numbers in a column are aligned. Padding a string in VB or C# code is a cinch thanks to the String class's PadLeft and PadRight methods. But what...Full Article.

SQL Tip: Displaying a Padded Number

A common requirement for reports is to left or right pad a number so that it conforms to a certain format or so that all the numbers in a column are aligned. Padding a string in VB or C# code is a cinch thanks to the String class's PadLeft and PadRight methods. But what...Full Article.

Redirecting with the Click of a Button

Every ASP.NET developer, at some point or another, has created a page with a Button that, when clicked, redirects the user to some other page. This is typically implemented by adding a Button control to the page, creating a Click event handler, and adding a Response.Redirect, perhaps passing along some user input through the querystring. There are two shortcomings with this approach:

  1. It involves an extra round trip...Full Article.

February's Toolbox Column Now Online

My Toolbox column in the February 2009 issue of MSDN Magazine is available online. The February issue examines two frameworks for implementing design patterns:

Issues with IE8 Beta 2? Opening blank popus?

 

If you have installed the IE 8 Beta 2 and have been using it for sometime, you would have benefited some of the features such as the Accelerators, In-private browsing, instant search, web slices and other enhanced navigation features.  You can find more information on the same at Click event handler, and adding a Response.Redirect, perhaps passing along some user input through the querystring. There are two shortcomings with this approach:

  1. It involves an extra round trip...Full Article.

February's Toolbox Column Now Online

My Toolbox column in the February 2009 issue of MSDN Magazine is available online. The February issue examines two frameworks for implementing design patterns:

Things That Make You Go Hmmm

As you might have gathered from the number of times I make a blog post beginning with "I got the following question from a reader the other day..." I field a lot of questions about the C# language (and in the past fielded a lot of questions about VBScript and JScript.) Each of them is, by definition, about something that was unobvious about the language; if it were obvious, the question wouldn't have been asked in the first place.

This means that ...Full Article.

Things That Make You Go Hmmm

As you might have gathered from the number of times I make a blog post beginning with "I got the following question from a reader the other day..." I field a lot of questions about the C# language (and in the past fielded a lot of questions about VBScript and JScript.) Each of them is, by definition, about something that was unobvious about the language; if it were obvious, the question wouldn't have been asked in the first place.

This means that ...Full Article.

Reading Declarations

Wow, lots of good "hmm" moments in the comments to yesterday's post. Keep them coming!

Many of these resonated strongly with me. One in particular was thinking back to the day when I finally internalized the reality that in C/C++, the declaration "int * px;" does not break down "int *" and "px", but rather "int" and "*px".

Perhaps you all find this perfectly straightforward, but it takes me a little longer to figure all this stuff out. (And hence my motto: "E...Full Article.

Reading Declarations

Wow, lots of good "hmm" moments in the comments to yesterday's post. Keep them coming!

Many of these resonated strongly with me. One in particular was thinking back to the day when I finally internalized the reality that in C/C++, the declaration "int * px;" does not break down "int *" and "px", but rather "int" and "*px".

Perhaps you all find this perfectly straightforward, but it takes me a little longer to figure all this stuff out. (And hence my motto: "E...Full Article.

Tip #43: Did you know... Way you register your IHttpModule depends on the pipeline in which an AppPool for your module will run?

To get your custom IHttpModule up and running you need three simple things:

  • Source code
  • Compiled and GAC’ed DLL
  • Registration with IIS config system

Suppose, you have a simple module that raises an event with HttpContext as an argument before authentication happens, on BeginRequest:

Full Article.

Routing for Web Forms in ASP.NET 4.0

A while back on a lark, I posted a prototype demonstrating how one could use Routing within Web Forms. This is something you can do today with ASP.NET 3.5 SP1, because of the work we did to separate Routing from ASP.NET MVC. I would have liked to include Web Form Routing as part of the Routing feature when we were working on SP1, but we didn't have the time to do so in a robust m...Full Article.

Routing for Web Forms in ASP.NET 4.0

A while back on a lark, I posted a prototype demonstrating how one could use Routing within Web Forms. This is something you can do today with ASP.NET 3.5 SP1, because of the work we did to separate Routing from ASP.NET MVC. I would have liked to include Web Form Routing as part of the Routing feature when we were working on SP1, but we didn't have the time to do so in a robust m...Full Article.

Silverlight and the 2009 Presidential Inauguration

Tomorrow’s presidential inauguration of Barack Obama will be a truly historic event.

Silverlight is being used as an enabling technology on several sites that will allow those of us who can’t be there in person to share the experience online.

Presidential Inaugural Committee

The Presidential Inaugural Committee has worked with iStreamPlanet to enable live and live and on-demand video streaming of the Inauguration event...Full Article.

Silverlight and the 2009 Presidential Inauguration

Tomorrow’s presidential inauguration of Barack Obama will be a truly historic event.

Silverlight is being used as an enabling technology on several sites that will allow those of us who can’t be there in person to share the experience online.

Presidential Inaugural Committee

The Presidential Inaugural Committee has worked with iStreamPlanet to enable live and live and on-demand video streaming of the Inauguration event...Full Article.

Microsoft Web Platform Installer v1.0

 

The Microsoft Web Platform Installer is now v1.0.   Simply putting, it provides you a single installer download of the web platform which includes IIS 7/116, Visual Web Developer Development Tool, SQL Server 2008 Express as well as the .NET Framework.

So, if you are running Windows XP, Windows Vista or Windows Server 2003/2008, it gives you all the stuff you require ...Full Article.

Issues with IE8 Beta 2? Opening blank popus?

 

If you have installed the IE 8 Beta 2 and have been using it for sometime, you would have benefited some of the features such as the Accelerators, In-private browsing, instant search, web slices and other enhanced navigation features.  You can find more information on the same at The Microsoft Web Platform Installer is now v1.0.   Simply putting, it provides you a single installer download of the web platform which includes IIS 7/116, Visual Web Developer Development Tool, SQL Server 2008 Express as well as the .NET Framework.

So, if you are running Windows XP, Windows Vista or Windows Server 2003/2008, it gives you all the stuff you require ...Full Article.

Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

 

I posted this article originally in March 2006 when the ASP.NET 2.0 Treeivew was just released.  It has received tremendous response (35000 views for this particular post) and also many recommendations / suggestions / corrections as comments.

The script then supported checking/unchecking of children/parents when selecting/deselecting a particular node.  However, in cases of havin...Full Article.

Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

 

I posted this article originally in March 2006 when the ASP.NET 2.0 Treeivew was just released.  It has received tremendous response (35000 views for this particular post) and also many recommendations / suggestions / corrections as comments.

The script then supported checking/unchecking of children/parents when selecting/deselecting a particular node.  However, in cases of havin...Full Article.

Sunday, January 18, 2009

Automatic vs Explicit Properties

Here's a question I got from a C# user last year, a question I get fairly frequently:

User: With "regular" explicit properties, I tend to use the private backing field directly from within the class. Of course, with an automatic property, you can't do this. My concern is that in the future, if I decide I need an explicit property for whatever reason, I'm left with the choice of changing the class implementation to use the new privat...Full Article.

Automatic vs Explicit Properties

Here's a question I got from a C# user last year, a question I get fairly frequently:

User: With "regular" explicit properties, I tend to use the private backing field directly from within the class. Of course, with an automatic property, you can't do this. My concern is that in the future, if I decide I need an explicit property for whatever reason, I'm left with the choice of changing the class implementation to use the new privat...Full Article.

Future-Proofing A Design

Last time on FAIC a user asked for guidance on the potential pitfalls of refactoring an automatic property into a regular explicit property. This is just an example of a far more general problem: how can we design programs so that they are easy to get right when things inevitably change in the future?

This is an incredibly difficult question to answer, one which whole books could be written on. Today, I'll just give three general points to think about.

First:...Full Article.

Future-Proofing A Design

Last time on FAIC a user asked for guidance on the potential pitfalls of refactoring an automatic property into a regular explicit property. This is just an example of a far more general problem: how can we design programs so that they are easy to get right when things inevitably change in the future?

This is an incredibly difficult question to answer, one which whole books could be written on. Today, I'll just give three general points to think about.

First:...Full Article.

Stack Overflow Reputation Tool now online

This is the micro-web-app that my recent ASP.NET question was about. It's very simple - it shows you the reputation gained or lost by a specified user (typically you) for either today or yesterday. Note that these are Stack Overflow "today" and "yesterday" - i.e. they're in UTC. That happens to be...Full Article.

Stack Overflow Reputation Tool now online

This is the micro-web-app that my recent ASP.NET question was about. It's very simple - it shows you the reputation gained or lost by a specified user (typically you) for either today or yesterday. Note that these are Stack Overflow "today" and "yesterday" - i.e. they're in UTC. That happens to be...Full Article.

Stack Overflow reputation and being a micro-celebrity

I've considered writing a bit about this before, but not done so for fear of looking like a jerk. I still think I may well end up looking like a jerk, but this is all stuff I'm interested in and I'll enjoy writing about it, so on we go. Much of this is based on experiences at and around Stack Overflow, and it's more likely to be interesting to you if you're a regular there or at least know the basic premises and mechanics. Even ...Full Article.

Stack Overflow reputation and being a micro-celebrity

I've considered writing a bit about this before, but not done so for fear of looking like a jerk. I still think I may well end up looking like a jerk, but this is all stuff I'm interested in and I'll enjoy writing about it, so on we go. Much of this is based on experiences at and around Stack Overflow, and it's more likely to be interesting to you if you're a regular there or at least know the basic premises and mechanics. Even ...Full Article.

Named Formats Redux

UPDATE: Be sure to read Peli's post in which he explores all of these implementations using PEX. Apparently I have a lot more unit tests to write in order to define the expected behavior of the code.

I recently wrote a post in which I examined some existing implementations of named format methods and then described the fun I had writing a UPDATE: Be sure to read Peli's post in which he explores all of these implementations using PEX. Apparently I have a lot more unit tests to write in order to define the expected behavior of the code.

I recently wrote a post in which I examined some existing implementations of named format methods and then described the fun I had writing a UpdatePanel control. The UpdatePanel control automatically converts normal postbacks to partial page postbacks and seamlessly updates...Full Article.

Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Retrieving Server-Side Data Using Web Services

Microsoft's ASP.NET AJAX framework offers two models for developing interactive web applications: client-centric and server-centric. With the server-centric model, developers use the standard ASP.NET controls - the GridView, Buttons, TextBoxes, and so forth - but place them within an UpdatePanel control. The UpdatePanel control automatically converts normal postbacks to partial page postbacks and seamlessly updates...Full Article.

Running the ASP.NET Windows Live Web site in IIS7, Could not load file or assembly 'System.Web.Extensions, Version=3.6.0.0,” Error

 

When I was trying to run the Windows Live Enabled Website that is shipped with the Windows Live Tools for Visual Studio November 2008 CTP (I had blogged about this earlier at When I was trying to run the Windows Live Enabled Website that is shipped with the Windows Live Tools for Visual Studio November 2008 CTP (I had blogged about this earlier at

Wednesday, January 14, 2009

Stop Hacking, Start Mapping: Object Relational Mapping 101

As the industry has moved from a three tier model to n-tier models, the object relational impedance mismatch has become more prevalent. Object Relational Mappers (ORMs) exist to bridge this gap as best as possible. Telerik's OpenAccess ORM is an industrial strength ORM that will meet the needs of all modern applications. It offers a wizard for both Forward and Reverse mapping to all major databases including Microsoft SQL Server, tight Visual Studio integration, LINQ support, transparent persist...Full Article.

New patterns & practices Application Architecture Guide 2.0

The new patterns & practices Application Architecture Guide 2.0 is now available as a free download for developers interested in design-level guidance for the architecture and design of applications built on the .NET Framework. It focuses on the most common types of applications, partitioning application functionality into layers, components, and services, and walks through their key design ...Full Article.

January's Toolbox Column Now Online

My Toolbox column in the January 2009 issue of MSDN Magazine is available online. The January issue examines:

HTTP Redirection Tip

I'm writing a series of concise montly web development tips over at DotNetSlackers.com. My first tip, published in December, looked at caching data for the lifespan of a request, which is a quick and easy way to improve the performance of data-driven web applications that have pages where the same data is requested multiple times per request. My m...Full Article.

Book News

Happy new year all -- I hope 2008 was a good year for you and that 2009 will be better. I myself was crazy busy at the end of 2008, working on a number of at-work projects and personal projects which I'm not going to blog about at this time. I hope to get more time in the schedule for blogging in the next couple of months.

www.dimdim.com

www.yuuguu.com

Both free

DimDim has a professional version that comes with $$

YuuGuu requiring a download

YuuGuu can tie into Live Messenger.. but then screws up multi-location sign in (that's silly)

Overall, DimDim seems more mature

In addition, there is also ASP.NET Dynamic Data, the best place for it is the Dynamic Data Forum.  When you write your question, there are a few simple things that you can do to make it easier for the 'experts' to answer (and hence to get an answer quicker!).

1. Mention what environment you're running in

a. What ORM framework you are usingFull Article.

Tip #42: Did you know... ConfigurationEditor allows you to generate C#, JavaScript or AppCmd script to update configuration?

If you want to write a script to add new or update existing configuration, no matter what configuration file it belongs to (e.g. administration.config, applicationHost.config or website or application specific web.config), you can install Configuration Editor, which is a part of the IIS Admin Pack and use “Generate script” feature, just of its numerous great features.

In order to download this and read more about this please click on below links.

- earlier post about a free Data Structures and Algorithms book which I'm occasionally helping out with in terms of editing.

I've just been told that a new version has recently been uploaded - please check it out. I have to admit that ...Full Article.

You don't have to use query expressions to use LINQ

LINQ is clearly gaining a fair amount of traction, given the number of posts I see about it on Stack Overflow. However, I've noticed an interesting piece of coding style: a lot of developers are using query expressions for every bit of LINQ they write, however trivial.

Now, don't get the wrong idea - I love query expressions as a helpful piece of syntactic sugar. For instance, I'd always pick the query expression form over the...Full Article.

Horrible grotty hack: returning an anonymous type instance

One of the reasons I don't view anonymous types as being too bad is that they're nicely confined to methods. You can't declare the type that you're returning from a method if it's anonymous (or if one of its type arguments is generic, e.g. a List<T> where T is an anonymous type and T isn't a type parameter to the method itself). However, you can get around this if you're sneaky.

I've always known that...Full Article.

Just Released: Validation Application Block Hands-On Lab

Reposting Grigori's announcement in case you missed it:

Here's a gift for the New Year's. We have produced a new hands-on lab on validation with Enterprise Library. It contains 13 exercises that walk you through capabilities of the Validation Application Block i...Full Article.

Asynchronous Fire and Forget With Lambdas

I've been having trouble getting to sleep lately, so I thought last night that I would put that to use and hack on Subtext a bit. While doing so, I ran into an old Asynchronous Fire and Forget helper method written way back by Mike Woodring which allows you to easily call a delegate asynchronously.

On the face of it, it seems li...Full Article.

Thursday, January 8, 2009

Building Web Sites with Telerik - Part 1

This article looks at building web sites using the control toolkit called Telerik, which is a third-party tool set that has great controls for building web sites. In this first part of the series, Brian examines how to setup a web site using the various controls shipped with the tool set. He starts with a detailed overview and then provides comprehensive coverage of the PanelBar, Rotator, and Docking controls with relevant source code followed by detailed analysis and screen shots.

Source Click Here.

Updates to the TextBox Word / Character Counter Control

When storing user-supplied text data into a database, it is essential that the length of the user's input does not exceed the size of the corresponding database table field. To ensure that a user's input is within the legal bounds, you can: set the TextBox control's MaxLength property (although this does not work for multi-line textboxes); use a validation control, such as my TextBoxLengthValidator control or a RegularExpressionValidator; use server-side code to check the Length property of the string before storing it in the database; or some combination of the above. The problem with these solutions is that they are not very interactive. The user doesn't know how close she is to hitting the maximum number of characters.

In October 2007 I created a custom ASP.NET server control that uses JavaScript to interactively display the number of characters and/or words a user has typed into a textbox, and wrote about it in an article titled Creating a TextBox Word / Character Counter Control. In the TextBoxCounter control's initial implementation is simply reported how many words or characters the user had entered. Because this control is most useful in scenarios where there is a limit to the number of characters or words allowed, a natural enhancement would be to allow the page developer to specify a maximum number of characters or words allowed. With this information, the control could be updated to show how many characters or words remain. Moreover, the appearance of the TextBoxCounter could be modified based on how close the user was to reaching the word or character limit.

Recently, 4Guys reader David Dude implemented these future enhancements and shared his code changes with me; I've since integrated them into the code base. This article looks at the enhancements to the TextBoxCounter control class and demonstrates how to use them in an ASP.NET page. Read on to learn more!
Read More >



Source Click Here.

The Joy of Code Reviews

As I mentioned in my recent post about how my team does agile, one of the core ingredients of our process is that nobody is allowed to check in without having gone through a code review and a test review. No other team that I've worked on previously has had such a rigorous process around code reviews - while we've had ad-hoc pair programming and occasional code walkthroughs, there were no rules about all code being reviewed before check-in. So when I first joined my new team at the SDC, I was unsure what to expect or if I'd like it. But as you might guess from the title of the post, I've become a convert.

First, let me go into a bit more detail about how the process works. A developer prepares a change set which normally consists of one completed requirement, or one or more bug fixes. Once they believe they are ready to check in, they will shout out "Code Review!", at which time any other developer who can spare some time will volunteer to be the reviewer. In some cases the "reviewee" will seek out a specific "reviewer" if they know them to be best qualified in the relevant technology or component.

A code review will typically take around 15 minutes, but they may be considerably longer or shorter. It takes place at the reviewee's computer (we normally have our entire team working in the same room. For a while we did have one developer in another location - in this case we mimicked the "same computer" approach by using desktop sharing and speakerphones). Normally there isn't any need to walk through the functional requirements or the high-level design in any detail, since the entire team is involved in the planning sessions and generally knows the critical details. However in some code reviews there may be some use of the whiteboard to communicate any design details that are needed to provided context to the code.

The review is performed by looking at the list of changed files in Visual Studio's "Pending Changes" window, going through them one-by-one (sometimes from top to bottom, sometimes in whatever order the reviewee thinks is most logical), and performing a "Compare with Latest" operation on each file. Most of us have Beyond Compare or something similar installed to make this easier, but the Visual Studio text comparer works OK as well. We don't have a specific checklist of things that need to be reviewed, but some typical areas for discussion include:

  • Quantity and quality of unit test coverage
  • Code readability, method and line length
  • Opportunities for reusing existing functionality, or merging new code with existing functionality
  • Naming conventions
  • Consistent application of patterns
  • Globalisation (appropriate use of culture classes, resource files etc.)
  • Hacks, shortcuts or other "smelly" code

If the reviewer is happy with everything in the change set, it's ready for a test review (or if that happened first, it's ready to be checked in). Alternatively, the reviewer can veto the check-in and insist that any uncovered issues are fixed first. In rare cases the reviewer may allow the check-in even if there are known issues, with TFS bugs or tasks created for tracking purposes. This option is most commonly used when the issues are minor and there are other developers waiting for the check-in before they can complete their own tasks.

So why did we choose to impose this additional workload across the development team? Well, it's certainly not because the developers make a lot of mistakes or need close supervision - the team is as experienced and capable as any I've worked with. And in fact it is quite rare for a code reviewer to veto a check-in - I don't have hard statistics but it probably only happens 1 time out of 10. Nevertheless I think the process extremely valuable for the reviewer, the reviewee and the quality of the codebase. First, each developer writes code with full knowledge that it will be scrutinised, so they take extra care to follow established patterns and avoid ugly hacks. Second, it helps "share the wealth" around who understands different parts of the solution. And finally it provides a very personal way for developers to learn from one another, whether it be a new Visual Studio shortcut key, a .NET API they didn't know existed, or a new architecture, design or testing technique.

One more interesting observation about how this process works in my team: at our "retrospective" meetings that we run at the completion of each iteration, there have been a number of occasions where people have called out that it takes too long to check in code. However I'm not aware of any situations where anyone in the team has suggested abolishing (or even streamlining) the code review or test review processes to achieve this outcome. And having the support and confidence of the team is the ultimate measure of the success of any process.



Source Click Here.

Handling Formats Based On Url Extension

Rob pinged me today asking about how to respond to requests using different formats based on the extension in the URL. More specifically, he'd like to respond with HTML if there is no file extension, but with JSON if the URL ended with .json etc...

/home/index -> HTML

/home/index.json -> JSON

The first thing I wanted to tackle was writing a custom action invoker that would decide based on what's in the route data, how to format the response.

This would allow the developer to simply return an object (the model) from an action method and the invoker would look for the format in the route data and figure out what format to send.

So I wrote a custom action invoker:

public class FormatHandlingActionInvoker : ControllerActionInvoker {    protected override ActionResult CreateActionResult(        ControllerContext controllerContext,         ActionDescriptor actionDescriptor,         object actionReturnValue) {      if (actionReturnValue == null) {        return new EmptyResult();      }        ActionResult actionResult = actionReturnValue as ActionResult;      if (actionResult != null) {        return actionResult;      }        string format = (controllerContext.RouteData.Values["format"]           ?? "") as string;        switch (format) {          case "":          case "html":            var result = new ViewResult {               ViewData = controllerContext.Controller.ViewData,               ViewName = actionDescriptor.ActionName             };            result.ViewData.Model = actionReturnValue;            return result;                      case "rss":            //TODO: RSS Result            break;          case "json":            return new JsonResult { Data = actionReturnValue };      }        return new ContentResult {         Content = Convert.ToString(actionReturnValue,          CultureInfo.InvariantCulture)       };    }  }

The key thing to note is that I overrode the method CreateActionResult. This method is responsible for examining the result returned from an action method (which can be any type) and figuring out what to do with it. In this case, if the result is already an ActionResult, we just use it. However, if it's something else, we look at the format in the route data to figure out what to return.

For reference, here's the code for the HomeController which simply returns an object.

[HandleError]  public class HomeController : Controller {    public object Index() {      return new {Title = "HomePage", Message = "Welcome to ASP.NET MVC" };    }  }

In order to make sure that all my controllers replaced the default invoker with this invoker, I wrote a controller factory that would set this invoker. I won't show the code here, but I will include it in the download.

So at this point, we have everything in place, except for the fact that I haven't dealt with how we get the format in the route data in the first place. Unfortunately, it ends up that this isn't quite so straightforward. Consider the default route:

routes.MapRoute(      "Default",      "{controller}/{action}/{id}",      new { controller = "Home", action = "Index", id = "" }  );

Since this route allows for default values at each segment, this single route matches all the following URLs:

  • /home/index/123
  • /home/index
  • /home

So the question becomes, if we want to support optional format extensions in the URL, would we have to support it for every segment? Making up a fictional syntax, maybe it would look like this:

routes.MapRoute(      "Default",      "{controller{.format}}/{action{.format}}/{id{.format}}",      new { controller = "Home", action = "Index", id = "", format = ""}  );

Where the {.format} part would be optional. Of course, we don't have such a syntax available, so I needed to put on my dirty ugly hacking hat and see what I could come up with. I decided to do something we strongly warn people not to do, inheriting HttpRequestWrapper with my own HttpRequestBase implementation and stripping off the extension before I try and match the routes.

Warning! Don't do this at home! This is merely experimentation while I mull over a better approach. This approach relies on implementation details I should not be relying upon

public class HttpRequestWithFormat : HttpRequestWrapper  {    public HttpRequestWithFormat(HttpRequest request) : base(request) {     }      public override string AppRelativeCurrentExecutionFilePath {      get      {        string filePath = base.AppRelativeCurrentExecutionFilePath;        string extension = System.IO.Path.GetExtension(filePath);        if (String.IsNullOrEmpty(extension)) {          return filePath;        }        else {          Format = extension.Substring(1);          filePath = filePath.Substring(0, filePath.LastIndexOf(extension));        }        return filePath;      }    }      public string Format {      get;      private set;    }  }

I also had to write a custom route.

public class FormatRoute : Route  {    public FormatRoute(Route route) :       base(route.Url + ".{format}", route.RouteHandler) {      _originalRoute = route;    }      public override RouteData GetRouteData(HttpContextBase httpContext)    {      //HACK!       var context = new HttpContextWithFormat(HttpContext.Current);        var routeData = _originalRoute.GetRouteData(context);      var request = context.Request as HttpRequestWithFormat;      if (!string.IsNullOrEmpty(request.Format)) {        routeData.Values.Add("format", request.Format);      }        return routeData;    }      public override VirtualPathData GetVirtualPath(      RequestContext requestContext, RouteValueDictionary values)    {      var vpd = base.GetVirtualPath(requestContext, values);      if (vpd == null) {        return _originalRoute.GetVirtualPath(requestContext, values);      }            // Hack! Let's fix up the URL. Since "id" can be empty string,        // we want to check for this condition.      string format = values["format"] as string;      string funkyEnding = "/." + format as string;            if (vpd.VirtualPath.EndsWith(funkyEnding)) {         string virtualPath = vpd.VirtualPath;        int lastIndex = virtualPath.LastIndexOf(funkyEnding);        virtualPath = virtualPath.Substring(0, lastIndex) + "." + format;        vpd.VirtualPath = virtualPath;      }        return vpd;    }      private Route _originalRoute;  }

When matching incoming requests, this route replaces the HttpContextBase with my faked up one before calling GetRouteData. My faked up context returns a faked up request which strips the format extension from the URL.

Also, when generating URLs, this route deals with the cosmetic issue that the last segment of the URL has a default value of empty string. This makes it so that the URL might end up looking like /home/index/.json when I really wanted it to look like /home/index.json.

I've omitted some code from this blog post, but you can download the project here and try it out. Just navigate to /home/index and then try /home/index.json and you should notice the response format changes.

This is just experimental work. There'd be much more to do to make this useful. For example, would be nice if an action could specify which formats it would respond to. Likewise, it might be nice to respond based on accept headers rather than formats. I just wanted to see how automatic I could make it.

In any case, I was just having fun and didn't have much time to put this together. The takeaway from this is really the CreateActionResult method of ControllerActionInvoker. That makes it very easy to create interesting default behavior so that your action methods can return whatever they want and you can implement your own conventions by overriding that method.

Download the hacky experiment here and play with it at your own risk. :)

Tags:


Source Click Here.

'WebForm_PostBackOptions' is undefined error, ASP.NET 2.0

Recently one of our customers had an issue when migrating from ASP.NET 1.1 to ASP.NET 2.0.  The issue came up particularly in the deployment server where any page that had validations raised the error 'Webform_PostBackOptions' is undefined.

If you had worked with ASP.NET 1.1 you would recollect there was an aspnet_client folder that contains all the scripts that help in client side validation as well as raising the postback events.

In ASP.NET 2.0, the "WebResource.axd" file is the handler that generates all the client side scripts which were earlier processed by the aspnet_client folder.

Coming back to this particular customer scenario, they were running URL Scan utility on their server http://learn.iis.net/page.aspx/473/using-urlscan 

URL Scan is an useful free utility that can be installed on servers that allows you to restrict the file extensions served by the IIS.  This way, potentially harmful requests can be denied and thereby injection attacks avoided.

However, the WebResource.axd handler had to be manually added as an extension to be allowed and thereafter this error went off.

There are many more causes of this particular error and I found that it has been discussed enough in forums.  Here below is one of them for your reference

http://www.eggheadcafe.com/tutorials/aspnet/03cedfc8-e623-4fee-81d8-04663b71b675/aspnet-11-to-aspnet-2.aspx

 

Cheers !!!



Source Click Here.

Monday, January 5, 2009

Tip #41: Did you know... establishing a remote connection to a IIS server with self-issued certificate will require a certificate validation delegate?

Either through WMSvc or through your own script, whenever you try to establish a connection with a remote server, which doesn’t provide a trusted certificate you need to provide a delegate for this certificate validation check to validate untrusted certificates.

The signature for this delegate is as follows

Namespace: System.Net.Security
Assembly:  System (in System.dll)

public delegate bool RemoteCertificateValidationCallback(      Object sender,      X509Certificate certificate,      X509Chain chain,      SslPolicyErrors sslPolicyErrors  )

Thus, to accept ALL server certificates, you will need to set the callback of ServicePointManager to validate a server certificate in the following manner:

ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallbackFlag;    bool RemoteCertificateValidationCallbackCheck(      Object sender,      X509Certificate certificate,      X509Chain chain,      SslPolicyErrors sslPolicyErrors  )  {      return true;  }

For the official MSDN documentation on this delegate refer to RemoteCertificateValidationCallback Delegate and ServicePointManager.ServerCertificateValidationCallback Property

Kateryna Rohonyan
SDET, IIS Team



Source Click Here.

Fun With Named Formats, String Parsing, and Edge Cases

Recently I found myself in a situation where I wanted to format a string using a named format string, rather than a positional one. Ignore for the moment the issue on whether this is a good idea or not, just trust me that I'll be responsible with it.

The existing String.Format method, for example, formats values according to position.

string s = string.Format("{0} first, {1} second", 3.14, DateTime.Now);

But what I wanted was to be able to use the name of properties/fields, rather than position like so:

var someObj = new {pi = 3.14, date = DateTime.Now};  string s = NamedFormat("{pi} first, {date} second", someObj);

Looking around the internet, I quickly found three implementations mentioned in this StackOverflow question.

All three implementations are fairly similar in that they all use regular expressions for the parsing. Hanselman's approach is to write an extension method of object (note that this won't work in VB.NET until they allow extending object). James and Oskar wrote extension methods of the string class. James takes it a bit further by using DataBinder.Eval on each token, which allows you to have formats such as {foo.bar.baz} where baz is a property of bar which is a property of foo. This is something else I wanted, which the others do not provide.

He also makes good use of the MatchEvaluator delegate argument to the Regex.Replace method, perhaps one of the most underused yet powerful features of the Regex class. This ends up making the code for his method very succinct.

Handling Brace Escaping

I hade a chat about this sort of string parsing with Eilon recently and he mentioned that many developers tend to ignore or get escaping wrong. So I thought I would see how these methods handle a simple test of escaping the braces.

String.Format with the following:

Console.WriteLine(String.Format("{{{0}}}", 123));

produces the output (sans quotes) of "{123}"

So I would expect with each of these methods, that:

Console.WriteLine(NamedFormat("{{{foo}}}", new {foo = 123}));

Would produce the exact same output, "{123}". However, only James's method passed this test. But when I expanded the test to the following format, "{{{{{foo}}}}}", all three failed. That should have produced "{{123}}".

Certainly this is not such a big deal as this really is an edge case, but you never know when an edge case might bite you as Zune owners learned recently. More importantly, it poses an interesting problem - how do you handle this correctly? I thought it would be fun to try.

This is possible to handle correctly using regular expressions, but it's challenging. Not only are you dealing with balanced matching, but the matching depends on whether the number of consecutive braces are odd or even.

For example, the following "{0}}" is not valid because the right end brace is escaped. However, "{0}}}" is valid. The expression is closed with the leftmost end brace, which is followed by an even number of consecutive braces, which means they are all escaped sequences.

Performance

As I mentioned earlier, only James's method handles evaluation of sub-properties/fields via the use of the DataBinder.Eval method. Critics of his blog post point out that this is a performance killer.

Personally, until I've measured it in the scenarios in which I plan to use it, I doubt that the performance will really be an issue compared to everything else going on. But I thought I would check it out anyways, writing a simple console app which runs each method over 1000 iterations, and then divides by 1000 to get the number of milliseconds each method takes. Here's the result:

format perf

Notice that James's method is 43 times slower than Hanselman's. Even so, it only takes 4.4 milliseconds. So if you don't use it in a tight loop with a lot of iterations, it's not horrible, but it could be better.

My Implementation

At this point, I thought it would be fun to write my own implementation using manual string parsing rather than regular expressions. I'm not sure my regex-fu is capable of handling the challenges I mentioned before. After implementing my own version, I ran the performance test and saw the following result.

haackformat perf

Nice! by removing the overhead of using a regular expression in this particular case, my implementation is faster than the other implementations, despite my use of DataBinder.Eval. Hopefully my implementation is correct, because fast and wrong is even worse than slow and right.

One drawback to not using regular expressions is that the code for my implementation is a bit long. I include the entire source here. I've also zipped up the code for this solution which includes unit tests as well as the implementations of the other methods I tested, so you can see which tests they pass and which they don't pass.

The core of the code is in two parts. One is a private method which parses and splits the string into an enumeration of segments represented by the ITextExpression interface. The method you call joins these segments together, evaluating any expressions against a supplied object, and returning the resulting string.

I think we could optimize the code even more by joining these operations into a single method, but I really liked the separation between the parsing and joining logic as it helped me wrap my head around it. Initially, I hoped that I could cache the parsed representation of the format string since strings are immutable thus I could re-use it. But it didn't end up giving me any real performance gain when I measured it.

public static class HaackFormatter  {    public static string HaackFormat(this string format, object source)    {        if (format == null) {          throw new ArgumentNullException("format");      }        var formattedStrings = (from expression in SplitFormat(format)                   select expression.Eval(source)).ToArray();      return String.Join("", formattedStrings);    }      private static IEnumerable<ITextExpression> SplitFormat(string format)    {      int exprEndIndex = -1;      int expStartIndex;        do      {        expStartIndex = format.IndexOfExpressionStart(exprEndIndex + 1);        if (expStartIndex < 0)        {          //everything after last end brace index.          if (exprEndIndex + 1 < format.Length)          {            yield return new LiteralFormat(                format.Substring(exprEndIndex + 1));          }          break;        }          if (expStartIndex - exprEndIndex - 1 > 0)        {          //everything up to next start brace index          yield return new LiteralFormat(format.Substring(exprEndIndex + 1            , expStartIndex - exprEndIndex - 1));        }          int endBraceIndex = format.IndexOfExpressionEnd(expStartIndex + 1);        if (endBraceIndex < 0)        {          //rest of string, no end brace (could be invalid expression)          yield return new FormatExpression(format.Substring(expStartIndex));        }        else        {          exprEndIndex = endBraceIndex;          //everything from start to end brace.          yield return new FormatExpression(format.Substring(expStartIndex            , endBraceIndex - expStartIndex + 1));          }      } while (expStartIndex > -1);    }      static int IndexOfExpressionStart(this string format, int startIndex) {      int index = format.IndexOf('{', startIndex);      if (index == -1) {        return index;      }        //peek ahead.      if (index + 1 < format.Length) {        char nextChar = format[index + 1];        if (nextChar == '{') {          return IndexOfExpressionStart(format, index + 2);        }      }        return index;    }      static int IndexOfExpressionEnd(this string format, int startIndex)    {      int endBraceIndex = format.IndexOf('}', startIndex);      if (endBraceIndex == -1) {        return endBraceIndex;      }      //start peeking ahead until there are no more braces...      // }}}}      int braceCount = 0;      for (int i = endBraceIndex + 1; i < format.Length; i++) {        if (format[i] == '}') {          braceCount++;        }        else {          break;        }      }      if (braceCount % 2 == 1) {        return IndexOfExpressionEnd(format, endBraceIndex + braceCount + 1);      }        return endBraceIndex;    }  }

And the code for the supporting classes

public class FormatExpression : ITextExpression  {    bool _invalidExpression = false;      public FormatExpression(string expression) {      if (!expression.StartsWith("{") || !expression.EndsWith("}")) {        _invalidExpression = true;        Expression = expression;        return;      }        string expressionWithoutBraces = expression.Substring(1          , expression.Length - 2);      int colonIndex = expressionWithoutBraces.IndexOf(':');      if (colonIndex < 0) {        Expression = expressionWithoutBraces;      }      else {        Expression = expressionWithoutBraces.Substring(0, colonIndex);        Format = expressionWithoutBraces.Substring(colonIndex + 1);      }    }      public string Expression {       get;       private set;     }      public string Format    {      get;      private set;    }      public string Eval(object o) {      if (_invalidExpression) {        throw new FormatException("Invalid expression");      }      try      {        if (String.IsNullOrEmpty(Format))        {          return (DataBinder.Eval(o, Expression) ?? string.Empty).ToString();        }        return (DataBinder.Eval(o, Expression, "{0:" + Format + "}") ??           string.Empty).ToString();      }      catch (HttpException) {        throw new FormatException();      }    }  }    public class LiteralFormat : ITextExpression  {    public LiteralFormat(string literalText) {      LiteralText = literalText;    }      public string LiteralText {       get;       private set;     }      public string Eval(object o) {      string literalText = LiteralText          .Replace("{{", "{")          .Replace("}}", "}");      return literalText;    }  }

I mainly did this for fun, though I plan to use this method in Subtext for email fomatting.

Let me know if you find any situations or edge cases in which my version fails. I'll probably be adding more test cases as I integrate this into Subtext. As far as I can tell, it handles normal formatting and brace escaping correctly.



Source Click Here.

Friday, January 2, 2009

Year End Reading for 2008

A small set of links reviewing 2008, and looking forward to 2009, from tech to news to photos, annotated with some personal comments...

Source Click Here.

Reading: Designing for the Social Web

A little bit about Designing for the Social Web - an interesting, insightful and fun read on what to keep in mind when designing social experiences on the web.

Source Click Here.

Predictions for 2009

Every year I ask everyone I know to try to make some predictions for the following year.  Truthfully, I've never gone back and compared my predictions with reality (that would spoil the fun I think).  Well, here are my predictions for 2009.

  1. Deep / Long Recession:  2009 will be a year of change in the IT industry, sparked, of course, by the recession that started in 2008.  With every recession we face there will be challenges, but there will also be opportunities.  I predict that there will be a "weeding" out of IT organizations, those who will survive will be the ones who have adapted their practices even before the recession took hold. 
  2. Spark of Innovation:  Recessions always get us to think about doing more with less - and I think that this will further spark new ideas on how we can add value to business and industry as a whole. 
  3. Head in the Cloud:  Doing more with less, being nimble, cutting operational costs, reducing risks - these are all great reasons why I think cloud services will become much more mainstream.
  4. Too Many Damn Social Network and Social Network Aggregators:  2008 truly birthed social networking (I remember, this was something I did predict).  Social networking has proliferated throughout our societies entire online life - from our computers, to our mobile devices, and of course into the world of online gaming.  Facebook has proven to be a catalyst for them all - Twitter has truly taken hold - and there are dozens of others such as Ping.fm that can be used to help broadcast our lives out into the ether like never before.  These types of communities will reach a turning point this year.
  5. SharePoint 2010 will be announced:  (I'm speculating here folks) SharePoint will go through another revolutionary change - just as it has done with every release.  SharePoint will bring not only advances in document management but it will begin to truly leverage Silverlight from a user experience perspective.  I predict that Microsoft will also announce much of what we see in the new online Live services down into the SharePoint space - allowing organizations to have Micro-social networks much easier than we can today with the product.  I also believe that SharePoint will be "meshafied" - meaning, we should be able to experience SharePoint leveraging offline/synchronization functionality that mesh and the synchronization framework have. 
  6. Microsoft Groove will morph:. into the "meshafied" version of SharePoint.  We will have offline content of virtually all aspects of SharePoint - from the social network experience to document and list management. 
  7. Azurameshafication: Microsoft Azure offers cloud solutions, and many organizations will start to provide services using these core services.  That's a given, however, I also predict that Microsoft Mesh will play a much larger role and savvy organizations will think long and hard about coupling a fantastic online experience with a P2P/Offline experience.
  8. 100 Gb of Online Storage for the World:  Today SkyDrive gives us 25gigs of free online space.  I predict that throughout the year, as the demand for cloud services increases, Google, Microsoft, and Amazon will jump frog each other providing more and more free online storage until each of us can get up to 100 GB of storage for free.
  9. Explosion of User Experience:  Silverlight 2.0 now makes it more realistic to build business applications outside of the traditional ASP.NET/WPF/Winform boundaries.  Today a lot of the Silverlight controls for business applications look very similar to Winform control - and I think in 2009 those organizations who will truly push these boundaries of user experience controls will truly make the biggest influence on how the world works.  I predict 1 or 2 vendors who will offer amazingly innovative and useful Silverlight controls that will allow us to express business value in ways we haven't seen today.
  10. Windows 7 Hype:  I believe that Windows 7 will have a great deal more hype.  Software vendors will be biting at the bit trying to think of ways of providing multi-touch user experiences to their apps (see prediction #9).  Microsoft will announce limited multi-touch functionality to Vista SP3 scheduled  to be released the late part of 2009 or early 2010.
  11. Microsoft to announce Office 2010 Live will be pay per use:  I predict that Microsoft announce that they will give away base functionality for Office Live 14, and also provide greater functionality/scale/features/no-adverts to those willing to pay incrementally on either a pay per use model or a monthly subscription model.

Let me know what you think by posting your own predictions and linking to mine! 

Happy New Year everyone! 



Source Click Here.

Tip #40: Did you know.How to scope master pages?

Master page is a  template page that can be used to create a consistent layout for your application. First you create a master page to define the look & feel of the application and then you create the content pages that contains the content.

You can attach these content pages to the master page at the following three levels:

  1. Page Level: You can use the page directive on each of the content pages

    <@Page Language="VB" MasterPageFile="~/Main.master"%>

    Or programmatically set it in the content page Page_PreInit Event

    for VB
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
            Me.MasterPageFile = "~/Main.master"
    End Sub

    for C#
    protected void Page_PreInit(Object sender, EventArgs e)
            {
                this.MasterPageFile = "~/Main.Master";
            }

  2. Application Level : By specifying the following in web.config file, all the aspx files will use the master page as Main.master (If  aspx file does not contain a Content control, the master page won't be applied to it )

    <configuration>
        <system.web>
                   <pages masterPageFile="~/Main.master" />
       </system.web>
    </configuration>

    [You will notice that the pages node already exists in web.config, add the masterPageFile attribute to this node]

  3. Folder Level: By specifying the following in web.config all the aspx files in a specified folder (admin) will use the master page as Admin.master (If  aspx file does not contain a Content control, the master page won't be applied to it )

    <configuration>
        <location path="admin">
        <system.web>
                   <pages masterPageFile="~/Admin.master" />
       </system.web>
       </location>
    </configuration>

    [you will notice system.web already exists, leave it as it is & add a new node 'location' with the above content under 'configuration']

By setting master page programmatically or thru web.config you may not get the Visual Studio master page design time features.

 

Deepak Verma
SDET | Visual Web Developer



Source Click Here.

Not Your Typical Top Ten Of 2008 Post

At the end of the year, it's very common for bloggers to take a look back at their own blog and list their favorite 10 blog posts. I find that somewhat narcissistic, so you know I'm going to do that.

But before I do, I thought it would be great to list the top 10 blog posts by others I read in 2008. The only problem is, I have very bad short-term memory and I can't seem to remember which ones I read that had a real impact on my thinking. I'll have to try and keep better track in 2009.

So based on a cursory Google search and look through my Google Reader app, here are some of my favorite blog posts of 2008 by you all, I couldn't even list 10. Please do comment with your own favorite blog posts, mine or otherwise of 2008.

Favorite Posts I Read

My Top Posts (Using the Ayende Formula)

A while back, Ayende wrote up a weighted query for Subtext to determine the top posts. I updated it to only include mine published in 2008. Here are the top 5.

Milestones Moments

There are some posts that I personally liked because they represent important events that happened to me in 2008.

Ok, so maybe this post is pretty typical and doesn't live up to the title I gave it. Oh well, I tried.

I'm sure I'm forgetting a whole lot of other important events that happened in 2008. I'm probably neglecting great blog posts that I read. But that's the great thing about a blog, I'm confident people will point out my shortcomings in the comments to this post, and for that, I'm grateful. You all rock!

And with that, I leave you with this moment of zen, a photo taken near my house.

giant snowman



Source Click Here.

Originals Enjoy