| |

WPF and Silverlight have a daunting learning curve. There's no doubt about it. All we can do is take one bite at a time and, eventually, we'll finish the elephant. I've talked about my approach to today's WPF/Silverlight tooling and a good intro to routed events and commands, but there's so much more. I haven't talked about dependency properties, but that's probably the second concept you'll have to grasp (before events/commands) as you ramp up on the wide world of XAML. I'm going to skip over it, for now, because I've found something else worth noting: how the value of dependency properties are determined. Obviously, if you don't understand the concepts behind dependency properties, you'll need to brush up, first.
Traditionally, determining the value of a property is simple: you get it's value (referred to as "local value" in WPF/Silverlight). That's it. A call to person.FirstName would return the value stored in the private person._firstName field. If it hasn't been set, then the default value of that type would be used. Simple. If we need to inject any custom logic here, we typically start by doing so in the accessor. For instance, if we want to ensure the value cannot be empty, we add a check to the setter. Things can (and will) get more complex, tho. For instance, we might have a need to allow others to add in their own validation. This would traditionally be handled by an event handler with a Person.FirstNameChanged event. For better or worse, this is all custom and has a lot of room for "creativity." WPF seeks to standardize this and adds a bit of a framework around dependency properties to do so. Determining the value of a dependency property is accomplished in a five-step process.
- Get
- Evaluate
- Animate
- Coerce
- Validate
For the most part, these are all pretty simple to understand. The first step is arguably the most complex, in my mind, because getting the base value isn't as simple as the aforementioned person.FirstName example.
1. Get the Base Value
Obviously, you need to know what value you're working with before you can proceed, but with features like templating and property inheritance, what the heck is the value!? In school, you had PEMDAS; in WPF you have... well, something a bit more detailed.
- Local value
- Style triggers
- Template triggers
- Style setters
- Theme style triggers
- Theme style setters
- Property value inheritance
- Default value
I'm not going to dig into each of these. I simply want to mention a few important aspects to keep in mind. First, "local value" refers to any call to DependencyObject.SetValue() (i.e. Height="123" in XAML or code or Canvas.Left="123" in XAML). The only other thing to concern yourself with, if you're a beginner to dependency properties, is the default value. Default values are not necessarily the same as that of the underlying type. For instance, FrameworkElement.Height has a default value of "NaN" (not a number), despite the fact that it's type, double, has a default of 0. Default types for dependency properties are set when the dependency property is registered.
2. Evaluate
If the value from step one derives from System.Windows.Expression, such as data bindings, WPF converts that to a real value. Pretty self-explanatory.
3. Animate
If the dependency property is currently being animated, the value we've retrieved/evaluated is pretty much ignored in favor of the value set by the animation.
4. Coerce
Next is the injection of custom code via the CoerceValueCallback delegate, if one is registered. Being custom code, you're really left to your imagination on what you can and should do here, but one common scenario is to ensure the value is within expected bounds.
5. Validate
Lastly, we inject one last bit of custom code via the ValidateValueCallback delegate, if one is registered. Validation returns a simple true of false, so there's not much you can do if you made it this far with a bad value. If validation fails, an exception is thrown. For this reason, be sure you take advantage of both coercion and validation, if you have a specific domain you're working in.

JetBrains started work on ReSharper 4.5 recently; but, more importantly, they just made nightly builds available online. I've said it before and I'll say it again: this is the best Visual Studio add-in I've seen... and I'm not the only one who thinks so. I'm a huge productivity geek and ReSharper helps feed my addiction to speed... as in quick. JetBrains won't give you drugs. Although, ReSharper may seem like it, when you work on a machine without it. Development without ReSharper is somewhat analogous to drug withdrawals... cold sweats, lots of twitching, and wondering if you'll be able to finish in time. Okay, maybe not, but I do dread life without it.

Every year, there's one underlying theme that seems to be pushed in the technology arena more than anything. This year, I feel like it's the year of the cloud. The last time I did this was five years ago, so I'll have to back-fill a few years, but here are the themes I've noticed over the past 11 years.
- 2008: Year of the Cloud
- 2007: Year of User Experience
- 2006: Year of AJAX/Web 2.0
- 2005: Year of SaaS
- 2004: Year of Offshore Outsourcing
- 2003: Year of the Architect
- 2002: Year of Web Services
- 2001: Year of XML/.NET
- 2000: Year of Enterprise Java
- 1999: Year of Linux
- 1998: Year of the Web
We've been approaching "the year of the cloud" for a while, now. You can actually look back to 1998, when the web started to really catch on. A few years later, as Java started to build momentum and then .NET hit the scenes, which is when XML as a standard communication language started to catch on. Also tied to the .NET release was a huge push for web services. As this was more and more successful, service-oriented architecture (SOA) started to boom. In my mind, that was a big boon to the outsourcing trends, which have seemingly quieted down a bit, but not completely. SOA also led to the software as a service (SaaS) trend, which triggered Microsoft's software plus services (S+S) push, but that was more of a side story. With everything moving to the web, backed by [typically open] services, asynchronous Javascript and XML (AJAX) was the next big push. This was tied to the "Web 2.0" moniker, which I'd argue wasn't quite what Tim Berners-Lee intended. Either way, this led to the big push for better user experiences, which many people confuse with user interface design. The Web 2.0 push also kept the industry on its web focus, which is where we are left today.
It's easy to look back and see how we got here. Trends show that architectural changes typically take two or three years to gain momentum in the community, so we'll probably have a couple of years before the next major architecture peaks. The trend towards distributed computing has grown more and more, but I have a feeling things are going to start coming back a little. We've been pushing out to the web for a lot of reasons; one of which is the rise of the Mac. What we've been losing out on, however, is the power of the desktop. I see the S+S push to continue, but more as an underlying theme than a strong focus. Services will continue to be the foundation, maintaining the importance of cloud computing, but the desktop will be where the processing occurs. I see Silverlight proving a huge success, which will eventually bring .NET to the Mac. This will probably bring Novell and Microsoft a little closer together, with respect to Microsoft's relationship with Mono, but this may simply be a change in focus for Mono. Oh, and when I say, "bring .NET to the Mac," I'm not talking about the scaled-down version in Silverlight. I'm talking about the real deal. I see WPF and Silverlight merging along with the smart client architecture built into .NET today. This will take more than a few years, but it seems to be inevitable. Most likely, by the time all this happens, multi-core will be a way of life, as opposed to the we-should-be-thinking-about-threading thoughts most developers have today. Armed with a strong multi-threaded foundation, which is easy to use, the combined WPF/Silverlight presentation tier will quickly overtake Flash and Air. By this time, we should also start to see more integration into our everyday lives...
Okay, I'm probably getting a little out of hand here. If I go much further, we're going to be on the USS Enterprise, so I'll stop while I'm ahead. I'll just leave it at, it'll be interesting to see what's next. My money's on the power of the desktop, which we've lost over the past 10 years.

I should start off by saying this isn't really about hard-core code generation. It's more about simplifying some of the more repetitive tasks we tend to do during development. In this instance, I needed to get 7 GUIDs to use in some test code. Sure, I could've use the Create GUID tool in Visual Studio, but what fun is that? Besides, I hate manual tasks and this tool would have forced me down a ~24 step process. No thanks. I'll stick to the 3 steps PowerShell can give me.
First thing's first, how do we create a GUID in PowerShell? I'm going to fall back to .NET for this one.
[Guid]::NewGuid()
If you run this, you'll get a blank line. What's up with that!? Admittedly, I'm not 100% sure why this is happening, but I have a pretty good guess. GUIDs are surrounded by curly-braces ({}), which are interpreted by PowerShell to be a script block. Putting 2 and 2 together, I'm assuming PowerShell thinks this is a script to run. Easy fix.
[Guid]::NewGuid().ToString()
That's it. The only other thing I had to do was add in my other formatting to create the GUID in code and slap that in a loop.
foreach ($i in 1..7) { 'new Guid("{0}")' -f [Guid]::NewGuid() }
You'll notice I opted to use the PowerShell shortcut syntax for string formatting. If you missed it, I talked about it as well as the static-method-calling syntax last week.
This tiny exercise reminded me of a pretty advanced Excel spreadsheet I created years ago because I was sick of typing the same bit of code over and over again. Since then, other tools, like GhostDoc and Resharper, have augmented my developer experience, enabling a much higher level of productivity than I had back then. Nonetheless, there is still room for improvement. This makes me wonder how much PowerShell could do for me with respect to code generation.

Someone I work with came to me recently and showed me an interesting bug. In Visual Studio, you can force a project to be built as 32- or 64-bit by going to the project properties Build tab and specifying the target platform. He did this and then proceeded to build the app. This put all the binaries in a \bin\x86 directory. WTF!? I tried it myself and -- not that I doubted him -- I got the same results. The build directory still had the previous value of \bin\Debug, so I found this odd. I changed the build directory to \__bin\Debug and guess what... that's exactly where it went. I thought this was odd, but remembered the IE7 bug on Windows Server 2003 I mentioned a few months back. I changed it back to \bin\Debug and everything worked like a charm.
It looks like changing the target platform changes the build location and, to get around that, change the build directory to something else, save the properties, and change it back. Annoying, but at least you only have to do this once. I went ahead and added this to Connect.
Symptoms
When opening a solution with a web project in Visual Studio, you receive the following error in a popup dialog:
System.Runtime.InteropServices.COMException
Cause
Apparently, this is an issue with IIS configuration. I'm not quite sure why we get such a useless error message, tho. Very annoying. If you're not sure you're seeing this with a web project, load the solution and, when the error pops up, look at the status bar. You should see a "loading" message with the path of the problematic solution.
Resolution
- Ignore the errors and let the solution load
- In the Solution Explorer, right-click on the project that failed to load, click Edit <project file>
- Scroll down to the bottom of the file and look for <UseIIS>True</UseIIS> (located at \Project\ProjectExtensions\VisualStudio\FlavorProperties\WebProjectProperties\UseIIS)
- Repace True with False
- Save and close the project file
- In the Solution Explorer, right-click on the project, click Reload Project
More Information
- Applies to: Visual Studio 2005, 2008

I'm a month and a half late, but the Resharper nightly builds are back! I guess I stopped checking after not seeing any movement for a while. I'm glad to see some activity, tho. This is the most beneficial add-in to Visual Studio I've seen; especially as a productivity geek. What I've been most surprised about is the overall quality of the nightly builds in the past 6 months. Simply outstanding. If you're asking yourself whether to give it a shot or not, I say go for it. You're likely to run into minor issues, but if my experiences are indicative of how well they manage their day-to-day development, this is a team with a very tight ship. I always grab the latest and try to update a few times a week, depending on what I'm in the middle of. If you're not quite as confident as I am, grab a "works here" release. I'm sure you'll see how great this tool is in relatively short time. An absolute must-have for all code-focused developers.

Nothing new here. I just wanted to save this code snippet because it's popped up a few times in the past year and I have to go find it over and over. At least this will make it a little easier for me. This is by no means an authoritative reference -- it's simply what I have used. If you know of something I'm missing, please let me know.
First, you'll need to import the Win32 LogonUser() function:
using System.Runtime.InteropServices;
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
The only question you probably have is about the logon type and provider parameters. The only provider I know of is the default, 0, which uses "negotiate" (Kerberos, then NTLM) for Windows XP/Server 2003 and later machines. Windows 2000 defaults to NTLM. If you don't know the difference, let me know and I'll explain that in more detail. Here are a list of logon types:
- Interactive (2) -- Intended for interactive use (duh) with something like terminal server or executing a remote shell. This type caches credentials for disconnected operations.
- Network (3) -- Intended for high performance servers to authenticate plain-text passwords.
- Batch (4) -- Intended for batch servers, which act on behalf of the user without his/her direct intervention. Typically used to process many plain-text auth attempts at a time.
- Service (5) -- Intended for service accounts, which have the "service" privilege enabled -- don't ask me what that is because I don't know.
- Unlock (7) -- Intended for GINA DLLs (whatever that is) that will interactively use the machine. This type includes some auditing.
- Clear Text (8) -- Intended for double-hop impersonation scenarios where credentials will be sent to the target server to allow it to also impersonate the user. As I understand it, this is what IIS "Basic" authentication uses. To perform a double-hop, you'll actually have to do a few other things. I won't get into that here, but let me know if that'd be of interest.
- New Credentials (9) -- Clones current credentials and uses new credentials for outbound connections. Supposedly, this doesn't work with the default provider -- it requires the WINNT50 provider, whatever that is.
The following is a list of the supported providers. I don't know anything about the non-default ones, but figured I'd list them for completeness..
- Default (0) -- "Negotiate" (Kerberos, then NTLM) for Windows XP/Server 2003 and later; NTLM for Windows
- NT 3.5 (1)
- NT 4.0 (2)
- NT 5.0 (3) -- Required for the "new credentials" logon type.
Next, well... just use it. As you can see, the last parameter in the LogonUser() function is an out parameter for a token which represents the user. This is key. All you need to do is initialize a WindowsIdentity instance with this token and you're well on your way.
using System.Security.Principal;
public static WindowsIdentity GetIdentity(string domain, string userName, string password)
{
IntPtr token;
bool success = LogonUser(userName, domain, password, 2, 0, out token);
return (success) ? new WindowsIdentity(token) : null;
}
Pretty simple. Of course, we still aren't there, yet. Now that you have the identity, you most likely want to impersonate it. Luckily, this is a simple 2-liner... well, technically two 1-liners. I should also say that, if you want to do impersonation with an already-obtained WindowsIdentity (and you don't have a password), you'll start here.
ImpersonationContext context = GetIdentity("mydomain", "me", "mypassword").Impersonate();
context.Undo();
That's it. Enjoy!
I just found something very useful in Visual Studio 2008 a few days ago. I've been using MSTest for about 2 years, now, and one thing I liked initially was the wizard that would generate test stubs for you. I liked that it gave you somewhere to start. After using it more and more, I began to hate it, tho. I guess the problem is I'm anal about how my code looks and I end up changing everything. So, I started generating the classes myself. The only problem with this approach is the private member accessor the wizard generates is no longer there. Not desirable, but there's an easy fix: run thru the wizard quickly and delete the methods. At least, that was until a few days ago. In VS08, all you need to do is open the file of the desired class, right click the background, select the Create Private Accessor menu item, and then pick the test project to add it to. VS has so many menu items, it's easy to overlook the really useful ones, so I figured this one was worth sharing. Hopefully, Sara Ford is listening.


David Kean mentions his thoughts on string handling and I have to say I completely disagree. He states that you should always return String.Empty instead of null. I hate this. An empty string and what equates to "no value," by definition, mean two different things. David, on the other hand, contends that the two should always be treated as the same. To be clear, I'm not saying the two should never be handled the same. On the contrary, I believe that's the norm... and rightfully so. With that, however, there are still cases where they need to be handled differently. Besides, the benefits you get from returning an empty string are immediately invalidated when considering consistency principles.
I'd even go as far as to say, returning empty strings promotes bad practices. Why? Because the developer then treats what is returned as a non-null value. While this isn't a problem, it typically goes further. The same developer will start assuming all methods that return strings act the same way. Let's not forget what they say about people who make assumptions... For this reason, I believe it's a good practice to always use String.IsNullOrEmpty() to validate string values, no matter what you think/know is returned.
I could list a number of what-if scenarios depicting why this is so important, but I won't. It should be pretty clear. Let's face it, we've all fallen victim to a null reference exception, which is essentially what happens when you assume a variable has a value. Clarify your assumptions with good exception handling.
Lastly, one other reason I like null over empty strings is because it uses less memory. Yes, this is very trivial, but it's true. The bottom line is that, whether you return null or empty string, you have to treat it as if it were null. For this reason alone, I believe it's cleaner to simply use null. Using empty strings is a hack, in my mind, unless it really means something different than "no value."
|
|
|
|