|
|
These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.
October 2009 - Posts
-
[In addition to blogging, I am now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu (@scottgu is my twitter name)] This is the twelfth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. Today’s post covers a small, but nice, change coming with VS 2010 – an “Add Reference” dialog that loads fast. Add Reference Dialog in VS 2008 The slow performance of the “Add Reference” dialog in previous releases of Visual Studio has been a common complaint that many a developer (including yours truly) has ranted about. Previous releases of VS opened the “Add Reference” dialog on the “.NET” tab by default – and when that tab was loaded VS would synchronously scan the global assembly cache (GAC) retrieving .NET assembly information. Because the GAC scan was done on the UI thread, it would freeze the IDE until the scan completed – which meant that you couldn’t cancel the operation, even if you didn’t want to use that tab. Because GAC scans can often take awhile (if you have lots of assemblies installed and/or a slow hard drive), you could end up having to wait a really long time for the dialog to respond. Add Reference Dialog in VS 2010 The Beta2 release of VS 2010 introduces a few welcome changes to the “Add Reference” dialog behavior that significantly improves its performance. The first improvement is that the “Add Reference” dialog in VS 2010 now defaults to opening on the “Projects” tab instead of the .NET tab. This means that the dialog always loads really fast. If you want to setup a project-to-project reference, or browse the file-system to select a file assembly, etc. you can now select these tabs immediately without having to wait for anything to load. The second improvement is that the .NET and COM tabs now load asynchronously and do not block the UI thread while their lists are populated. This means that if you accidentally click the tabs you are no longer blocked waiting for them to synchronously load – with VS 2010 you can now either click “Cancel” to close the dialog or click on another tab instead. Hope this helps, Scott 
|
-
[In addition to blogging, I am now using Twitter for quick updates and to share links. You can follow me on Twitter at: twitter.com/scottgu (@scottgu is my twitter name)] This is the eleventh in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. Today’s post covers WPF 4. WPF 4 Improvements WPF (Windows Presentation Foundation) is one of the core components of the .NET Framework, and enables developers to build rich, differentiated Windows client applications. WPF 4 includes major productivity, performance and capability improvements – in particular in the areas of Controls, XAML, Text, Graphics, Windows 7 integration (multitouch, taskbar integration, etc), Core Fundamentals, and Deployment. This is the first of several posts I’ll do over the coming months about some of the improvements and new features. I will do a separate post soon that covers some of the major advances coming with VS 2010’s WPF and Silverlight Designer – which also includes a ton of improvements. Controls Controls for Building Rich Clients WPF 4 adds a variety of new controls that make building rich line-of-business applications for the client easier and faster. The new, richer control set includes LOB essentials such as DataGrid, DatePicker, and Calendar controls. These new controls are 99% API- and behaviorally-compatible with their Silverlight counterparts, enabling developers to create a consistent experience across the client and web while optimizing workflow by reusing code between Silverlight and WPF implementations. Bag O'Tricks is back We are also releasing an out-of-band collection of eight controls called the WPF Bag O’ Tricks download. It includes the following controls: AnimatingTilePanel, ColorPicker, InfoTextBox, ListPager, NumericUpDown, Reveal, TransitionsPresenter, TreeMapPanel. Windows 7 & Office Ribbon Control A new WPF Ribbon Control will be available for download shortly after the release of WPF 4. It features skins for Windows 7 and Office, as well as all the standard Ribbon features that end-users are familiar with, including tabs and groups, dynamic resizing, quick access toolbar, application menu, contextual tabs, key tips, and more.  The WPF Ribbon will be fully extensible to meet changing guidelines for future releases. A CTP with a limited feature set is available today here GRAPHICS Cached Composition Massive performance wins are possible with the new Cached Composition feature in WPF 4, which allows applications to cache arbitrary content including live and fully-interactive controls, vector geometry, etc. as bitmaps which persist in video memory. Once cached, these elements can be arbitrarily transformed, animated, manipulated, and can have Effects applied, all without having to re-render the cached element. This spares both the CPU and the GPU the cost of re-rendering content, and instead allows the GPU to render straight from the cache. The cache(s) understand dirty regions, so a blinking cursor in a cached textblock, for example, will only need to re-render the cursor between frames. There’s even a new Brush which specifically uses these intelligent caches – effectively a VisualBrush with vastly better performance. Pixel Shader 3 Support WPF 4 builds on top of the very popular ShaderEffect support first introduced in WPF 3.5 SP1 by allowing applications to now write Effects using Pixel Shader version 3.0. The PS 3.0 shader model is dramatically more sophisticated than PS 2.0, allowing for even more compelling Effects on supported hardware. LayoutRounding WPF 4 adopts the UseLayoutRounding property, originally introduced in Silverlight 2. WPF’s layout engine frequently calculates sub-pixel positioning coordinates. This can lead to rendering artifacts as elements positioned on sub-pixel boundaries are anti-aliased over multiple physical pixels. UseLayoutRounding will force the layout engine to place elements on whole pixel boundaries, thus removing most of the rendering artifacts caused by this problem – which generates cleaner and crisper UI by default. Animation Easing Function Discrete, linear, and spline animations were supported with previous versions of WPF. WPF 4 introduces a new concept of Easing Functions – which allows application authors to create fluid behavior using animations. This can be used in an infinite number of ways, such as creating a springy behavior, or adding anticipation to an animation. Easing Functions customize the manner in which animations progress from start to finish. The built-in easing functions provide a range of behaviors such as circular, exponential, elastic, and bouncy animation progress. The extensibility design also allows application authors to create custom easing functions to define the manner in which their animations progress. With this easy-to-use feature, designers can effortlessly create fluid, organic animations. CleartypeHint The new CleartypeHint attached property allows application authors to enable higher-quality Cleartyped text rendering in many situations where it would have previously been disabled. Such situations include text in layered windows, text in VisualBrushes, DrawingBrushes, BitmapCacheBrushes, and anywhere else where the introduction of an intermediate render target would have previously resulted in grayscale text rendering. TEXT STACK New Text Rendering Stack The WPF text rendering stack has been completely replaced – a change that brings with it significant improvements to text rendering clarity, configurability, and support for international languages. The new text stack now supports display-optimized character layout, to produce text with comparable sharpness to Win32/GDI text: WPF’s new text stack also now supports explicitly selecting aliased, grayscale, or ClearType rendering modes: The new text stack allows optimizing text hinting and snapping for either animated or static text. Additionally, the new text stack now supports fonts with embedded bitmaps. This allows many East Asian fonts to render with the sharpness to which Win32 users have grown accustomed. BindableRun Since the initial release of WPF, Run.Text has been a normal CLR property. This has meant that Run.Text lacks all the benefits of the WPF dependency property system, most notably the ability to be bound. In WPF 4, we have converted Run.Text to a dependency property allowing developers to use the first WPF supplied bindable Run. More details can be found here. Custom Dictionaries WPF includes a spell checker which before WPF 4 only used the OS-provided dictionary for input validation. This has been a major issue for apps which target specific industries with specialized terminology, as those apps were plagued by misspelling notifications. WPF 4 has introduced an API to allow an application to add words to the dictionaries used by WPF for spell checking. More details can be found here. Selection and Caret Brush In a push to allow rich customization of the look and feel of WPF apps, developers can also now change the brush used to paint WPF text selection and carets via two simple properties: SelectionBrush and CaretBrush: WINDOWS 7 LIGHT UP Windows 7 Multitouch Support With the introduction of multi-touch input and manipulation processing support, WPF 4 provides a great way to light up your client applications in Windows 7. Multiple finger input are exposed through existing and new input events in WPF 4, while new manipulation and inertia events are now available for developers to use. New features include: - Multi-touch Manipulation, Inertia (Pan, Zoom, Rotate) events on UIElement
- Raw multi-touch events (Up, Move, Down) on UIElement, UIElement3D and ContentElement
- Multiple capture supporting multiple active controls
- ScrollViewer enhancement to support multi-touch panning
- Touch device extensibility
- Future Surface SDK compatibility
Windows 7 Shell Integration WPF 4 also exposes several new and key Windows 7 Shell features to WPF developers. These Shell features enable a richer, integrated user experience. The new taskbar is less cluttered and can convey more information at a glance. The Aero thumbnails support user commands. Jump lists provide access to contextual startup tasks and files available to the application. WPF 4 integrates Windows 7 Jump List functionality, including: - Tasks
- Items
- Recent and Frequent Lists integration
- Custom Categories
Windows 7 Taskbar integration, including: - Progress bar
- Overlay Icon
- Thumbnail buttons with commanding support
- Description Text DWM Thumbnail clipping
In Windows 7, the taskbar has been redesigned to be less cluttered and to help users perform tasks with fewer clicks. WPF 4 provides integration with the Windows 7 taskbar in XAML, allowing applications to surface useful information to the user from the application's taskbar icon using icon overlays, progress bar, thumbnail toolbars, thumbnail description text, and thumbnail clipping. There is also a new TaskbarItemInfo class in WPF 4 that is exposed as a dependency property. It encompasses all the new taskbar features introduced in Windows 7. Icon Overlays Icon overlays allow an application to communicate certain notifications and status to the user through its taskbar button by display of small overlays which appear at the lower-right corner of the button. Progress Bars A taskbar button can be used to display simple progress information to the user without that user having to switch to the application window itself. Progress bars can be used to track file copies, downloads, installations, media burning, or any other operation that will take a period of time. Thumbnail Toolbars Thumbnail Toolbars provide access to the key commands for an application without the user having to restore or activate the window. This feature enables application authors to embed an active toolbar control in a window's thumbnail preview. The application can show, enable, disable, or hide buttons from the thumbnail toolbar as required by its current state:  WPF FUNDAMENTALS New XAML/BAML Parser Engine WPF 4 has replaced its implementation of XamlReader.Load(), BAML loading, Control & DataTemplates functionality with a new engine built on top of the new System.Xaml.dll. As part of this effort, we’ve fixed many bugs and made many functionality improvements. Users of XamlReader.Load() can take advantage of several new language features in XAML2009 such as support for generic types. MarkupExtensions and TypeConverters can now get more services during object graph creation, enabling more scenarios, such as access to the Root object. Tools to analyze and manipulate XAML will also be much easier to create with many of the new low level APIs provided in System.Xaml.dll. Data Binding Support for DLR Unlike CLR classes, the members of dynamic objects are defined at runtime. DynamicObject is a new abstract class in the .NET Framework 4 that allows developers to easily implement IDynamicMetaObjectProvider. With C#’s new DLR support with the ‘dynamic’ keyword, we are expecting some library implementations to switch to using DynamicObject and IDynamicMetaObjectProvider as a standard way to exposing runtime defined properties and members of objects. WPF 4 data binding support for IDynamicMetaObjectProvider will allow the use of natural property syntax to access dynamic properties. This feature extends the WPF data binding engine to map the existing property and indexer access data binding syntax to support access to dynamic members offered by IDynamicMetaObjectProvider. Visual State Manager (VSM) Another new feature supporting the WPF-Silverlight continuum is the VisualStateManager, which introduces a simple new way to apply visual states to controls. This mechanism provides a way to easily customize both the look and feel of a control by providing the means to map the control logic to its respective start and end visual states. VSM is very flexible in that it automatically generates the transition animations in between the respective states, so the control author spends less time writing code and more time on the visual states that are defined in a control template. That means VSM can give a control author the ability to easily interchange the look and feel of controls, and VSM gives the control author a way to easily interchange how a control visually responds to user interaction. This is fully supported with Expression Blend. HTML-XBAP Script Interop WPF 4 provides the means for direct communication between an XBAP and script in the host HTML page (where the XBAP is loaded in an HTML frame or IFRAME element). The XBAP can get deep access to the HTML DOM, including to any ActiveX controls embedded in the containing HTML page and including handling of DOM events. WPF exposes the main script object from the host frame. This is a dynamic object that represents the frame’s window object plus any custom script functions and global variables from script in the HTML page. From it, an application can invoke script functions directly or “dot into” the HTML DOM. The functionality is available in partial-trust XBAPs and under all supported versions of Internet Explorer and Firefox. UIAutomation Virtualization WPF has introduced virtualized controls in past releases; however there was never a standardized way for an automation client to interact with a virtualized control. Two control patterns, ItemsContainerPattern and VirtualizedItemPattern, have been added in WPF 4 to support access and interact with virtualized elements. ItemsContainerPattern is used to access the virtualized controls & find virtualized items and VirtualizedItemPattern is used to realize virtualized items. SynchronizedInput Pattern This is another UIA control pattern added in WPF 4. This pattern could be used by automation clients to track whether the given input event is routed to the correct element by WPF framework. This pattern has three associated automation events, viz. InputReachedTargetEvent, InputReachedOtherElementEvent and InputDiscardedEvent to indicate where the input is handled. CLIENT DEPLOYMENT .NET Framework 4 Client Profile To improve deployment size, time and overall experience of the .NET Framework 4 deployment, there is now a more compact version of .NET that is a subset of the full .NET Framework 4 - called the .NET Framework 4 Client Profile. The current redistributable size of the .NET Framework 4 Client Profile is about 30MB. The full Microsoft .NET Framework 4 is a pure superset of the Client Profile. The goal of the .NET Framework 4 Client Profile is to improve and help streamline the deployment size, time, reliability and overall deployment experience for client applications. The Client Profile contains the functionality that most common desktop client applications (including Windows Forms and WPF applications) would need so it is anticipated that the majority of client application developers will target it instead of the Full .NET Framework 4. For that reason, most Visual Studio 2010 Beta 2 client project templates target the .NET Framework 4 Beta 2 Client Profile by default. Unlike the .NET Framework 3.5 SP1 Client Profile, an important enhancement in the NET Framework 4 Client Profile is its support on all platforms and OSs, including those supported by the Full Framework like Windows Vista, Windows XP, Windows Servers 2003 and 2008, Windows 7, all for both x86 and x64. You can view or change the version of the framework that you target by opening your project’s properties window, and then select the "Application" page. You can then change the “Target framework” drop-down to either the full .NET Framework or the .NET Client Profile. The project Publish property page also allows you to select the prerequisite needed for your ClickOnce deployment. In Beta2, VS2010 automatically selects the correct profile (Client Profile or Full) depending on your primary project target: The same prerequisite dialog from above appears when you create “Setup and Deployment” projects (under “Add New Project”/“Other Project Types”). The NET4 Client Profile prerequisite entry is checked by default in this case. Enhancements in NET4 Client Profile vs. NET 3.5 SP1 Client Profile Although the concept of a Client Profile is not new and was introduced in .NET Framework 3.5 SP1, the .NET Framework 4 Client Profile contains several important improvements: | | .NET Framework 4 Client Profile (NEW) | .NET Framework 3.5 SP1 Client Profile | | Supported OS | Supported on all platforms and OSs that are supported by the .NET Framework (excluding IA64 and the Server Core role in W2K8) | Supported only on Windows XP 32-bit machines that did not have any .NET Framework version installed. (Client Profile setup silently installs the full 3.5 SP1 Framework otherwise) | | Redistributable | Supports redistributable as well as web download | Supports web download only | | Add Remove Programs entries | The full Framework comprises the Client Profile and another part called “Extended”. Thus it has two entries in the Add/Remove Programs dialog (or Programs and Features window). If you installed the Full Framework, you can switch to the Client Profile by simply removing “Extended” from Add/Remove Programs. | Single entry in Add Remove Programs | | Visual Studio | Improved support for Client Profile targeting in Visual Studio 2010. By default many Visual Studio 2010 Beta2 Client project target the NET4 Client Profile. | Single checkbox in Visual Studio 2008 Service Pack 1 “Application” Project properties for .NET Framework 3.5 projects. Client Profile support unavailable in out-of-the-box VS 2008. | | Features | Includes new .NET 4 features (such as Managed Extensibility Framework (MEF), C# 4 Dynamic Keyword, etc) as well as features previously included in NET 3.5 SP1 Full (Speech, WPF Spell Check, etc) | Subset of features in .NET 3.5 SP1 Full | Because .NET 4.0 is a side-by-side release from previous releases of the .NET Framework, installation of the .NET 4.0 Framework does not require that prior versions of .NET on the machine need to be serviced/patched. This means that the .NET 4.0 Client Profile installs much faster on a machine than the .NET 3.5 SP1 Client Profile. Full Trust XBAP Deployment Starting in WPF 4, the ClickOnce elevation prompt is also enabled for XAML Browser Applications (XBAPs) in Intranet and Trusted Zones, making it easier to deploy full-trust XBAPs. For XBAPs that require security permissions greater than the minimum code access security (CAS) permission grantset of the Intranet and Trusted Zones, the user will be able to click 'Run' on the ClickOnce elevation prompt when they navigate to the XBAP to allow the XBAP to run with the requested permissions. Summary As you can tell above – there is a bunch of great new functionality coming with WPF 4.0. Below are a few links and resources you can follow to learn more some of these features: I’ll do more posts in the coming months that also highlight some of the new WPF 4 capabilities and how to take advantage of them. I’ll also be doing another post shortly that talks about the new VS 2010 WPF and Silverlight designer – which makes it possible to build great WPF and Silverlight applications using a WYSIWYG designer directly within Visual Studio 2010. Hope this helps, Scott 
|
-
Imagine that you've got an ASP.NET page that is generating an email message that needs to include links back to the website. Perhaps you're writing the next greatest online message board application and when someone replies to a thread you want to send out emails to the other thread participants indicating that a new message has been posted along with a link to view the just-posted message. You know that the URL to view a particular thread is, say, ~/Threads/View.aspx?ThreadId=threadId. But how do you turn that relative URL into an absolute URL like http://www.yourserver.com/Threads/View.aspx?ThreadId=threadId?
The simplest answer is to hard code the domain name into the URL when generating the email's content, but that approach is naive and wouldn't work if you were building an application that others could buy and install on their servers. It also would cause a headache if you change your domain name. Finally, it's a headache because oftentimes an ASP.NET application has different URLs depending on the environment. From the development environment the URL might be http://localhost:somePortNumber/MyMessageboard/Threads/View.aspx?ThreadId=threadId, whereas on the staging environment it might be http://stagingserver/MB/Threads/View.aspx?ThreadId=threadId. Ideally, the email generated from a particular environment would contain the appropriate URL back to said environment.
The good news is that generating a fully qualified URL in ASP.NET is quite simple. The following code will pick up the correct HTTP or HTTPS setting, the correct server name - be it localhost, localhost:portNumber, serverInIntranet, an IP address, or a domain name (www.example.com) - and the applicaiton path, if any. Here's the code in both C# and VB:
// C#
string relativeUrl = "~/Threads/View.aspx?ThreadId=" + threadId;
string fullyQualifiedUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl(relativeUrl);
' VB
Dim relativeUrl As String = "~/Threads/View.aspx?ThreadId=" + threadId
Dim fullyQualifiedUrl As String = Request.Url.GetLeftPart(UriPartial.Authority) & Page.ResolveUrl(relativeUrl)
That's it! Pretty easy.
The Request.Url property returns the fully qualified URL of the currently requesting page. The GetLeftPart(UriPartial.Authority) method returns just the protocol and domain name, which is then concatenated with the resolved relative URL to give us the fully qualified URL for the relative URL.
For more on Request.Url, along with a look at the many other path-related properties available of the HttpRequest class, see Rick Strahl's blog entry, Making Sense of ASP.NET Paths.
|
-
I was recently working on an application and needed the ability to present the user with a list of links when they hovered over a particular line of text. HTML elements include a title attribute that, when set, displays the attribute's value in a small yellow window when the user hovers over the element. Problem is, the tooltip is a text-only interface. There's no way to embed a hyperlink or image or other rich markup into the tooltip.
Since we are using jQuery in this project I spent some time exploring various techniques for implementing rich tooltips in jQuery. Specifically, I needed a solution that met the following criteria:
- The tooltip would appear near or next to the text that the user was hovering over, and not on some fixed, predefined spot on the screen.
- I could, from server-side code, specify what elements would display tooltips when hovered over.
- I could, from server-side code, customize the tooltip message.
- The tooltip could include any sort of HTML markup I wanted to throw into it - links, images, etc. - and the user could interact with this markup (click on a link, for instance).
- The tooltip would remain displayed for a specified amount of time (say, 500 milliseconds) after the user moused off of the element that displayed the tooltip.
Unfortunately, I was unable to find a pre-built solution that would meet our needs, so I created my own, which I'd like to share now.
Please keep in mind that I know just enough JavaScript to shoot myself in the foot. Also, my experience with jQuery is limited, to be kind.
In order to display rich tooltips using my approach you need to do three things.
First, add the following CSS to those pages that use the rich tooltips:
.skmTooltipHost { cursor: help; border-bottom: dotted 1px brown; }
.skmTooltipContainer { padding-left: 10px; padding-right: 10px; padding-top: 3px; padding-bottom: 3px; display: none; position: absolute; background-color: #ff9; border: solid 1px #333; z-index: 999; }
Those elements that should display a tooltip when hovered over need to use the skmTooltipHost class. The skmTooltipContainer class defines the styles for the tooltip itself.
Next, add the following $(document).ready function to your page (and add a script reference to the appropriate jquery.js file, if you haven't already):
<script type="text/javascript"> $(document).ready(function() { $(".skmTooltipHost").hover( function() { $(this).append('<div class="skmTooltipContainer">' + $(this).attr('tooltip') + '</div>'); $(this).find('.skmTooltipContainer').css("left", $(this).position().left + 20); $(this).find('.skmTooltipContainer').css("top", $(this).position().top + $(this).height()); $(".skmTooltipContainer").fadeIn(500); }, function() { $(".skmTooltipContainer").fadeTo(500, 1.0, function() { $(this).remove(); }); } ); }); </script>
Finally, decorate those HTML elements that you want to display a tooltip with the skmTooltipHost class and add an attribute named tooltip that contains the content to display in the tooltip. For example, imagine I had a document with the following markup:
<p>ASP.NET simplifies the process of creating dynamic web applications!</p>
I could turn add a tooltip to the text “ASP.NET” by adding the additional markup:
<p><span class="skmTooltipHost" tooltip="ASP.NET was created by Microsoft in 2001.">ASP.NET</span> simplifies the process of creating dynamic web applications!</p>
To get rich markup in the tooltip attribute you'll need to escape the <, >, and " characters with <, >, and ", respectively. For instance, we could add a hyperlink in the above tooltip like so:
<p><span class="skmTooltipHost" tooltip="ASP.NET was created by Microsoft in 2001. Learn more at <a target="_blank" href="http://www.4guysfromrolla.com/">4GuysFromRolla.com</a>!">ASP.NET</span> simplifies the process of creating dynamic web applications!</p>
You can see these rich tooltips in action here - http://scottonwriting.net/sowBlog/CodeProjectFiles/JQueryTooltipDemo.htm
And lastly, to do this programmatically from server-side code, you would add a Label Web control to your page named, say, lblASPNET. You'd set its CssClass property to skmTooltipHost. To set its tooltip attribute add the following (untested) code to the Page_Load event handler:
lblASPNET.Attributes.Add("tooltip", Server.HtmlEncode("ASP.NET was created by Microsoft in 2001. Learn more at <a target="_blank" href="http://www.4guysfromrolla.com/">4GuysFromRolla.com</a>!")
|
-
This is the tenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. In today’s blog post I’m going to cover a small but really nice improvement to code intellisense with VS 2010 – which is its ability to better filter type and member code completion. This enables you to more easily find and use APIs when writing code. Code Intellisense with VS 2008 To help illustrate this intellisense improvements coming with VS 2010, let’s start by doing a simple scenario in VS 2008 where we want to write some code to enable an editing scenario with a GridView control. We might start off by typing “GridView1.Edit” to bring up intellisense to see what Edit members are available on the control. Doing this with VS 2008 brings up the intellisense drop-down and filters the current location in the dropdown to the members that start with the word “Edit”: This is great if the method/property/event we want to work with starts with “Edit” – but doesn’t really help us if the “Edit” member we are looking for starts with something else (for example: the “RowEditing” event or the “SetEditRow()” helper method). We have to either manually scroll up and down looking for the other edit members, or pull up the object browser or help system to find them. Code Intellisense with VS 2010 Let’s now try out the same scenario with VS 2010. When we type “GridView1.Edit” within VS 2010 we’ll find that the EditIndex property is still highlighted by default. But the intellisense list has also been filtered so that it enables you to quickly locate all other members that have the word “Edit” anywhere in them: This allows us to quickly see all of the edit related methods/properties/events and more quickly find what we are looking for. Searching for Keywords This new intellisense filtering feature of VS 2010 is useful for searching for any member – regardless of what word it starts with. For example, if we want to enable paging on a datagrid and can’t remember how to-do it, we could just type “GridView1.Paging” and it would automatically filter out everything but members that have the word paging. Notice below how no members on the GridView class actually start with the word “Paging” – but I am still finding the two members that do have paging in them later in their names: Searching for Types This new intellisense filtering capability of VS 2010 is also useful for quickly finding classes and types. For example, when we type “List” to declare a variable, the editor will provide automatic filtering to show all types that have the word “List” somewhere in them (including IList<> and SortedList<> – which do not start with List): This makes it much easier to find type names you can’t entirely remember – without having to resort to searching through the object browser and/or using help documentation. Pascal Case Intellisense The .NET Framework naming guidelines specify that type and member names should be “Pascal Cased” by default. This means that each word in a type or member should start with a capitalized letter (for example: PageIndexChanged). VS 2010’s intellisense filtering support now enables you to take advantage of this to quickly find and filter methods based on their pascal naming pattern. For example, if we typed “GridView1.PIC” VS 2010 would filter to show us the members that have PIC in their name, as well as those members which have a pascal cased name where the word segments start with that letter sequence: Notice above how PIC caused both “PageIndexChanged” and “PageIndexChanging” to show up. This saves us a few keystrokes when resolving either member or type names. Summary I think you’ll find that the new intellisense filtering approach in VS 2010 makes it easier to quickly find and use classes and members when writing code. You can take advantage of it with both VB and C#. Hope this helps, Scott P.S. In addition to blogging, I have recently been using Twitter to-do quick posts and share links. You can follow me on Twitter at: www.twitter.com/scottgu (@scottgu is my twitter name) 
|
-
This is the ninth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. In today’s blog post I’m going to cover some of the new code searching and navigation features that are now built-into VS 2010. Searching and Navigating code Developers need to be able to easily navigate, search and understand the code-base they are working on. In usability studies we’ve done, we typically find that developers spend more time reading, reviewing and searching existing code than actually writing new code. The VS 2010 code editor adds some nice new features that allow you to more productively search and navigate a code-base, and enable you to more easily understand how code is being used within a solution. Searching and Navigating the ASP.NET MVC Source Code For this blog post I’m going to use the ASP.NET MVC framework code-base (which has many thousand lines of code) to help demonstrate some of the new VS 2010 searching and navigation features. If you have VS 2010 Beta 2 installed, you can follow along by downloading and opening the ASP.NET MVC framework source code from here. You should find that the performance of the below features is really fast with this project – despite it being many thousands of lines of code in size. All of the features I’m demonstrating below are also now built-into VS 2010 (and work for all project types and for both VB and C#). VS 2010 “Navigate To” Support Being able to quickly find and navigate code is important with both big and small solutions. Visual Studio 2010 now supports a new (Ctrl+comma) keyboard shortcut (meaning the control key is held down together with the comma key). When you press the (Ctrl+comma) combination, a new VS 2010 “Navigate To” dialog will appear that allows you to quickly search for types, files, variables and members within your solution – and then open and navigate to them: The “Navigate To” dialog provides an fast incremental search UI – with results immediately populating as soon as you start typing search terms. For example, type “cont” (without pressing enter) and you’ll see that 176 results immediately show up within the results list as you start to type: Type a few more characters and you’ll see the list automatically filters to just those results that match “controller”: You can use the scroll bar to scroll through the results – or alternatively press the tab key and then use the cursor arrows if you don’t want to take your hands off the keyboard. You’ll find that the “Navigate To” window lists all types of results that match your search term – including Type names, Method/Property names, Field declarations, and file names: Selecting any of the results in the results list will open the relevant source file within VS 2010 (if it isn’t already open) and take you immediately to the relevant source location (and highlight the relevant name within it): Nice Fuzzy Search Capabilities The “Navigate To” search box supports some nice “fuzzy search” capabilities that allow you to perform smart filters and searches without having to know exactly the name of the thing you are looking for. These work well with the incremental/immediate search UI of the dialog – and allow you to refine your searches and get real-time results as you type. To try this out let’s first search on the word “cache”. Notice how the search results include not just items that start with the word “cache” – but also display any results that have the word “cache” in it: We can add multiple words to the search textbox to further filter the results. For example, below I am filtering the list to only include those that have both “cache” and “action” in the name: Types and members within the .NET Framework using a naming design-guideline pattern called “Pascal Casing” – which means that the first letter of each word in a Type or Member name is capitalized. The “Navigate To” dialog allows you to optionally use this “Pascal Casing” convention to quickly filter types. Just type the uppercase first letter of names in a type/member and it will automatically filter for results that match the uppercase pascal naming convention. For example, typing “AMS” will filter to the below results (just those types and members that have words in them that start with A then M then S): The “Navigate To” dialog allows you to quickly filter and locate code with a minimum of keystrokes – and avoid you ever having to use the mouse, open the solution explorer, and click on a file directly. View Call Hierarchy Having the ability to quickly search and navigate to code is great. Being able to also quickly discover how that code is being used is even better. VS 2010 introduces a new “View Call Hierarchy” feature that allows you to quickly discover where a particular method or property within your code-base is being called from, and allows you to quickly traverse the call tree graph throughout the code-base (without having to run or debug the solution). To use this feature, simply select a method or property name within your code-base, and then either type the (Ctrl+K,Ctrl+T) keyboard shortcut combination, or right-click and select the “View Call Hierarchy” context menu command: This will bring up a new “Call Hierarchy” tool window that by default shows up under the code editor. Below you can see how the “Call Hierarchy” window is displaying the two methods within our solution that invoke the ViewPage.RenderView() method we selected above. We can then optionally drill down hierarchically into the first “RenderViewAndRestoreContentType” method to see who in-turn calls it: For virtual methods/properties you can also use the call hierarchy window to see what types sub-class and override them. Double clicking any of the members within the “Call Hierarchy” window will open the appropriate source file and take you immediately to that source location: This allows you to quickly navigate throughout a code-base and better understand the relationships between classes and methods as you code. Highlighted References With VS 2010, when you select or highlight a variable / parameter / field declaration within the code-editor, all subsequent usages of it are now automatically highlighted for you within the editor. This makes it easy to quickly identify where and how a variable or parameter is being used. For example, when we select the “controllerContext” parameter passed to the ControllerActionInvoker.GetParameterValue() method in the editor below, notice how the 4 usages of it within that method are also now automatically highlighted: If I select a local variable within the method, all the places it is used are also now automatically highlighted: If multiple usages are highlighted, you can cycle through them using the (Ctrl-Shift-up arrow) and (Ctrl-Shift-Down arrow) keystrokes to quickly move the cursor to the previous or next highlighted symbol. Summary The new VS 2010 text editor makes it easy to quickly search, navigate and explore code within a project or solution. The performance of these operations is really fast (even with a large code-base) and are kept up to date as you work on the project and make changes to it. The end result enables you to be much more productive. Hope this helps, Scott P.S. In addition to blogging, I have recently been using Twitter to-do quick posts and share links. You can follow me on Twitter at: www.twitter.com/scottgu (@scottgu is my twitter name) 
|
-
I’m happy to announce that today we shipped the Beta 2 release of Visual Studio 2010 and .NET 4.0. MSDN subscribers can download Beta 2 immediately. We will be opening up Beta 2 for everyone to download starting this Wednesday. VS 2010 and .NET Improvements VS 2010 and .NET 4 bring a huge number of improvements and additions. They include big advances for ASP.NET web development, WPF and WinForms client development, SharePoint development, Silverlight development, data development, parallel computing development, and cloud computing development. VS 2010 also delivers a ton of improvements in the core IDE, code editors, programming languages, and enterprise design, architect, and testing tools. TFS 2010 is now easy to install (only 20 minutes to setup source control, bug and work item tracking, build automation, and continuous integration), can be installed on both servers as well as client OS and domain controller machines, and is now included with all MSDN subscriptions of Visual Studio. I’ve started a series of blog posts that will cover some of the improvements and feature additions in VS 2010 and .NET 4. Stay tuned to my blog as I post many, many more posts over the coming months. VS 2010 Product Line SKU Simplifications With VS 2010 we are simplifying the product lineup and pricing options of Visual Studio, as well as adding new benefits for MSDN subscribers. With VS 2010 we will now ship a simpler set of SKU options: - Visual Studio Express: Free Express SKUs for Web, VB, C#, and C++
- Visual Studio 2010 Professional with MSDN: Professional development tools as you are used to today with the addition of source control integration, bug tracking, build automation, and more. It also includes 50 hours/month of Azure cloud computing.
- Visual Studio 2010 Premium with MSDN: Premium has everything in Professional plus advanced development tools (including richer profiling and debugging, code coverage, code analysis and testing prioritization), advanced database support, UI testing, and more. Rather than buying multiple “Team” SKUs like you would with VS 2008, you can now get this combination of features in one box with VS 2010. It also includes 100 hours/month of Azure cloud computing.
- Visual Studio 2010 Ultimate with MSDN: Ultimate has everything in Premium plus additional advanced features for developers, testers, and architects including features like Intellitrace (formerly Historical Debugging), the new architecture tools (UML, discovery), test lab management, etc. It also includes 250 hours/month of Azure cloud computing.
Side by Side Support with VS 2008 VS 2010 and .NET 4.0 can be installed side-by-side on the same machine as VS 2008 and .NET 3.5. You can install the Beta 2 version on a machine and it will not impact your existing VS 2008 / .NET 3.5 development. Go-Live License Available .NET 4 and VS 2010 Beta 2 include a “go-live” license which means you can start using the products for production projects. Summary VS 2010 and .NET 4.0 deliver some significant new capabilities and improvements. The goal with today’s Beta 2 release was to work hard on performance, stability, and the integration of the overall feature set. The team’s focus is now transitioning to getting your feedback on the product and preparing for the final release candidate (RC) milestone. Please send us any feedback you have on the Beta 2 release. Hope this helps, Scott P.S. In addition to blogging, I have recently been using Twitter to-do quick posts and share links. You can follow me on Twitter at: www.twitter.com/scottgu (@scottgu is my twitter name) 
|
-
The ASP.NET team today released a significant new update of the Microsoft Ajax Library (Preview 6). This update includes a bunch of new capabilities and improvements to our client-side AJAX library, and can be used with any version of ASP.NET (including ASP.NET 2.0, 3.5 and 4.0), and can be used in both ASP.NET Web Forms and ASP.NET MVC projects. Today’s release includes the following feature improvements: - Better Imperative Syntax: A new, simplified, code syntax for creating client controls.
- Client Script Loader: A new client-side script loader that can dynamically load all of the JavaScript files required by a client control or library automatically, and executes the scripts in the right order.
- Better jQuery Integration: All Microsoft Ajax controls are now automatically exposed as jQuery plug-ins.
In addition to the client library improvements, we also today released a new (free) Microsoft AJAX Minifier tool. This tool allows you to substantially improve the performance of your websites by reducing the size of your JavaScript files. It can be run both as a command-line tool, and also ships as a Visual Studio MSBuild task that you can integrate into your VS projects to automatically minify your JavaScript files whenever you do a build. Using the Microsoft AJAX Library (Preview 6) There are two ways that you can start building applications with the Microsoft Ajax (Preview 6) release: 1) You can visit the ASP.NET CodePlex website and download the Preview 6 release (which also includes a large set of samples with it). 2) Alternatively, you can access the Microsoft Ajax Library scripts directly from the Microsoft Ajax Content Delivery Network (CDN). You can do this by just adding the following script tag to either an .aspx or .html page: <script src=”http://ajax.microsoft.com/ajax/beta/0910/Start.js” type=”text/javascript”></script> You read my blog post from last month to learn more about the Microsoft AJAX CDN (or visit http://www.asp.net/ajax/cdn). Better Imperative Code Syntax with this release The ASP.NET team heard feedback from the community that many developers preferred an imperative code approach (as opposed to a declarative syntax approach) when creating client controls. With today’s release we are introducing a simple imperative code syntax for creating client controls and binding them to HTML elements within a page. This syntax is fully supported by the JavaScript Intellisense in both VS 2008 and VS 2010. Below is an example of the imperative code you can now write to programmatically create a client-side DataView control that displays data from a WCF web service: The above code instantiates a new Microsoft Ajax DataView control and attaches the control to an HTML <div> element with the id “imageView”. The URL of the WCF service is specified with the “dataProvider” property, and the name of the method to call on the service is specified with the “fetchOperation” property. The “autoFetch” property indicates that the control should automatically bind against the WCF service when it loads. Below is what the “imageView” HTML <div> element that the DataView control is attached to looks like. This <div> contains a template that will be used for displaying each data item retrieved from the service (note: templates were a feature we introduced with an earlier Microsoft Ajax Preview release): The {{ Uri }} and {{ Name }} expressions within the template above are replaced with the Name and Uri properties of the images retrieved from the service. The attribute namespace prefix “sys:src” on the <img> element is used to prevent browsers from attempting to load an image at the actual path {Uri}. The value of the sys:src attribute gets plugged into the src attribute when the template is loaded. When the page is rendered in the browser, we then get a simple photo gallery like below: Alternatively, if you don’t want to use a declarative binding syntax within a template, you can modify the template to be pure HTML markup like below (no more {{ }} BLOCKED EXPRESSION: You can then wire-up and specify a itemRendered event handler when you create the DataView control like below: You can then implement the “imageRendered” event handler using the JavaScript below, and use the Sys.bind() method to programmatically assign values to the <img> and <span> tags within the template: This allows you to maintain your template as pure HTML markup, while still displaying the same photo gallery experience at runtime. Using the Microsoft Ajax Client Script Loader The Microsoft AJAX Client-side library is now split up across multiple JavaScript files – allowing you to download and use only those script files that you actually need (reducing download sizes). Manually adding all of the script files required to use Ajax controls can be tedious though (and error prone). To make it easier to use both client controls as well individual client library components, we are introducing a new client script loader with today’s release. This client script loader helps you automatically load all of the scripts required by a control and execute the scripts in the right order when a page loads. For example, the following page uses the client script loader to load all of the scripts required by the “watermark” control, and then wires up the watermark control to an <input> textbox: Notice the call to the Sys.require() method above. When you call Sys.require(), you supply the name of a client component (or an array of client components) that you want to load. The sys.require() client loader then automatically downloads all of the required script files in parallel (allowing your scripts to load faster and also allow you to avoid blocking the page from rendering). When all of the scripts required by the components requested are loaded, the Sys.onReady() method is called and the watermark is created. Above we are binding the “watermark” control to a <input> textbox with an id of “name”. At runtime the watermark control will cause the textbox to have a watermark (that automatically disappears when a user sets the focus on the textbox and starts typing):  The client script loader supports many advanced features including automatic script combining and lazy loading. It can also be smart about downloading either debug or release versions of libraries. It also allows you to register your own libraries and have them automatically be loaded as well using the Sys.require() syntax. Using Microsoft Ajax Library Controls with jQuery Microsoft ships jQuery as a standard part of the ASP.NET MVC framework, and also adds it by default to new ASP.NET Web Forms projects created with Visual Studio 2010. With today’s preview we are making it easy to integrate jQuery and Microsoft Ajax controls, and enable developers using jQuery to use the Microsoft Ajax controls with a familiar jQuery plug-in API syntax. Specifically, we are now exposing all Microsoft Ajax controls as jQuery plug-ins automatically. In other words, when you add jQuery to a page, you can use Microsoft Ajax controls just like jQuery plug-ins. For example, the following script demonstrates how you can use jQuery to create a DataView that displays data from a WCF service (using a jQuery plugin like code syntax): Notice above that I’m loading jQuery by calling the Sys.require() client-side loader API. You can load jQuery using the new client script loader, or alternatively you can just include the jQuery library in the page using a standard <script> tag. Once jQuery is added to the page, Microsoft Ajax Library controls are automatically exposed as jQuery plug-ins. This means you can create and attach Microsoft Ajax controls using a standard jQuery plugin syntax (like above), and fully integrate with the jQuery selector syntax. Reducing the Size of JavaScript Files with the Microsoft Ajax Minifier There are two common ways that people use to reduce the download size of a JavaScript file: compression and minification. When you host your website on a Windows Server using IIS 7.0, you can configure IIS to automatically compress your JavaScript files using GZIP compression – which can provide a significant improvement on performance and the download size of files. However, you can get additional performance benefits by both compressing and minifying your JavaScript files. Steve Sounders describes these additional benefits in his excellent book High Performance Web Sites. In addition to releasing Microsoft Ajax Library (Preview 6), we are today also releasing a new (free) Microsoft Ajax Minifier utility that can help reduce the size of your JavaScript files considerably. It was created by Ron Logon who works on the MSN team. You can download the Microsoft Ajax Minifier from the ASP.NET CodePlex website for free. The following screenshot demonstrates the results of minifying the standard jQuery library using various minification tools such as Douglas Crockford’s JSMin, Dean Edward’s Packer, and the YUI Compressor. The bottom two files were minified using the Microsoft Ajax Minifier utility. Notice that the Microsoft Ajax Minifier has reduced jQuery from 125 KB to only 53 KB. The Microsoft Ajax Minifier supports two levels of minification: normal and hypercrunched. When you use normal minification, the Microsoft Ajax Minifier removes all unnecessary whitespace, comments, curly braces, and semi-colons. When you enable hypercrunching, the Microsoft Ajax Minifier becomes more aggressive in reducing the size of a JavaScript file, and it minifies local variable names and removes unreachable code. Here’s a sample of a JavaScript file: Here’s what the JavaScript file looks like after it has been minified with the Microsoft Ajax Minifier (with hypercrunching enabled): Notice that all unnecessary whitespace has been removed. Notice also that the function parameters firstValue and secondValue have been renamed to b and a. The Microsoft Ajax Minifier download includes the following components: - ajaxmin.exe – A command-line tool for minifying JavaScript files.
- ajaxmintask.dll – A MSBuild task for minifying JavaScript files in a Visual Studio project.
- ajaxmin.dll – A component that you can use in your C# or VB.NET applications to minify JavaScript files.
After you install the Microsoft Ajax Minifier, you can use the Microsoft Ajax Minifier command-line tool to minify a JavaScript file from a command-prompt. You also have the option of adding the Microsoft Ajax Minifier as a custom MSBuild task to Visual Studio. Adding the Microsoft Ajax Minifier MSBuild task to your Visual Studio project file allows you to automatically minify all of the JavaScript files in your project whenever you perform a build, and enables you to perform minification in an automated way. Summary Today’s release of the Microsoft Ajax Library has several exciting new features for client-side developers. The new simplified imperative syntax should appeal to JavaScript developers. The client script loader makes it much easier to create client controls and optimize the download of files. And, the jQuery integration enables developers using jQuery to take advantage of the client controls, templating, and data access features of the Microsoft Ajax Library without changing their programming style. Finally, the new Microsoft Ajax Minifier enables you to significantly improve the performance of your Ajax applications by reducing the size of your JavaScript files. You can use the minifier from a command prompt or you can use the minifier when building a project in Visual Studio. Click here to download both the Microsoft Ajax Library (Preview 6) release and the new Microsoft Ajax Minifier release. Hope this helps, Scott P.S. In addition to blogging, I have recently been using Twitter to-do quick posts and share links. You can follow me on Twitter at: www.twitter.com/scottgu (@scottgu is my twitter name) 
|
-
JSLint is a free JavaScript code quality tool created by Douglas Crockford. At the JSLint.com website you can paste in a block of JavaScript code and JSLint will examine the code and warn you when it encounters any script that violates its list of rules. Many of the rules JSLint checks against are configurable, and include checks for usage of undefined variables, use of the eval function, statements not terminated with semicolons, and other 'trouble waiting for a place to happen' coding patterns.
JSLint.VS is a free, open source Visual Studio Add-In created by Predrag Tomasevic that brings JSLint to the Visual Studio IDE.
Today I installed JSLint.VS for the first time on a machine. The installation went smoothly, but anytime I used the Add-In it reported No Errors, even though the JSLint.com website was finding errors with the same block of JavaScript code. The good news is that I was able to identify the problem and fix it.
Just the Workaround, Please For JSLint.VS to work the .js extension must be associated with the JScript WSH engine. Chances are, you have the JScript WSH engine already installed, but another program has claimed the association. In my case, the .js extension was associated with UltraEdit. Once I reassociated it with the JScript engine, the JSLint.VS Add-In worked as expected.
To see what program the .js extension is associated with, drop to the command line and enter:
assoc .js
The output should be: .js=JScript. If it's not, enter:
assoc .js=JScript
Now try JSLint.VS again.
For Those Who Care... The Why... When you launch JSLint.VS from within the IDE it creates three files in the Application Data folder (My Documents\User\Application Data):
- wsh.js - contains the JSLint JavaScript code, which you can download from http://www.jslint.com/fulljslint.js
- temp.js - contains the JavaScript code to check with JSLint
- csh.cmd - a batch file that executes the wsh.js file, passing in the temp.js contents as input.
Specifically, JSLint.VS executes the following command:
csh.cmd wsh.js < temp.js
If the .js extension is not mapped to the JScript WSH engine the above command will result in the following error message: “There is no script engine for file extension .js”
In the face of that error, JSLint.VS simply returns, “No Errors.” Once you associate the .js extension with the JScript WSH engine you should be good to go!
|
-
[In addition to blogging, I have recently been using Twitter to-do quick posts and share links. You can follow me on Twitter at: www.twitter.com/scottgu (@scottgu is my twitter name)] This is the eighth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. Today’s post covers a cool new runtime feature in ASP.NET 4 – which is the ability to use URL routing with Web Forms based pages. What is URL Routing? URL routing was a capability we first introduced with ASP.NET 3.5 SP1, and which is already used within ASP.NET MVC applications to expose clean, SEO-friendly “web 2.0” URLs. URL routing lets you configure an application to accept request URLs that do not map to physical files. Instead, you can use routing to define URLs that are semantically meaningful to users and that can help with search-engine optimization (SEO). For example, the URL for a traditional page that displays product categories might look like below: http://www.mysite.com/products.aspx?category=software Using the URL routing engine in ASP.NET 4 you can now configure the application to accept the following URL instead to render the same information: http://www.mysite.com/products/software With ASP.NET 4.0, URLs like above can now be mapped to both ASP.NET MVC Controller classes, as well as ASP.NET Web Forms based pages. Mapping URLs using ASP.NET MVC The URL Routing engine introduced with ASP.NET 3.5 SP1 provides a powerful way to handle incoming URLs. Typically you write code as part of application startup to register/map URLs that match a specific URL format to code handlers. Below is an example of how you can use ASP.NET MVC today to map the /products/software URL to a controller class called “Products” that has an action method named “Browse”: The first “products-browse” parameter to the MapRoute() helper method above is a friendly name for the route. The second “products/{category}” parameter is the URL filter that matches the /products/software URL – and which treats the second segment of the URL as a parameter value called “category”. This parameter will then be passed to the ProductsController’s Browse() action method to process. Mapping URLs using ASP.NET Web Forms ASP.NET 4.0 now allows you to also use the URL Routing engine to map URLs to ASP.NET Web Forms pages as well as ASP.NET MVC Controllers. Below is an example of how you can use the new MapPageRoute() helper method in ASP.NET 4.0 to map the /products/software URL to a “Products.aspx” page that lives immediately under the application root directory: The first two parameters to the MapPageRoute() helper are the same as in MapRoute(). The first parameter provides a friendly name for the route, and the second specifies the URL format to match. The third parameter, though, points to a Products.aspx page to handle the URL instead of a controller class. You can optionally specify additional parameters to MapPageRoute() that take advantage of features like “route constraints” and provide “default values for parameters” just like you can with ASP.NET MVC based route registrations. Within the Products.aspx page you can then write code like below that uses the new Page.RouteData property in ASP.NET 4.0 to retrieve the “category” parameter value mapped using the /products/{category} URL filter, and then databind the category products to display them: In addition to programmatically accessing incoming route parameters using code like above, you can also take advantage of the new declarative <asp:routeparameter> control with any ASP.NET DataSource control to declaratively bind a value from a route as well. For example, below we are using a <asp:routeparameter> statement to bind the select statement’s @category parameter from the /products/{category} parameter in the URL route: Retrieving URLs within an ASP.NET Web Form The URL routing engine in ASP.NET can be used to both map incoming URLs to code handlers, as well as be used to programmatically generate outgoing URLs using the same mapping registration logic. For example, above when we mapped the /products/{category} URL we gave it a “friendly name” of “products-browse”. This allows us to now also use the new Page.GetRouteUrl() helper method to lookup the route within the URL routing system, optionally specify parameters to it, and then retrieve an actual URL that it maps back to. For example, the below code would retrieve a URL value of “/products/software”: You can access the above helper method within either your code-behind file or within your .aspx markup. There is also now a Response.RedirectToRoute() set of methods that you can use to redirect users to a route (regardless of whether it is a MVC or Web Forms handled one) and optionally pass parameters to it. Handling PostBack Scenarios URL Routing with ASP.NET 4.0 fully supports postback scenarios. The <form runat=”server”> control will automatically emit the same URL that caused the page to be rendered. For example, if you access a page with a /products/software URL then any server-side <form runat=”server”> control within it would render out a <form action=”/products/software”> HTML element back to the client – which means that any postback scenarios that happen on the page will preserve the original URL. This makes supporting clean, SEO friendly, URLs easy with Web Forms and postback scenarios – and avoids some of the tricks people need to use today when using URL rewriting modules to achieve similar effects. Summary ASP.NET 4.0 makes it easy to implement clean, SEO friendly, URLs using both ASP.NET MVC and now ASP.NET Web Forms (you can also have applications that mix the two). The URL routing engine makes it easy to register URLs of any shape or format and map them to any handler you want. Because the URL routing engine can be used for both mapping incoming URLs as well as generating outgoing URLs, you can at a later point change the URL mappings and not have to modify any page or controller specific code to reflect them – which makes building SEO optimized applications much easier. Hope this helps, Scott 
|
-
My Toolbox column in the October 2009 issue of MSDN Magazine is available online and includes the following reviews:
- nukeationMachine - nukeationMachine is a Visual Studio Add In that streamlines implementing WPF, WinForms, and ASP.NET user interfaces. nukeationMachine includes 1,600 UI bits, which are common groupings of user interface elements, such as Ok, Cancel, Retry buttons. You can add any UI bit to a design surface with a click of the mouse and in a fraction of the time it would take to add and position each user interface element separately.
- Podcasts of Note: .NET Rocks - each week hosts Carl Franklin and Richard Campbell spend about an hour exploring a particular technology, product, or person of interest to the .NET community. Franklin and Campbell are both natural interviewers and do a great job picking the brains of their guests while maintaining a smooth and natural flow to the discussion. Listening to a .NET Rocks podcast is a lot like overhearing a conversation among experienced developers at a user group meeting or conference - you're bound to learn something new, hear an interesting anecdote or two, and discover how other knowledgeable developers are using .NET and related technologies in their daily jobs.
- Fluent NHibernate - NHibernate is a popular ORM for .NET whose relational to domain mapping is typically specified via XML. Fluent NHibernate is an open source library that enables developers to specify these mappings using a fluent interface, an API design style that aims at maximizing readability through the use of descriptive names and method chaining.
This issue reviewed The Nomadic Developer, by Aaron Erickson. An exerpt from my review follows:
If you currently work for a technology consulting company, or are weighing the pros and cons of doing so, then Aaron Erickson's book "The Nomadic Developer" is for you. ... [It] should be required reading for anyone currently seeking a job at a consulting company, especially those who have not previously worked as consultants. The book's second chapter, "The Seven Deadly Firms," describes seven dysfunctional traits that, if present, will negatively impact your time at the company. For each dysfunction, Erickson supplies a detailed description, explains what life is like at a consulting firm when that trait is present, and provides tips for spotting the dysfunction during a job interview. There are also chapters on the top 10 traits a technology consulting firm is looking for in applicants, and another chapter that suggests questions applicants should ask during the interview process.
Enjoy! - http://msdn.microsoft.com/en-us/magazine/ee309513.aspx
As always, if you have any suggestions for products, blogs, or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.
|
-
App_Data, App_Code, App_Themes, and App_GlobalResources – we’ve come to love them over the years. I was hoping the team could add a few more “special” folders to ASP.NET, but I don't think these will make it ...
App_Store – drop in an xml file with product descriptions and … presto! Instant e-commerce!
App_etizers – content you serve customers before they get to the main part of the site. App_liances – will work with Azure, because cloud computing needs appliances. App_endix – I'm not sure what this would do, actually. Perhaps I should remove it.

|
-
I recently ran into a situation where I needed to delete all records from a table except for the 1,000 most recently added records. Specifically, I was working on a site that used Error Logging Modules And Handlers (ELMAH), a free, open source error logging library for ASP.NET applications. ELMAH doesn't automatically prune its error log. If you are using the database as a log source and if your web hosting provider has a database quota in effect, it is possible to have ELMAH's error log grow so large that the quota is surpassed and the database is taken offline. To help mitigate this problem, it is a good idea to take steps to keep ELAMH's error log size in check:
As with any sort of logging service is is important that ELMAH's log be periodically pruned. If you let ELMAH's log grow unchecked it can reduce performance when querying the log and suck up disk space, which is especially important in hosted environments where there are typically hard disk quote limits for each user on the database server. The good news is that there are a number of techniques you can employ to help ensure that your ELMAH error log stays a reasonable size.
- Use error filtering.
- Setup a weekly job in SQL Server to delete entries older than, say, three months.
- Update the ELMAH_LogError stored procedure to delete old log entries.
Keep in mind that trimming the error log brings with it a tradeoff: you are removing error log entries that might be important for analysis later in time. If this is the case, if you think you might need to review that error log from more than 90 days in the past, then before deleting records from the error log you should archive them somewhere.
While these approaches are certainly good measures to implement, they don't handle the case where there's a flood of errors in a short amount of time. If ELMAH's error log is being inundated with errors from the past 24 hours, a script that deletes error log entries older than three months is going to have no effect.
An alternative approach is to delete all entries in ELMAH other than the most recently added N error log entries. This ensures that the error log never exceeds a maximum number of records (N), while keeping the N most recent records. The following query will do the trick:
DELETE FROM ELMAH_Error WHERE ErrorId NOT IN (SELECT TOP 1000 ErrorId FROM ELAMH_Error ORDER BY TimeUtc DESC)
The ErrorId column is the primary key in the ELMAH_Error table, and TimeUtc stores the UTC date/time the error was recorded. The subquery gets the first 1,000 ErrorId values ordered by the time the error was logged, from the most recently logged to the oldest. The query deletes all error records whose ErrorId values are not in that set of the 1,000 most recently added errors.
If you are using SQL Server 2005 or beyond, you can use the ROW_NUMBER() keyword in a query like so:
DELETE FROM ELMAH_Error WHERE ErrorId IN ( SELECT ErrorId FROM ( SELECT ErrorId, ROW_NUMBER() OVER(ORDER BY TimeUtc DESC) AS RowIndex FROM ELMAH_Error ) AS ErrorsWithRowNumbers WHERE RowIndex > 1000 )
The innermost query uses the ROW_NUMBER() keyword to assign a row number to each record from ELMAH_Error, numbering the most recently logged error 1, the next one 2, and so forth, such that the oldest error will have the largest row number assigned. This innermost query is used as a derived table. The query that uses it gets the ErrorId values whose row number is greater than 1,000, which returns those ErrorId values for errors that are “ranked” 1,001 or higher. In other words, it returns those ErrorId values for errors that are not one of the 1,000 most recently added errors. Finally, this set of ErrorIds are deleted from the table.
I ended up using the second query (the one with ROW_NUMBER()), placing it in the ELMAH_LogError stored procedure (along with a DELETE statement that removes any error log entries older than 3 weeks). If you use either one of these queries, consider adding an index on the TimeUtc column sorted in descending order.
Happy Programming!
|
|
|
|