Its very simple, free and SEO Friendly. Submit Now....
Tuesday, December 30, 2008
CodeSnip: How to Update a Table by Selecting Records from another Table
Source Click Here.
Tip #39: Did you know. How to cancel a remote web operation in Visual Studio 2008?
In VS2005, when you connected to an FTP or FrontPage server, the IDE would not let you intervene to cancel the operation. In VS2008, during most any operation that has you connecting to a remote source via FTP or FrontPage Server Extensions, you can hit the "Esc" key, and the IDE should cancel or give you the option to cancel the impending operation. This can be useful if you experience network latency problems with whatever server you're trying to connect to, or realize you need to cancel in the midst of a more costly operation. Some simple examples of situations when you can hit escape are: doing any sort of file operation in a remote web site, such as add/delete/renaming files, opening a large web site, and when using Publish Web to publish a web to a remote location.
You'll notice that you get the following message on the status bar when doing an operation in a remote web:
And you'll get the following dialog if you hit esc during a publish:
John Dundon
SDET | Visual Web Developer
Source Click Here.
I Love To Code
I was reading Jeff Atwood's latest post, Programming: Love it or Leave it when I came across this part, emphasis mine.
Joel implied that good programmers love programming so much they'd do it for no pay at all. I won't go quite that far, but I will note that the best programmers I've known have all had a lifelong passion for what they do. There's no way a minor economic blip would ever convince them they should do anything else. No way. No how.
Unlike Jeff, I will go that far. I love to code, and I do it for free all the time.
I don't think Joel meant to imply that programmers would continue to write code for their current employers for free in lieu of any pay. What I think he meant was that programmers who love to code will code for fun as well as profit. They'll write code outside of their paying jobs.
For example, I took the entire week off last week and spent lots of time with my family, which was wonderful (cue gratuitous picture of kid)! I trained my son in Ninja acrobatics.
I got my brother completely hooked on Desktop Tower Defense.
And tried to figure out what sort of mischief my son was involved in, as that face is as guilty as sin.
However, along with all that family fun, I spent nearly every minute of downtime hacking on Subtext. I went on a huge refactoring binge cleaning up stale code, separating concerns left and right, and replacing the old method of matching requests with ASP.NET Routing.
And it was huge fun!
And I'm not alone. I noticed several streams on Twitter of folks having fun writing code, such as Glenn Block sharing his learning in the open experiences, among others.
Developers I've worked with who really love to code, tend to do it for fun, as well as for work. Personally, I don't think it's unhealthy as long as it's not the only thing you do for fun. And I'm not suggesting that if you don't do it for fun, you don't love to code. Some people work so much, they don't have time to do it for fun, but would code for fun if they had copious free time.
As for me, I'll say it again, I <3 to code.
Source Click Here.
Interesting use of XML Literals as a View Engine
Dmitry, who's the PUM for ASP.NET, recently wrote a blog post about an interesting approach he took using VB.NET XML Literals as a view engine for ASP.NET MVC.
Now before you VB haters dismiss this blog post and leave, bear with me for just a second. Dmitry and I had a conversation one day and he noted that there are a lot of similarities between our view engine hierarchy and and normal class hierarchies.
For example, a master page is not unlike a base class. Content placeholders within a master page are similar to abstract methods. Content placeholders with default content are like virtual methods. And so on.
So he thought it would be interesting to have a class be a view rather than a template file, and put together this VB demo. One thing he left out is what the view class actually looks like in Visual Studio, which I think is kinda cool (click on image for larger view).
Notice that this looks pretty similar to what you get in the default Index.aspx view. One advantage of this approach is that you're always using VB rather than switching over to writing markup. So if you forget to close a tag, for example, you get immediate compilation errors.
Another advantage is that your "view" is now compiled into the same assembly as the rest of your code. Of course, this could also be a disadvantage depending how you look at it.
Source Click Here.
Monday, December 29, 2008
CodeSnip: How to Update Table by Selecting Records from another Table
Source Click Here.
Tip #37: Did you know.How to organize usings?
Overtime C# source code files may have unnecessary & unorganized using directives. Visual Studio IDE organize using options can help you to unclutter the source code.
To organize the C# code right click anywhere inside the code editor, select Organize usings.
- Select Remove Unused Usings to remove any using directives that are not used in the source code (this may remove some required using directives if the source code doesn't build)
- Select Sort Usings to organize alphabetically the using directives (by default directives that begin with System comes before other using directives)
- Select remove and Sort to perform both of the above operations
Thanks,
Deepak Verma
SDET | Visual Web Developer
Source Click Here.
Tip #38: Did you know... How to use Failed Request Tracing to trace Rewrite Rules?
IIS7.0 Failed Request Tracing (FRT) is a powerful troubleshooting tool for request-processing failures. More details regarding FRT and how to enable it can be be found here.
Once the failed request tracing is enabled for your site, do the following to trace rewrite rules:
After the FRT rule is created, the log will start getting generated in %SystemDrive%\inetpub\Logs\FaileReqLogFiles\. You can open this log by using Internet Explorer, and it will be rendered as an HTML document that can be easily browsed.
PS: If the Failed Request Tracing was installed after URL rewrite module, the "Rewrite" area in Trace Providers may not be available. If you do not see "Rewrite" area listed there, go to Add/Remove programs and then run URL rewrite module installer in repair mode.
For more details on this, read this walkthrough.
Don Raman
SDET, IIS Team
Source Click Here.
Saturday, December 27, 2008
Apply ASP.NET Authentication and Authorization Rules to Static Content with IIS 7.0's Integrated Pipeline Feature
Many ASP.NET applications that support user accounts use forms-based authentication and URL authorization. Forms-based authentication is a mechanism by which users can log into the site by entering their credentials - typically a username and password - into textboxes in a login page. Once validated, the server returns an authentication ticket cookie that identifies the request; this cookie is sent back on subsequent visits to the site, which keeps the user "logged on" for the lifetime of the cookie or until the authentication ticket expires. URL authorization is a mechanism by which authorization rules can be defined on a URL-by-URL or folder-by-folder basis. In short, with URL authorization you can instruct the application to deny access to a particular folder to anonymous users, or prohibit access to a particular URL to all users except those in the Admin role.
Because the forms-based authentication and URL authorization features are part of ASP.NET, the ASP.NET runtime must be consulted in order for these features to be employed. When developing an application using Visual Studio and the ASP.NET Development Server, all requests are handed off to the ASP.NET runtime. Consequently, the authentication and authorization logic applies to both ASP.NET-specific content like ASP.NET pages and Web Services, as well as static content like images, PDFs, and ZIP files. Things are a bit different with IIS, Microsoft's production-grade web server software. By default, IIS handles all static content itself, only invoking the ASP.NET runtime when an ASP.NET resource is requested. As a result, those URL authorization rules you apply to static content are ignored when hosting your site in a production environment!
The good news is that starting with IIS 7.0 Microsoft has introduced the integrated pipeline. In a nutshell, with the integrated pipeline you can instruct IIS to work with the ASP.NET runtime during the processing of all requests, regardless of whether the request is for an ASP.NET-specific resource. This article shows how to use the integrated pipeline feature to apply ASP.NET forms-based authentication and URL authorization rules to static content. Read on to learn more!
Read More >
Source Click Here.
My 10 common mistakes in ASP.NET
At work I’ve come to realize that I don’t always produce code that just work. I make mistakes and often forget to test properly before I sign off a task. So I talked to our test lead and asked him to compile a list of the most common issues he finds when testing my work. I then printed out the list and hung it on the wall next to my desk as a checklist to go through whenever I think a task is done.
He could actually only produce 7 common issues, but I put in three more that relates to code quality. Since I’m an ASP.NET front-end developer, the list focuses on UI issues seen through the lens of a tester. The list is not prioritized.
I hereby declare that all features, tasks and tweaks…
Works correctly in IE6, IE7 and Firefox
The test lead found that cross-browser issues surfaced from time to time. Most often it was really minor issues like positioning of elements or general IE6 quirks. The reason why this rule isn’t called “Works correctly across browsers” but instead focuses on IE and Firefox is simple. If you can get your page to work in IE6, IE7 and Firefox, then it almost always works in Safari and Opera as well. Second, those browsers cover about 98% of our visitors. Third, if it was called “Works correctly across browsers” it might be easier to ignore when going through the list.
Is XSS secure
Make sure that all input fields are handled correctly so no HTML or JavaScript entered by a user can mess up the page.
Long text doesn't break design
My limited brain tells me that a name is never longer than approx. 50 characters. I still believe it, but what happens if you put in a 300 character name? In many cases this would break the UI. Either limit the length of text a user can submit or tweak the design to take long text into account.
Localize everything
When I start working on a new feature for the website, I hard code all text because it might change during development. When the feature is approved by the product team then I localize the text. Since this is on the list, I sometimes forget to localize ALL the text. I will still do hard coding of text, but this checklist will help me remember to localize before signing off.
The enter-key works as expected
When using ASP.NET webforms, a form element is probably located at the master page so all pages resides inside that form. That often leads to strange behaviours of the enter-key. Remember to set default buttons either from code-behind or on the Panel webcontrol.
The code is reusable when possible
This is a general coding law and in ASP.NET the same rules apply. Separate elements in user- and server controls and make them small and specialized so they can be used elsewhere. Read more about reusable ASP.NET.
Unit tests written when possible
If you’re not using the ASP.NET MVC framework, unit testing your website is not easy. However, if you pull out as much of the code-behind logic into components that you can put in a library, then you can unit test. Instead of using .ashx files for HttpHandlers, put them in a separate library. Use server controls instead of user controls when you can.
The code is well commented
This goes without saying. Comment and document your code so other developers can easily pick up where you left.
Is peer verified before going into testing
Before a feature is signed off and sent to test, we do peer verification. Peer verification is when one of your colleagues performs sanity checking on your feature or just tries to break it. This let you find issues early on and make the life easier for the testers. When we are really busy, I often forget to ask for peer verification and that shows.
Is signed off by product owner
At work we have a product team that always have the ownership of a feature. We developers also have ownership of features, but that is from an implementation level. During a busy day when I do several different tasks, I sometimes forget to get the product owner to sign off my work. If it isn’t signed off, then you’re simply not done yet and I sometimes have to finish a task several days after I was “done”. This is annoying and makes it harder to meet deadlines. I must say that this is probably the single most important issue, but it is also the one that I almost never forget for that very reason.
Time will tell if this list will raise the quality of my work. I’m sure that as long as I don’t ignore the list, it will. Are any issues missing?
Source Click Here.
Thursday's Silverlight presentation
This Thursday, October 23rd, the Copenhagen .NET user group is throwing one kick-ass presentation for anyone interested. The theme is Silverlight 2.0 experiences for .NET developers and it’s going to blow you away. It’s not drag ‘n drop demos or a tutorial, but about the possibilities the new Silverlight version brings to ordinary .NET developers, presented by one of the most experienced Silverlight guys in Denmark.
The reason I’m looking forward to this talk so much is I’ve never really played that much with Silverlight and I want to see if the new version can be used for something cool in BlogEngine.NET and at ZYB. I’ve only seen one presentation of Silverlight back in the day and that was a bit boring with all the dragging and dropping of controls in Visual Studio. This will not be a presentation like that.
So, if you’re interested in coming along for the ride, be at Microsoft in Hellerup this Thursday at 4pm. It’s free and arranged by the Copenhagen .NET user group and people from the .NET community are going to be there. Check out www.cnug.dk for more info and remember to join the Facebook group.
Source Click Here.
Track your visitors using an HttpModule
I’ve been thinking about how to solve a very simple problem on a website: visitor behaviour tracking. In a sense it is what Google Analytics does, but there are problems with conventional JavaScript based trackers.
They are good at tracking page views, but very bad at tracking actions or behaviour around a website. Some products like Headlight are actually pretty good at tracking actions such as button clicks etc, but at the level I’m interested in tracking, I would have to add JavaScript all over my page. I don’t want to do that.
Also, there are some very good server-side logging products like log4net out there. The problem is that they are not really meant for tracking website behaviour with URLs, user agents and other important metadata.
What I want is a combination of the traditional JavaScript- and server-side methods. So, I’ve played around with a custom HttpModule that logs all page views and custom actions. You add the custom actions yourself by calling VistorLog.AddAction("message", "type"). That way you have page views and actions in a chronologically correct order.
A neat thing is that all page views and actions are kept in session and only when the session expires does it write to the database. That way it can do a batch insert which is much faster than hitting the database constantly. Another neat thing is that the HttpModule is only 100 lines of code.
The code
Basically, three things are going on. The session starts and we add a Visit object to it.
void session_Start(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
Visit visit = new Visit();
visit.UserAgent = context.Request.UserAgent;
visit.IpAddress = context.Request.UserHostAddress;
context.Session.Add("visit", visit);
}
Then every page view is registered after an .aspx page is served.
void context_PostRequestHandlerExecute(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (context.CurrentHandler is Page)
{
Visit visit = context.Session["visit"] as Visit;
if (visit != null)
{
Action action = new Action();
action.Url = context.Request.Url;
action.Type = "pageview";
visit.Action.Add(action);
}
}
}
Then the session ends and we need to store the visitor log.
void session_End(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
Visit visit = context.Session["visit"] as Visit;
if (visit != null)
{
// Log the Visit object to a database
}
}
Implementation
When you have registered the HttpModule in the web.config, then it starts collection page views in the session. To store them in a database you must add your own code to the session_End method of the module. Now you are also able to store actions just by calling a static method on the VisitorLog module:
VisitorLog.AddAction("Profile picture deleted", "deletion");
Keep in mind that this code is just me playing around in my sandbox. It has never been in a production environment.
Download
Source Click Here.
Search for people using SHA1 hashing
About 10 years ago, it was actually possible to look people up by their e-mail address online. You could also find a persons e-mail by searching for his or her name. Back then there where a lot of e-mail directories that acted like the yellow pages but for e-mail addresses. Very handy, but when spam became a problem, no one was willing to publicise their e-mail address and the e-mail search quickly died out.
Years passed and nobody thinks seriously about searching for people by their e-mail address anymore. It was tossed out of our toolbox – abandoned and forgotten.
Then a few years ago, something wonderful started to happen with the web. Community sites, forums, blog platforms etc. stated publishing FOAF and SIOC documents. Both documents contain e-mail addresses of people but not in the traditional sense. They publish SHA1 hashed e-mail addresses.
You can hash an e-mail using the SHA1 algorithm but you can never reverse it. That means the hashed e-mail addresses are secured from spam bots, but they are also left public for all of us to search for. All you need to do is to hash an e-mail address and do a Google search with the hashed value. Try searching for my hashed e-mail address on Google or go hash your own e-mail.
Here is a quick way of using SHA1 algorithm to hash any string value in C#.
public static string CalculateSHA1(string value)
{
value = value.ToLowerInvariant().Trim();
return FormsAuthentication.HashPasswordForStoringInConfigFile(value, "sha1").ToLowerInvariant();
}
The limitations of the SHA1 e-mail search is that you can only find people that have an online profile or blog, participate in online discussions or comments on blogs. The number of searchable people will rise as more and more sites start supporting FOAF and SIOC.
Source Click Here.
Simple JavaScript event model
At work we are using a lot of JavaScript for all of our user controls and other ASP.NET components. I’m guessing that so are you. Our solution is to add a .js file per each user control and then load them on the page dynamically as explained here. That is a great way to componentize your web application.
Bad behavior
The problem is when an action on one user control’s JavaScript effects elements on other user controls. An example could be the page header where it says Signed in as Joe. When you are on the update profile page and change your name from Joe to Johnny using AJAX, then you don’t update the header element. If you do, you probably reference the DOM element from your profile update script directly. This is bad since the header and profile are located in two different user controls and thus haven’t got a clue about the existence of each other. Why should the JavaScript treat them differently?
Good behavior
What you really want to do is to use an event model. Then it works like so:
The user changes his name to Johnny and the AJAX function in JavaScript triggers an event called profileNameUpdated and passes the new name along as a parameter. The page header have already told the event model to subscribe to the profileNameUpdated event and so it now catches the event triggered by the profile. It reads the new name and updates its own DOM element.
The code
Amazingly, the JavaScript code for this is less than 1KB and works on all websites, platforms and browsers. This is what it looks like.
// The constructor of the eventFramework
function eventFramework()
{
this.handlers = [];
}
// Triggers the event specified by the name and passes the eventArgs to listeners
eventFramework.prototype.trigger = function(name, eventArgs)
{
for(var i = 0; i < this.handlers.length; i++)
{
if(this.handlers[i].eventName == name)
this.handlers[i].eventHandler.call(this, eventArgs);
}
}
// Adds a listener/subscriber to the event specified by the 'name' parameter
eventFramework.prototype.addListener = function(name, handler)
{
if(typeof(name) != 'string' || typeof(handler) != 'function')
{
throw new SyntaxError("Invalid parameters when creating listener with the following arguments: 'Name': " + name + ", 'Handler': " + handler);
}
this.handlers.push({ "eventName" : name, "eventHandler" : handler });
}
// Initializes the eventFramework and makes it available globally
var events = new eventFramework();
Implementation
Download the .js file below and add it to your site. It should be the first JavaScript to be included in the <head> element of your pages.
When the script is included, it is now possible to start triggering and listening to events. To trigger an event, simple write this:
events.trigger('profileNameUpdated', 'Johnny');
You can also pass objects or JSON as a parameter like so:
events.trigger('profileNameUpdated', {'name':'Johnny', 'oldName':'Joe'});
To subscribe or listen to these events, you simply add the following to any user control or JavaScript file:
events.addListener('profileNameUpdated', eventListener);
function eventListener(eventArgs)
{
alert(eventArgs);
}
The eventArgs parameter will contain whatever was passed along by the trigger.
Download
Source Click Here.
Reverse GEO lookup in C#
Google’s maps API now supports reversed GEO lookup which allows you to find an address based on geo coordinates. All you need is a latitude, a longitude and this handy method:
private const string endPoint = "http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=true&key=YOURKEY";
private static string GetAddress(double latitude, double longitude)
{
string lat = latitude.ToString(CultureInfo.InvariantCulture);
string lon = longitude.ToString(CultureInfo.InvariantCulture);
string url = string.Format(endPoint, lat, lon);
using (WebClient client = new WebClient())
{
string xml = client.DownloadString(url);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode node = doc.ChildNodes[1].FirstChild.ChildNodes[2].ChildNodes[0];
return node.InnerText;
}
}
It returns the address as a string.
Source Click Here.
I'm not dead yet
I’ve been a bit inactive for the last few months. Here’s an update.
New laptop
My old laptop was 2½ years old so I thought it was about time to upgrade to a newer machine. I’ve been happy with Dell, so I got a new XPS M1530 laptop. Here is what I customized it with:
- 4GB memory
- 64GB solid state HDD
- HDMI out
- Blue-ray drive
- Wireless N (really fast)
It results in this Windows Experience Index.
BlogEngine.NET
It’s been awhile since the team and I have given any information about the next version of BlogEngine.NET. Truth be told, we haven’t had much time to work on it since the last release back in August. Many bugs have been fixed and more will be during the next weeks. The roadmap has been conservatively updated. We might change it to add more things to it.
Since I got my new laptop I’ve updated BlogEngine.NET to run in both IIS 6 + 7 out-of-the-box. The solution has also been updated to Visual Studio 2008. One of the major things that I will focus on in BlogEngine.NEXT is refactoring and cleaning of the code. We are also working with the Windows Live Writer team to implement support for the newest version that is currently in beta.
Another thing I really want to add is life streaming. The ability to have Facebook updates, Twitter tweets etc. to be listed alongside blog posts in a chronological order. This will bridge the gap between blogging and microblogging in a nice way I think. I’ll soon have something to show here on this blog.
SemanticEngine.NET
Since I published the bits on CodePlex a few months ago, I haven’t had time to do a follow up. I still haven’t time. That’s why I asked for people to help out, but so far no one have volunteered. I’ll probably do some polishing and make an official release around Christmas. Still, if you have the time to help out please drop me a note.
Blogging
I’ve been so busy that I haven’t had the time to blog – or the energy. Time is only one part of blogging. The other part is having something interesting to write about. Normally I get ideas from code that I experiment with or play with at home or at work. Lately, I’ve been so swamped at work that I haven’t had the time to play around with code as I normally do. That is changing now since we have hired some new developers to balance the work load.
I’ve just upgraded to Visual Studio 2008 (about bloody time!) so I’ll have a lot of experimenting to do and will of course blog about some of that.
Source Click Here.
W3C Geolocation support in Firefox
The W3C has created a standard for location sharing called Geolocation. It allows any person to share her location with any website at the click of a button. Imagine the possibilities with this.
Here is a scenario:
You’ve arrived in a new city, a new continent, a new coffee shop. You don’t really know where you are, and are looking for a good place to eat. You pull out your laptop, fire up Firefox, and go to your favorite review site. It automatically deduces your location, and serves up some delicious suggestions a couple blocks away and plots directions there.
Firefox 3.1 will have this build in, but until then we can use a Firefox add-on called Geode. Basically, it uses your Wi-Fi network to find your exact location and then passes it to a JavaScript callback method on your website. Already now, services like Pownce, Fire Eagle and ZYB uses this to improve the user experience of their services.
Here is a screenshot of what it looks like when Geode ask for a location:
Getting started using Geode
You should start by downloading the Geode add-on for Firefox and make sure your Wi-Fi is turned on. Then fire up your HTML editor and add this JavaScript to one of your pages:
function geodeAsk()
{
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(geoFound, geoNotFound);
}
function geoFound(pos)
{
var lat = pos.latitude;
var lon = pos.longitude;
alert(lat + ', ' + lon);
}
function geoNotFound()
{
alert('You must be on a wifi network for us to determine your location');
}
// Ask the browser for its location
geodeAsk();
Open the page in Firefox. Geode will now ask you if you want to share your location with the page. It’s that simple. Geode then sends the latitude and longitude to the JavaScript callback method and you can now do whatever you want with it. If you want to retrieve the address based on the location, then you need to do a simple reverse GEO lookup.
Source Click Here.
Christmas geek dinner
It’s that time of year again where you just want a fun evening in the company of your friends and some nice food. Unfortunately, your friends are busy so all you have left is your fellow .NET developer geeks and a brewery.
That’s right folks; it’s time for the first Copenhagen geek dinner Christmas edition. It’s Thursday, December 18th at 7pm at Brewpub in the center of the city. As usual, ZYB will pay for all the beer and as a special Christmas present, Microsoft will sponsor the food. You might have to pay a small amount depending on how many we are going to be, but it will not ruin your budget.
There is only room for 20 people, so sign up right now.
Source Click Here.
BlogEngine.NET Christmas update
Some exiting things have been going on with BlogEngine.NET lately.
Theme-pack
13 new and very slick looking themes have been cleaned up, bundled and released on CodePlex. Since we decided not to include more than a couple of themes with BlogEngine.NET 1.4 we knew a theme-pack was necessary. Thanks to Janko for gathering the themes and cleaning them up. Download the theme-pack.
.NET 3.5 and Visual Studio 2008
The current version 1.4.5 is the last official version on .NET 2.0 and in Visual Studio 2005. Right now the team is already working in Visual Studio 2008 and will upgrade to .NET 3.5 during Christmas. A lot of people asked for this, so now we are giving it to you.
Windows Live Writer 2009
Al Nyveldt has been in contact with the Windows Live Writer team to ensure that the BlogEngine.NET will support the new features of WLW 2009 and vica versa. Only BlogEngine.NET and Wordpress has been given special attention by the WLW team which we are very proud about. Read more on Al’s blog.
TinyMCE upgrade
For those of us who don’t use Windows Live Writer, but prefer the online HTML editor, there is good news. We are upgrading the TinyMCE implementation to the newest version and it should work much smoother. It’s not only prettier, it’s also better. Hopefully, this will happen over Christmas as well.
Source Click Here.
Tuesday, December 23, 2008
Two worlds of Dynamic Data customization: generic vs schema specific
There are many ways to customize a ASP.NET Dynamic Data site, which can sometimes be a bit overwhelming to newcomers. Before deciding what customization makes sense for you, it is important to understand the two major buckets that they fall into:
- Generic customization: things that apply generically to any table/column.
- Schema specific customization: things that apply to specific tables and/or columns.
They can both very useful depending on your scenario, but it is important to understand how they are different in order to make the right choices. The rule of thumb is that you want to stay in the world of generic customization whenever possible, and only use the schema specific customization when you have to. Doing this will increase reusability and decrease redundancy.
We'll now look at each in more details.
Generic customization
Generic customization includes everything that you can do without any knowledge of the database schema that it will be applied to. That is, it's the type of things that you can write once and potentially use without changes for any number of projects. It lets you achieve a consistent and uniform behavior across an arbitrarily large schema, without needing to do any additional work every time you add or modify a table.
Here are some key types of generic customization:
Page Template customization
Under the ~/DynamicData/PageTemplates folder, you'll find some default Page Templates like List.aspx and Edit.aspx. If you look at them, you won't find any references to a specific table/column. Instead, they define the general layout and look-and-feel of your pages in an agnostic way.
e.g. if you look at List.aspx, you'll see a GridView and a LinqDataSource (or EntityDataSource with Entity Framwork), but the data source doesn't have any ContextTypeName/TableName attributes, and the GridView doesn't define a column set. Instead, all of that gets set dynamically at runtime based on what table is being accessed.
You can easily make changes to these Page Templates, such as modifying the layout, adding some new controls or adding logic to the code behind. It's a 'normal' aspx page, so you can treat is as such, but you should never add anything to it that is specific to your schema. When you feel the need to do this, you need to instead create a Custom Page (see below).
Field Template customization
Under the ~/DynamicData/FieldTemplates folder, you'll find a whole bunch of field templates, which are used to handle one piece of data of a given type. e.g. DateTime_Edit.ascx handles DataTime columns when they're being edited.
As is the case for Page Templates, Field Templates should always be schema agnostic. That is, you don't write a field template that's only meant to handle a specific column of a specific table. Instead, you write a field template that can handle all columns of a certain type.
For example, in this post I describe a field template that can handle Many To Many relationships. It will work for any such relationship in any schema (though it is Entity Framework specific).
Field Generator customization
Under Page Template above, I mentioned that the GridView didn't specify a column set. Instead, the way it works is that there is something called a Field Generator which comes up with the set of columns to use for the current table.
The idea is that the Field Generator can look at the full column set for a table, and use an arbitrary set of rules to decide which one to include, and in what order to include them. e.g. it can choose to look at custom model attributes to decide what to show.
Steve Naughton has a great post on writing a custom field generator, so I encourage you to read that for more info on that topic.
Schema specific customization
Any time you make a customization that is specific to a certain table or column, you are doing schema specific customization. Here are the main type of things you can do:
Custom Pages
When you want to have a very specific look for a certain page (e.g. for the Edit page for your Product table), a generic Page Template will no longer do the job. At that point, you want to create a Custom Page. Those live under ~/DynamicData/CustomPages/[TableName]. e.g. to have a custom page to edit products, you would create a ~/DynamicData/CustomPages/Products/Edit.aspx.
You can start out with the custom page being an identical copy of the page template, but then you can start making all kind of schema specific changes. For instance, you could define a custom <Fields> collection in the DetailsView, at which point you no longer rely on the Field Generator (discussed below). Taking this one step further, you can switch from a DetailsView into a FormView (or ListView), giving you full control over the layout of the fields.
Model annotations
Another very important type of schema specific customization is model annotation. This is what most introductory Dynamic Data demos show, where you add CLR attributes to the partial class of your entity classes.
For instance, you can add a [Range(0, 100)] attribute to an integer field to specify that it should only take values between 0 and 100. Dynamic Data comes with a number of built-in annotation attributes, and you can easily build your own to add news ways to annotate your model.
The general idea here is that it is cleaner to add knowledge at the model level than to do it in your UI layer. Anything that you can add to describe your data in more details is a good fit for model annotations.
Conclusion
All of the different types of customization that I describe above have useful scenarios that call for them. My suggestion is to get a good understanding of what makes some of them Generic while others are Schema Specific, in order to make an informed decision on the best one to use for your scenarios.
Source Click Here.
Tip #36: Did you know... How to manage pilot or beta program for your site using Application Request Routing in IIS7.0?
Won't it be cool if you can target and route appropriate users of your site to your pilot/beta/new looking site based on user's profile. This may help you in managing select users who have previously signed for pilot program and redirect them to new looking web site and gather feedback. This is a very typical situation when your web site is evolving or going a major change. IIS7.0 Application Request Routing (ARR) module helps you achieve this. The other situation where this can help is to limit and manage the amount of traffic that is routed to pilot site. There can be numerous other scenarios like ones mentioned where ARR can assist but the focus of the tip will be to learn how to get this done through ARR. You can apply it to other related scenario too.
Let's say for example we would like to redirect all users who have .NET Framework 3.5 installed and are using the browser Internet Explorer to the pilot site. For achieving this using ARR, follow the below steps:
- Launch IIS Manager.
- Create a server farm named "pilotSiteServers" using this walkthrough. This server farm will represent the pilot/beta environment.
- Create another server farm named "productionSiteServers" as above. This server farm will represent the production environment.
- Select the server farm "pilotSiteServers". The following icons will be shown:
- Double click on "Routing Rules".
- Since this scenario involves multiple server farms with conditional matching of HTTP request headers, we will use URL Rewrite UI which exposes additional options. Click on "URL Rewrite" under "Advanced Routing".
- You will note that two rules are already there.
- These rules has to be changed. The order of rule is important. I will explain it in a while. For now, if ARR_productionSiteServers_loadbalance is above ARR_pilotSiteServers_loadbalance, change the order of the rules by using Move Up or Move Down after selecting the rule.
- Select ARR_pilotSiteServers_loadbalance, and then click Edit... in the Actions pane.
- We need to define conditions now. Remember our aim is to "redirect all users who have .NET Framework 3.5 installed and using the browser Internet Explorer to the pilot site"
- Click Add Conditions, and then click Add....
- Enter {HTTP_USER_AGENT} as Condition input and *MSIE* as Pattern. This condition checks to see if the client is using IE.
- Add another condition to check for the .NET version. Click Add..., and then enter {HTTP_USER_AGENT} as Condition input and *.NET CLR 3.5* as Pattern.
- Finally, uncheck the "Stop processing of subsequent rules" checkbox, and then click "Apply" to save the changes.
- Now let me answer why the order of rules mattered. This is because URL rewrite processes the rules in order when "Stop processing of subsequent rules" is unselected. So in this case the first rule ARR_pilotSiteServers_loadbalance will be considered first. This rule tries to match whether the client is using IE and has .NET Framework 3.5 installed. If so, the requests are forwarded to the pilotSiteServers server farm. Since the "Stop processing of subsequent rules" checkbox is unchecked, it will also process the second rule. This means the rule ARR_productionSiteServers_loadbalance will also get processed. This will route all other request to productionSiteServers server farm.
That's it, we are done. For details regarding pre-requisite and command line equivalent of the above URL Rewrite rules look here.
Don Raman
SDET, IIS Team
Source Click Here.
StickyNotes for Visual Studio
Pablo Galiano, one of my friends and colleagues from my patterns & practices days, has just released a very cool extension for Visual Studio 2008 called StickyNotes. As the name suggests, it allows you to attach sticky notes to your code, with a lot more richness and less intrusiveness than regular code comments. You can also choose between personal notes (visible only to the person who created it) and team notes (visible to the entire team).
Unfortunately my team is still using Visual Studio 2005 (we started before VS2008 was released and haven't had time to upgrade yet!), so I haven't been able to use this on my project yet, but I have played around with it and it looks very nice. And while this tool isn't free, at $US9.99 (about what I pay for lunch) it's practically free. Give it a try!
Source Click Here.
Monday, December 22, 2008
Designing Crystal Reports for Users
Source Click Here.
MVC Controllers and Forms Authentication
Source Click Here.
Fluent Animations in Silverlight
Source Click Here.
Two New Videos on ASP.NET
Source Click Here.
Designing Crystal Reports for Users
Source Click Here.
MVC Controllers and Forms Authentication
Source Click Here.
Fluent Animations in Silverlight
Source Click Here.
Two New Videos on ASP.NET
Source Click Here.
Announcing the ASP.NET MVC Design Gallery
Source Click Here.
Four Helpful Custom Base Page Features
One of the first things I do when creating a new ASP.NET web application is create a custom base page class and add a handful of useful methods I've used in other projects. My latest article on DotNetSlackers.com shares four helpful features that you can add to your base page class:
- Display a JavaScript Alert
- Recursively Search the Control Hierarchy
- Record Page Execution Times
- Set the Page's Title
Read more at: Four Helpful Features to Add to Your Base Page Class.
Source Click Here.
Time for a new useless blog subtitle
For the longest time, I had set my blog subtitle to "Dynamic Data and other ASP.NET topics", which some might argue would not have won any originality contests. On the bright side, it was a fine match for my equally original blog title: "David Ebbo's blog".
So I went on a quest for a new subtitle as part of my 2009 New Year resolutions (ok, it's the only one so far). As for changing the Title itself, I'll save that for New Year 2010.
My first stop in this memorable journey resulted in the use of the extremely witty word 'Ebblog'. While undeniably cool, I somehow decided to pass on it. The future will probably not tell whether it was a good move.
Still looking to capitalize on my uniquely catchy last name, I came up with the soon-to-be memorable phrase: "The Ebb and Flow of ASP.NET".
Some online dictionary defines it as "the continually changing character of something". I guess that's not so bad.
And then there is Wikipedia, which defines it as "a form of hydroponics that is known for its simplicity, reliability of operation". Of course, I don't have a clue what hydroponics means (and neither do you), but the rest sounds pretty good.
So that's that. Thanks for letting me waste your time. By now, the momentum is clearly building for renaming the blog Title itself, but you'll just have to wait another year for this thriller to unfold.
Source Click Here.
A Little Holiday Love From The ASP.NET MVC Team
A while ago ScottGu mentioned in his blog that we would try and have an ASP.NET MVC Release Candidate by the end of this year. My team worked very hard at it, but due to various unforeseeable circumstances, I'm afraid that's not gonna happen. Heck, I couldn't even get into the office yesterday because the massive dumping of snow. I hope to get in today a little later since I'm taking next week off to be with my family coming in from Alaska.
But do not fret, we'll have something early next year to release. In the meanwhile, we gave some rough bits to Scott Guthrie to play with and he did not disappoint yet again with a a great detailed post on some upcoming new features both in the runtime and in tooling.
Often, it's the little touches that get me excited, and I want to call one of those out, Views without Code-Behind. This was always possible, of course, but due to some incredible hacking down in the plumbings of ASP.NET , David Ebbo with some assistance from Eilon Lipton, figured out how to get it to work with generic types using your language specific syntax for generic types. If you recall, previously it required using that complex CLR Syntax within the Inherits attribute.
Keep in mind that they had to do this without touching the core ASP.NET bits since ASP.NET MVC is a bin-deployable out-of-band release. David provided some hints on how they did this within his blog in these two posts: ProcessGeneratedCode
: A hidden gem for Control Builder writers and Creating a ControlBuilder for the page itself.
ASP.NET MVC Design Gallery
In the meanwhile, Stephen Walther has been busy putting together a fun new section of the ASP.NET MVC website called the ASP.NET MVC Design Gallery.
In one of my talks about ASP.NET MVC, I mentioned a site that went live with our default drab blue project template (the site has since redesigned its look entirely). The Design Gallery provides a place for the community to upload alternative designs for our default template.
Happy Holidays
Again, I apologize that we don't have updated bits for you to play with, but we'll have something next year! In the meanwhile, as the end of this year winds down, I hope it was a good one for you. It certainly was a good one for me. Enjoy your holidays, have a Merry Christmas, Hannukah, Kwanza, Winter Solstice, Over Consumption Day, whatever it is you celebrate or don't celebrate. ;)
Source Click Here.
ASP.NET MVC Design Gallery and Upcoming View Improvements with the ASP.NET MVC Release Candidate
Today we launched a new ASP.NET MVC Design Gallery on the www.asp.net site. The design gallery hosts free HTML design templates that you can download and easily use with your ASP.NET MVC applications. Included with each design template is a Site.master file, a CSS stylesheet, and optionally a set of images, partials, and helper methods that support them.
The gallery allows you to preview each of the designs online, as well as download a .zip version of them that you can extract and integrate into your site. The gallery allows anyone to create and submit new designs under the creative commons license. Visitors to the gallery can vote to provide feedback on them (thumbs up/thumbs down). The most popular designs show up at the top of the gallery.
We think this will provide a useful way for developers to more easily create attractive, standards compliant, sites. It will also hopefully encourage folks to create and share designs that can be easily re-used by others.
Upcoming View Improvements with the Release Candidate
While on the topic of UI, I thought I'd also share a few details about some of the View-related improvements that are coming with the new ASP.NET MVC Release Candidate (RC) build that will be shipping shortly. In addition to bug fixes, the release candidate incorporates a number of view-specific feature additions and community suggestions.
Views without Code-Behind Files
Based on feedback from a lot of people, we've decided to make a change so that MVC view files by default do not have code-behind files. This change helps to reinforce the purpose of views in a MVC world (which are intended to be purely about rendering and to not contain any non-rendering related code), and for most people eliminates unused files in the project:
With the ASP.NET MVC Beta, developers could eliminate the code-behind file by using the CLR syntax for generic types in a view's inherits attribute, but that CLR syntax is (to put it mildly) pretty undiscoverable and hard to use. The ASP.NET MVC team was able to combine a few extensibility features already in ASP.NET to now enable the standard VB/C# language syntax within the inherits attribute with the ASP.NET RC build:
One other nice benefit of not using a code-behind file is that you'll now get immediate intellisense when you first add them to the project. With the beta you had to do a build/compile immediately after creating a view in order to get code intellisense within it. The RC makes the workflow of adding and immediately editing a view compile-free and much more seamless.
Top-Level Model Property on Views
With previous builds of ASP.NET MVC, you accessed the strongly typed model object passed to the view using the ViewData.Model property:
The above syntax still works, although now there is also a top-level "Model" property on ViewPage that you can use:
This property does the same thing as the previous code sample - its main benefit is that it allows you to write the code a little more concisely.
HTML/AJAX Helpers Now Enable Expression Syntax
One of the requests a few people have asked for is the ability to use strongly-typed expression syntax (instead of using strings) when referring to the Model when using a View's HTML and AJAX helper objects.
With the beta build of ASP.NET MVC this wasn't possible, since the HtmlHelper and AjaxHelper helper classes didn't expose the model type in their signature, and so people had to build helper methods directly off of the ViewPage<TModel> base class in order to achieve this. The ASP.NET MVC RC build introduces new HtmlHelper<TModel> and AjaxHelper<TModel> types that are exposed on the ViewPage<TModel> base class. These types now allow anyone to build strongly-typed HTML and AJAX helper extensions that use expression syntax to refer to the View's model.
For example, I could build a (very simple) strongly-typed "TextBox" helper method using the code below:
And then use it within any of my views to bind against a Product model object like so:
Visual Studio will provide full intellisense for the strongly-typed expression syntax when working against the View's model in the source editor in this way:
Note: the HTML helper extensions in the core ASP.NET MVC V1 assembly will still use the existing (non-expression based) syntax. We are then planning to add expression-based versions to the MVCFutures assembly. You can of course also add your own helper methods (using either strings or strongly-typed expressions). All of the built-in helper methods can also optionally be removed (because they are extension methods) if you want to replace or override them with your own.
Scaffolding Support
The ASP.NET MVC RC build includes automatic "UI scaffolding" support when creating views using the new ASP.NET MVC "Add View" command inside Visual Studio. The scaffolding support enables the automatic generation of views against any .NET type or object - meaning it can work against POCO classes, LINQ to SQL, LINQ to Entities, NHibernate, SubSonic, LLBLGen Pro, or any other object model. The scaffolding engine uses reflection to retrieve the public shape of a View's model type, and then passes it to a scaffolding template to populate appropriate markup based on it within the view being created.
For example, assume we have a ProductsController class and want to create an "Edit" action on it to display an edit view of a particular Product. Using the RC build we can right-click within our "Edit" action method and choose the "Add View" context menu command like so:
Within the "Add View" dialog we can then indicate that we are passing a "Product" type to our View:
We can indicate that we want an "Empty" view template created (like above), or indicate that we want VS to automatically scaffold a form "Edit" view for the Product object we are supplying:
If we choose the "Edit" template VS will automatically generate a file for us that has the appropriate HTML and validation helpers to create an editable form view:
We can then run the application and immediately get edit UI:
We can then go in and change the generated edit.aspx file however we want to tweak/customize it.
One of the really nice things about the scaffolding system we are shipping is that it is implemented using Visual Studio's built-in T4 code generation system (Scott Hanselman has a nice post about this here). The "List", "Edit", "Create" and "Details" templates we ship with ASP.NET MVC can all be completely customized or replaced with T4 templates of your own (or downloaded from the ASP.NET MVC Design Gallery). So if you have your own particular way of creating HTML, or want to use custom HTML helpers (for example: strongly-typed expression based ones) you can update the default templates and the scaffolding system will use them going forward.
We are planning to enable the templates to be overriden both on a machine-wide level, as well as on a per-project level (so that you can check-in application-specific scaffolding templates under source control and share them across a team).
MSBuild Task for Compiling Views
By default when you do a build on an ASP.NET MVC project it compiles all code within the project, except for the code within view files. With the ASP.NET MVC Beta you had to roll your own MSBuild task if you wanted to compile the views. The ASP.NET MVC RC build now includes a built-in MSBuild task that you can use to include views as part of the project compilation process. This will verify the syntax and code included inline within all views and master pages for the application, and give you build errors if it encounters any problems.
For performance reasons we don't recommend running this for quick compiles during development, but it is convenient to add to particular build configuration profiles (for example: staging and deployment) and/or for use with Build or CI (continuous integration) servers.
Other ASP.NET MVC Release Candidate features coming
Above is a short list of some of the view-specific functionality coming with the release candidate build.
There are many other features and requests coming with the RC as well including: IDataErrorInfo support to enable models to surface validation error messages, as well as richer error validation extensibility to enable you to use your own approach to surface model validation errors to ModelBinders (the IDataErrorInfo support is built on top of this); new FileResult and JavaScriptResult ActionResult types (allowing you to more easily download files as well as executable JavaScript to browsers); built-in jQuery -vsdoc intellisense support; refactored AccontController support to enable easier unit testing and extensibility with form login scenarios; a variety of project template improvements, more extensibility everywhere; lots of bug fixes; and a few other cool features I'll blog about later once the RC is out.
We'll be releasing the ASP.NET MVC Release Candidate in January. Our plan is to have that build be ASP.NET MVC V1 API and feature-complete and have zero known bugs. We'll give people a short period to upgrade to it, give it a good tire-kicking, and report any last minute issues they find. We'll then ship the official V1 release shortly after that (so not far off now).
Hope this helps,
Scott
Source Click Here.