Showing posts with label .net 4. Show all posts
Showing posts with label .net 4. Show all posts

Monday, November 15, 2010

WPF – An Overview

Ever since Windows Vista (sorry Microsoft, for reminding you of that product again) and .NET Framework 3.0 were released, the Windows client developer (the one who is intentionally unaware and exceedingly pleasured by ignoring JS, HTML, DHTML and other useless irrelevant terms in technology) was puzzled with an (frankly) unwanted choice that never existed for him before: continue using the ultimately productive Windows Forms framework, that has been the cornerstone of Windows client applications ever since Visual Basic (classic), or learn, explore and rewrite the apps in the WPF framework for building (what’s now become an overly exploited term in software development) next generation user experiences.

Microsoft has always assured (many consider it a curse) its developers of continued abundance of options and tooling support for all the major line of business applications that one develops. While this has obvious and much desired advantages, the real problem comes in at the start of the adoption phase of the new technology or framework. The earlier releases of the framework don’t (in almost all cases) provide a complete replacement of the previous technology and there is a very steep learning curve involved, with an exceedingly high cost and risk factor in recreating the missing bits, by extending the not so feature complete releases.

My personal approach while dealing with this new-technology-every-PDC kind of releases is fairly simple:

Version Action

Alpha/Beta/CTP or
v1.0

Just be aware, a new (yet again awesome, silver bullet kind of) technology has arrived!

v2.0

Seems interesting, lets look at the real benefits.

v3.0+

Use it (OMG, its actually awesome and the silver bullet for everything a MS developer ever needed)

WPF (codename Avalon) was launched with .NET Framework 3.0 and at its time of release, had a substandard support in terms of tooling. Mr. Reader, be informed, that this is not a WPF tutorial series on how to get started with WPF. The attempt is to dive (as deep as possible) into the architecture of WPF and to understand why things are the way they are in WPF.

Windows & Graphics: The primary technologies behind many Windows-based user interfaces, GDI (graphics device interface) and USER subsystems, were introduced with Windows 1.0 in 1985. The next major support for graphics came with OpenGL (created by Silicon Graphics) in early 1990s for doing advanced 2-D and 3-D graphics on both Windows and non-Windows based systems. In 1995, Microsoft introduced DirectX, for providing a new high performance alternative for 2-D graphics, input, sound, communications and eventually 3-D (with DirectX 2 in 1996). With Windows XP, GDI+ was introduced by adding support for alpha blending and gradient brushes, but ended up being slower due to its complexity and lack of hardware acceleration.

With the release of .NET (and the managed world) in 2002, Windows Forms (built on top of GDI+) became the primary way for a C# or Visual Basic developer, to create rich and compelling user interfaces for Windows based systems. Windows Forms has proved itself as a productive and successful technology, but it still suffers from the limitations of GDI+ and USER subsystems, when it comes to graphics, layouts and rendering.

Major Components of WPF

In the adjoining image, the major code for WPF are highlighted in red, and its interesting to note, that out of the three components (PresentationFramework, PresentationCore and MilCore), only MilCore is unmanaged. Milcore is written in unmanaged code in order to enable tight integration with DirectX. All display in WPF is done through the DirectX engine, allowing for efficient hardware and software rendering. WPF also required fine control over memory and execution. The composition engine in milcore is extremely performance sensitive, and required giving up many advantages of the CLR to gain performance.

The Dispatcher:The DispatcherObject acts as a base class for most objects in WPF and encapsulates the basic constructs for concurrency and threading. The Dispatcher is the messaging system of WPF, which acts similar to the Win32 message pump and uses User32 messages for performing cross thread calls.

Dependency Object and richer Property system: In WPF, properties are preferred over methods or events and this constitutes one of the primary philosophies of the WPF architecture. The property system in WPF is based on the DependencyObject which enables tracking of dependency properties and revalidating values when changes occur. Another feature of properties in WPF is the notion of “attached properties”, which enables composition and component reuse, one of the primary goals of WPF. With attached properties, any object can now specify the properties of other objects, enabling tighter composition.

Routed Events: WPF introduces Routed Events, which from an implementation perspective, is an object backed by an instance of the RoutedEvent class and processed by the event system. From a functional perspective, it is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event. Since WPF enables richer composition model, it was essential for the event system to be able to “bubble up” events, generally upward through the element tree, until it reaches the root. It is to be noted that in WPF, literally any control can act as a container control, unlike Windows Forms where container controls inherited from a different base class. To enable routed events, or event bubbling in Windows Forms, you would have to attach the same event to multiple elements, while in WPF, you could do that by attaching them to a single element.

XAML (Xml Application Markup Language): The current trend in programming languages (specifically Microsoft technologies) has been towards declarative rather than imperative, and there are underlying benefits to it. XAML typically allows you to create the entire application declaratively, enabling the decoupling of the UI with the logic, supporting unprecedented designer-developer collaboration.
XAML directly represents the instantiation of objects in a specific set of backing types defined in assemblies. This is unlike most other markup languages, which are typically an interpreted language without such a direct tie to a backing type system. XAML enables a workflow where separate parties can work on the UI and the logic of an application, using potentially different tools.” – MSDN

The intent of this post is to provide a starting point in understanding the complexities and terminologies associated with the WPF architecture. I wish and hope, the initial hesitation associated with moving to and understanding WPF, is eased after going through this post. As with any framework, the best way to learn and leverage it still remains to be writing applications using it!

Dispatch!

Sunday, March 14, 2010

Awaiting .NET 4

The .NET Framework version 4.0 is slated for release in April 2010 and everyone seems to be excited about it (everyone by definition includes everyone, so me too). Being the next big release of the framework, there exists number of enhancements and fusion of several new ways of writing old and new smart applications.
I sat down searching for what’s in it for me, the conventional (it’s the most reputable word I could afford for myself, corollary to calling bugs as exceptions) .NET developer for whom writing .NET code is not only about developing cool new smart applications (hardly get to do it thanks to the huge number of legacy and combo apps we need to upgrade day-in day-out) but also write that enlightening code quickly and smartly.
I have made an honest (as if honesty still exists?) attempt to compile what I felt was just so super cool changes to the framework or language in general. Let me #warn you not to expect the entire v4 enhancements from the lines that follow. That won’t ever happen (if I could do that MSDN would be hosted at my local desktop, right?).

1. StringBuilder.Clear(): I was surprised to see this as an addition to the v4 version, as all this time I had expected this member function to be omnipresent in the StringBuilder class (going by the superior and smart design of the .NET framework). Just recently while using it for dynamic html generation (I was using VB9 and still didn’t use VB XML Literals for some bizarre reason, which is indeed classified), I found the absence of this method. The workaround was setting the Length property to 0 which would then clear the contents of the StringBuilder object.
2. String.IsNullOrWhiteSpace(): As is eminent from the name of the method, it checks not only the Null or Empty content of the string object but also helps avoid the use of the Trim() method to make certain we don’t end up with a string of precious whitespaces. An authentic admittance though, I already had added my own extension method in my v3.5 extension methods repository that did verify the absence of both Null and Whitespaces before performing any further string operations and was aptly named String.HasValue(). I am indeed smart (I always knew this, but formally broadcasting it on this DateTime.Now).
3. ServiceProcessInstaller.DelayedAutoStart: While developing Smart Client applications it is a very common requirement to register the application to launch on Windows startup. However, as is eminent, too many applications loading on startup will upsurge the boot time significantly deteriorating the end user experience. This feature comes to the rescue by delaying the start of the application until all other auto-start services have already started.
4. SMTP Client enhancements: Some of the enhancements include enabling SSL mode in application configuration files, specifying heading encoding and most importantly, multiple replying to addresses through MailMessage.ReplyToList().
5. Guid.TryParse(): The TryParse method has now been added to the Guid, Version and Enum types and behaves exactly as its counterparts in other types.
6. 64Bit enhancements: Recognising the mainstream adoption of 64 bit systems the Environment class has been decorated with: Environment.Is64BitProcess and Environment.Is64BitOperatingSystem.
7. IEnumerable<T> everywhere: New overloads of String.Concat() and String.Join() now support IEnumerable elements so that you don’t have to convert them to strings prior to performing Join or Concat operations on them. Also enhanced are several System.IO members like the new File.ReadLines() which returns an IEnumerable<String> rather than a string array. This in turn gives superior performance benefits as its always (read mostly) desirable to read a file one line at time rather than loading the entire content in memory as in File.ReadAllLines().
8. Corrupted State Exceptions: How many times have I written the following?
try{
// Something that should fail, or else why did i incur this try cost, right?
}
catch(Exception ex)
{
// Never do anything here. Let them come back to me for fixes (guarantees job security)
}
In .NET 4.0, corrupted state exceptions will never be caught even if you specify a try… catch block. Even though this is a huge obstacle (a setback or even a crisis) on my attempts towards my job security, yet I welcome it as it encourages writing more stable (in theory) code. Before you start depreciating your intentions to upgrade to .NET 4 for this particular reason, there is a switch that allows you to get the old behavior back by setting the following attribute LegacyCorruptedStateExceptionsPolicy=true in the config file.
This behavior can also be enabled on individual methods with the following attribute:
[HandleProcessCorruptedStateExceptions]
9. System.Data.OracleClient: Before you plunge into thinking why MS shelled it’s resources to enhance OracleClient, instead of their own franchise SQL Server, there is a surprise awaiting you. OracleClient is available in .NET 4 but marked as deprecated. Don’t believe me? No need to, just help yourself by visiting http://blogs.msdn.com/adonet/archive/2009/06/15/system-data-oracleclient-update.aspx .
10. VB Auto Implemented Properties and C# Named and Optional Parameters: These are some of the language specific enhancements essentially following Microsoft’s strategy of co-evolving the two languages.
VB now has auto implemented properties thereby reducing the amount of code generated significantly (I hated VB Dev Center for not introducing it in VB9).
C# developers now stand equal by having named and optional parameters (which to me should have been there at least since v2 of the language).  

The list above was never meant to be exhaustive, it does not even attempt to touch the Parallel computing extensions and dynamic (or functional) enhancements to the framework, but it surely addresses most of us, the conventional .NET developers, writing managed code that manages our company, our clients and primarily us!

Happy Coding!