MVC3 Routing

March 30, 2011 § 3 Comments

MVC3 Routing

MVC3 gives you great control over how URLs are mapped to your controllers. It gives you the ability to define your URLs in a human readable SEO (Search Engine Optimization) friendly fashion, to remap old URLs to new functionality and side-by-side utilize classic ASP.NET sites inside of MVC3.

MVC3 Basics

MVC3 routes are defined in the Global.asax.cs file of your MVC3 web application. By default, there is only one route defined in the RegisterRoutes method that looks like the line below.

routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

This route defines the route name, which can be anything as long as it is unique, the URL template, and the parameter defaults. The default route that is pre-defined for you maps to Controller/Action/id. You can add additional routes by copying the same line and adjusting the URL parameters and the related default values.

Custom MVC3 Routes

One of the many factors frequently considered by search engines to determine the relevance of a particular page to a particular search term is whether or not the URL link itself includes a particular term. In a classic ASP.NET site for a magazine, you might have a URL that looks like http://www.internet.com/ViewArticle.aspx?id=123. This URL passes the ID number of the article to view, but the URL itself doesn’t describe the content in any human readable way. If the URL instead was http://www.internet.com/MVC3_Routing/123 a human-or a web crawler-could read that and know that the article is about MVC3 Routing.

Another frequent use of custom routing is to allow multiple sites to link to the same location while providing additional data about where they came from. For example, if you had a link to a product page and you wanted to provide custom co-branding based on which one of your partners linked in to a page, you could do so by including a “partner name” variable in the link. A link like this could be to http://www.internet.com/PartnerA/Article/123 or http://www.internet.com/PartnerB/Article/123 for example. This would allow two different sites to link to the same article while providing their own information in the process.

The code block below defines a new route called ArticleRoute that defines a new parameter called article in addition to the standard controller and action.

routes.MapRoute(
                "ArticleRoute",
                "{article}/{controller}/{action}", 
                new { article="Unknown", controller = "Home", action = "Index" }             );

You can access this custom article part of the route in your controller by accessing the RouteData object.

RouteData.Values["article"]

To access the RouteData object in your Razor views, use the @Url.RequestContext.RouteData object.

When you are constructing URLs that use string data such as article titles or author’s names, you will need to use some form of URL-friendly encoding. The easiest method is to use HttpUtility.UrlEncode(“Your String”) which will replace all of the URL unfriendly characters with the appropriate HTML escapes.B This method is web spider friendly but not necessarily human readable URL friendly.

It is very important to remember that any data in a URL is easily user manipulated and shouldn’t be trusted. It is not an appropriate place to pass application variables between pages unless they are of a nature that it would be acceptable if the user manipulated them.

Re-mapping Routes

From time to time it is necessary to re-route an old URL to a new location. Traditionally you would use a redirect page to let users know to update their bookmarks and include a link to the new location. Sometimes it is impractical or even impossible to change URLs as is the case when you have 3rd partysoftware systems set up to access and scrape particular URLs.

If you wanted to route MyRazor.cshtml page to your MVC3 Home/Index controller, you can do so by defining a route like the one below.

routes.MapRoute("RT", " MyRazor.cshtml ",
                new { controller = "OtherController", action = "Packed" });

Including Classic ASP.NET as a Sub-directory in an MVC3 Web Application

If you have a large classic ASP.NET web site that you need to incrementally transition to MVC3 you can put the entire classic ASP.NET web site in your MVC3 web site as a sub-directory. You can then call the IgnoreRoute method seen in the code block below to tell MVC3 to not handle that particular URL path.

routes.IgnoreRoute("OldClassicASP/");

Constraints

You can define additional constraints to your defined routes to insure that the values passed for particular parts of your route are valid. This is useful not only for general security related needs but is also useful for scenarios where you might want to have additional routing logic in place for particular routes.

routes.MapRoute(
                "ColorPath", // Route name
                "{color}/{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                , new { color="blue" }
            );

In the example route above, a new anonymous object is added to the MapRoute path call that adds a constraint to this path. The route will only be used if the color is blue.

Namespaces

In large ASP.NET MVC3 applications you can potentially have hundreds of controllers. This can become problematic because the .NET Framework looks in the Controllers folder and all sub-folders looking for controllers to match up with the defined routes.

To help you organize your code, you can add namespaces to your routes to constrain the controllers the route will match to particular namespaces. The route below will only use controllers defined in the Home.Guru namespace.

routes.MapRoute("NamespacedRoute", "Cool/{controller}/{action}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } , null,
                , new string[] { "Home.Guru" });

Global Filters

If you want to define code that runs before or after your routing calls, you can define a global filter. Global filters are registered in the Global.asax.cs file by adding a line to the RegisterGlobalFilters method. This method, by default, registers the HandleErrorAttribute that is used to handle error conditions in ASP.NET MVC3 applications.

If you wanted to add a copyright notice at the bottom of all of your pages, you could add a global filter attribute that overrides the OnResultExecuted method which is run after your page has run.

public class CopyrightNoticeAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Write(String.Format("<h1>Copyright {0}</h1>",DateTime.Now.Year));
        }
    }

Once your custom attribute has been written you can add it to the global.asax.cs file.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CopyrightNoticeAttribute());
filters.Add(new HandleErrorAttribute());//Default in MVC3
}

Conclusion

Understanding how to customize and control the routing in ASP.NET MVC3 helps you organize your solution and gives you powerful tools to maintain your web application. Additional tools like global filters give you the ability to add code that cross-cuts your MVC3 views and can even add sophisticated logic to re-route your controllers.

 

(source : codeguru.com, article by David Talbot)

 

 

The Dumbest Ways To Interview A Developer

March 24, 2011 § Leave a comment

The Dumbest Ways To Interview A Developer

What’s the dumbest interview question you’ve ever been asked? Write it in the Comments section below.

If you were required to write code after becoming intoxicated, could you do it? Would you write better code? Worse?

This is exactly how Facebook selected their first interns, if we are to believe The Social Network movie. Who knows if it really happened or is a techie urban legend? Perhaps it truly contributed to selecting developers who supported Facebook’s meteoric rise.

Honestly, it seems ridiculous to me. Would you really want your developers coding drunk? What did this prove?

I will admit that I have written code with a buzz on (in college, of course). Surely it wasn’t my best effort – as proven by the lousy grade the assignment received. Certainly, alcohol should not play a part in evaluating someone’s coding capability.

Evaluating talent in a short time period associated with the interview process is challenging (with or without alcohol). Over the years, I have been through a lot of interviews on both sides and experienced many interesting approaches.

I personally have been asked a lot of dumb and irrelevant interview questions. Since it is already difficult to find the best developers in hot markets like mobile and social computing, interview questions should be crafted that not only help screen out the unqualified developers but – probably more important – don’t tick off the best developers.

It is fair and hopefully obvious to ask developers questions that directly relate to their claimed expertise. As I pointed out in a recent article, it is reasonable to use Google to look up common methods of solving problems during day-to-day work. Googling doesn’t diminish a developers capability, it enhances it.

However, developers should be able to answer the basics in an interview – without Googling.

What they shouldn’t have to answer are really dumb questions or go through irrelevant exercises. This just wastes everyone’s time.

One interview approach that’s essentially wasted time is to use brain teasers. My java-developer brother-in-law was recently lamenting about a so-called brain teaser that was asked of him during an interview. I forget the exact wording, but it had to do with figuring out what light switches controlled which light bulbs if you couldn’t see the bulbs as you operated the switches.

What the heck do light bulbs have to do with writing java code?

Plus you can go to sites where the most common brain teasers are asked and memorize answers. I found the light bulb answer on my first Google search. Or someone who interviewed at that company may have shared the brain teaser on their Facebook page.

Sure, developers need to have a sound ability to think through problems. However, I’d argue that this capability is more applicable to designers and architects. Developers typically need to take specifications that some designer created and turn it into software. Therefore, the ability to solve a brain teaser isn’t the greatest indicator of a great developer.

Then there are the “no win” questions. The purpose seems to be to box someone into a corner and see how they respond. This happened to a friend of mine who was on his third on-site interview with a software firm. All had gone swell and he was in the final interview with one of the founders when he was asked this question”

“Would you ever quit this job or leave the company?”

My buddy Joe was totally taken off guard. He had studied and prepared on how to answer the toughest interview questions, but not this one. With his future on the line, he evidently said the wrong thing. The exchange went something like this.

Joe: “What do you mean?”

Mr. CEO: “I only hire people who believe in the company and go the extra mile.”

Joe: “I am your man. I am passionate, hard working and take pride in my work.”

Mr. CEO: “But would you ever leave?”

Joe: “Well, I am not sure how to answer that question. I imagine that if the company and I continue to have a ‘win-win’ relationship, then no, I would not leave.”

Mr. CEO: “What if someone offered you twice your current salary?”

Joe: “I don’t know, maybe, I would consider that if things aren’t going well here for me.”

Mr. CEO: “Then, sorry, we can’t hire you. I only want people who will be here for the long haul.” That was it. Basically – don’t let the door hit you in the rear on the way out!

Here Joe had proven he was a solid developer, passing all peer and manager interviews with flying colors. Yet, one improbable question sunk his hopes. That just doesn’t make sense and everyone’s valuable time was wasted.

You know what else doesn’t make sense? Asking a software developer candidate to deliver a presentation. Granted, some developers do just fine at a white board, even in front of a big audience. And if the job requirements include the ability to present, then this is a reasonable request.

But if you are simply trying to determine if someone can write code, then how they solve a problem in front of a group of people doesn’t seem appropriate.

As an example, I can share the story of another friend of mine who works for a placement agency that places developers. Her firm had a candidate go through multiple interviews that culminated in a required presentation to a group. The candidate’s presentation went very well with a lot of back slapping afterward.

Yet when the recruiter followed up she was told her client would not be extending an offer. She was told that her candidate had looked at notes during the presentation and that didn’t exude enough confidence that the position requires.

Right. Should have left the notes at home. Are you kidding me?!?!

Finally, my least favorite question that I was ever personally asked has to be “What were you like in high school?”

Really?

I wanted to say, “What on earth does that have to do with me writing code?” But instead it led me down a rambling path of explaining why I quit the drum line in my senior year. My interviewer just stared at me disapprovingly. Obviously if I quit the band, then I would not be a reliable developer (as an adult no less).

When it comes down to it, you have to be prepared for anything in an interview and react as calmly and smartly as possible.

And if you happen to be offered a cocktail during your interview? Well, that’s your call. I’d venture a guess that Facebook no longer requires intoxication during their interviews.

I’d like to hear some of your experiences. What are some of the worst questions you were ever asked? Would any question actually cause you to turn down an offer or even walk out of an interview?

 

Firefox 4 Debuts Faster, More Secure Browser

March 24, 2011 § Leave a comment

Firefox 4 Debuts Faster, More Secure Browser

After 12 betas, 2 release candidates and over nine months of development, Mozilla today is officially releasing its next generation open source Firefox 4 web browser.

Firefox 4 is the first major browser update since Mozilla released Firefox 3.6 in January of 2010.

With Firefox 4, Mozilla developers have made multiple user facing changes that are very noticeable. Tabs are now on top of the address bar by default, instead of below as they have been ever since Firefox was first conceived. The user interface itself has been revamped in an effort to reduce clutter.

“We spent a bunch of time on the interface, making it as streamlined as possible, making it easy to get to the things that you want and also easy to get things out of your way” Johnathan Nightingale, director of Firefox at Mozilla toldInternetNews.com. “Moving from Firefox 3.6 to 4.0, we’ve compacted the interface, since most of the time users don’t need the whole menu.”

The ‘home’ button has been moved to the right of the address bar and the RSS icon has also been removed from the default display. Nightingale stressed that Mozilla has not taken any functionality away from the browser, they’ve just moved items from the default display in an effort to improve usability and efficiency.

Firefox 4 also integrates the Firefox Sync technology which enables users to synchronize their browser tabs and history across multiple systems. Firefox Sync extends to mobile platforms including Apple’s iOS by way of the Firefox Home application.

Tabs

Another key aspect of usability is the new Panorama feature, which enables users to group tabs together. Tabs are also improved by way of the new App Tab feature which pins a tab to the left of the browser.

“App tabs is a recognition that the way people use the web today is different,” Nightingale said. “Something like Gmail is not simply a web page that a user opens then closes, it’s an application that happens to live on the web.”

Another tab improvement comes by way of a notification element. If something has changed within an app tab, in Firefox 4 there is now a blue glow that appears around the favicon. So for example if a user has a Gmail app tab, whenever new email is received the tab will now have a blue glow.

Extensions

Mozilla’s extension system has also undergone a dramatic change for Firefox 4. The new browser makes use of the new Mozilla Jetpack platform which enables users to install and run extensions without the need to reload the browser.

For developers, Jetpack also makes it easier to build extensions by using JavaScript.

“You don’t have to learn XUL, you can just pull in some JavaScript APIs that feel a lot like web-based platforms,” Nightingale said.

Nightingale noted that extensions that were not built with Jetpack will still also run in Firefox 4. Mozilla’s add-ons site does identify which extensions require a restart and which ones do not.

Security

On the security front, Firefox 4 includes Mozilla’s Do Not Track implementation. With Do Not Track, browser users are able to alert sites whether or not they want to be tracked. It is still up to the websites themselves however to actually support the specification or not.

Both Google Chrome and Microsoft’s IE 9 each have their own respective versions of a Do Not Track implementation.

There is also a new Content Security Policy feature in Firefox 4, which could potentially mitigate most of the risk associated with Cross Site Scripting (XSS) attacks.

“Content Security Policy lets sites say where they expect to be loading content from,” Nightingale explained. “So if script is loaded from somewhere else, it’s likely a XSS vulnerability on the website.”

Nighingale noted that CSP enables websites to block non-authorized JavaScript from running. Additionally the system can report unauthorized script usage as well.

“The reporting aspect means that every Firefox 4 users makes the web safer,” Nightingale said. “If a Firefox 4 user is the first one to see an un-authorized script, we’ll send back the ping and the site can see that and they can fix the bug.”

The other key new security features is HTTP Strict Transport Security (HSTS) which can force SSL security to be used. The HSTS feature is important as it can help users to be protected against potential credential sniffing attacks like the one propagated by Firesheep earlier this year.

Performance

Mozilla developers have also been determined to ensure that Firefox 4 is the fastest browser yet. Developers enhanced the JagerMonkey JavaScript engine in an effort to boost performance.

Having a fast browsing experience all begins with how fast the browser starts, which was also an area of improvement in Firefox 4.

“We’re not interested in optimizing for a specific benchmark, but we’re very interested in optimizing for common workloads,” Nightingale said.

Sean Michael Kerner is a senior editor at InternetNews.com, the news service of Internet.com, the network for technology professionals.

 

Click Once Deployment not as promising as it’s promoted

March 16, 2011 § 2 Comments

Click once Deployment could have been one of best deployment method Microsoft introduce. But there are too many bugs.

first bug I found is that it creates a folder called application files which has space creating a lots of problem

Then if we edit any file we need to changes in manifest

There r very few scope to make it more flexible

Difficult to integrate encryption to app config files in term of security

But the best part is we dont have to notify for every verdin update it automatically picks latest version

Hoping Microsoft comes with very sexy solution later… I like like the click once deployment waiting from them…

Cloud Computing vs. Grid Computing: Does It Matter for Developers?

March 10, 2011 § 1 Comment

Should developers care whether the infrastructure supporting their apps is in the cloud or in a grid? Absolutely. Each has its pros and cons — and until recently, the cloud and grid computing models did not combine the best of both worlds in a single solution.

GridGain, a small cloud vendor, claims to have a solution that merges the cloud and grid computing, allowing developers to maximize the benefits of both models on one platform.

Cloud vs. Grid Computing

Cloud computing and grid computing are scalable, employing multitenancy architectures and multitasking. Both models also provide service-level agreements (SLAs) for guaranteed uptime availability. Where they differ is in their fundamental offerings:

  • A public cloud enables companies to scale up to massive capacities in an instant, without having to invest in new infrastructure, train new personnel, or license new software.
  • A computational grid system enables companies to use software to divide one large computing job into many portions across multiple machines, which can number in the thousands.

The cloud model does more than maximize computing power (grid’s main strength), as a cloud can provide many different services from Web hosting to word processing.

“A lot of people really get confused on cloud versus grid,” said Mike DiPetrillo, a senior engineer at VMware. “The two are closely related. I always think about it in terms of virtualization versus grid. Grid is great if you have an app that needs a lot of combined compute cycles. Virtualization is great if you have a lot of apps that need little compute cycles each.”

Cloud encompasses both grid and virtualization, he added.

“The point of cloud is you don’t have to care if you have a grid infrastructure underneath or a virtualization infrastructure underneath. All you do is deploy your app to the cloud and let the cloud figure out how to get the app the resources it needs.”

That’s why cloud is the over-arching architecture for virtualization, grid, SaaS, PaaS or anything else you can think of, said DiPetrillo.

The Shortcomings of Grid Computing Alone

One concern about grid is that if one piece of the software on a node fails, other pieces of the software on other nodes may also fail. This is alleviated if that component has a failover component on another node, but problems can still arise if components rely on other pieces of software to accomplish one or more grid computing tasks.

The large system images and associated hardware to operate and maintain them can create big capital and operating expenses as well.

Sometimes security and outages pose problems, but interoperability can be the biggest issue. If a company outsources or creates applications with one cloud computing vendor, and then decides to switch to another cloud vendor, the company may find it has to deal with two sets of proprietary APIs and different formats for importing and exporting data.

The GridGain Developer Story

To make the cloud as easy and powerful to use as possible for developers, GridGain created its GridGain platform.

“This is the world’s first and only cloud application platform that combines state of the art computation and data grid technologies in one product,” said Nikita Ivanov, GridGrain’s CEO.

Using GridGain, developers no longer need to sacrifice features by emulating compute grid with data grid or vice versa, said Ivanov.

“Our platform allows developers to avoid any manual deployment of user code, while providing advanced cloud-enabled, on-demand loading to any JVM-based applications,” he said. “There are no websites to click through, no awkward manual network configuration or restarts, no Ant/Maven builds, no IDE plugins, and no custom management consoles required.”

Developers can execute new code or cache new types of data in GridGain without any deployment or any restarting of a grid.

“You can have a live grid/cloud installation, dynamically create a new Java or Scala class and immediately put it into a data grid, and start querying it,” Ivanov explained.

Finally, GridGain enables developers to launch multiple GridGain nodes in the same JVM.

“This is one of the greatest time-savers today in distributed computing,” said Ivanov. “In fact, you can launch an entire grid or cloud right in the same JVM, put breakpoints onto multiple nodes and step through the entire cloud, tracing your distributed logic in your debugger — and never leaving the IDE.”

 

Click Once Deployment Issue

March 9, 2011 § Leave a comment

There was a problem that I was unable to launch an application that was published using ClickOnce. And the log file that the error message provided making finding the issue very easy. The log file contained the following error:

Following errors were detected during this operation.
* [6/7/2010 10:54:17 AM] System.Deployment.Application.DeploymentException (Subscription)
– Unable to install this application because an application with the same identity

is already installed. To install this application, either modify the manifest version
for this application or uninstall the preexisting application.
– Source: System.Deployment

Solution : You need to Clean Online App Cache

There 2 ways

1) Developer : Where you need simple command line tool mage.exe which is found in /Program Files/Microsoft Sdks/Windows/v7.0A/bin. Calling the tool like this mage -cc cleared the cache.

2) However, on a machine for non developers, this was not an option, as they don’t have the Sdks on their machines. So, an alternative.

go Cmd run this command

rundll32 dfshim CleanOnlineAppCache

Problem Solved

Hope this useful…. 🙂

Android Honeycomb’s music app extracted, brings cloud sync and streaming to phones

March 9, 2011 § Leave a comment

Android Honeycomb’s music app extracted, brings cloud sync and streaming to phones

Those who are familiar with Android Honeycomb might have already come across its music player’scloud syncing feature, though previous attempts to port said app to phones hadn’t been successful. Whatever it was that kept crashing the app back then, it seems to have fixed itself — after xda-developersmember WhiteWidows slapped the leaked app onto his rooted EVO 4G, the phone started to automagically sync his tunes to his Google account. The modder then swapped in an empty SD card, but he was still able to stream music straight from the cloud after checking the “Stream music” option in the app. Pretty neat, eh? That said, we do wonder if Google will be able to handle the exabytes worth of high-quality Justin Bieber and Spice Girl tracks.

 

Where Am I?

You are currently viewing the archives for March, 2011 at Naik Vinay.