Windows 7 hasn't even been released (Currently RC1) and there is already buzz about Windows 8. Of course I know that in terms of development Windows 7 is in it’s stabilization phase so naturally the kernel team and perhaps even some others have started on the next generation of Windows software. I have spent a lot of time on MSDN’s Channel 9 looking at some of the low level design considerations that went into Windows 7 Kernel and there has been some indication that they have already started on the Windows 8 project.
This week my MCPMag.com news flash talked about Windows 8. There wasn’t much information to go on other than two job postings for the Windows 8 team and a blog post that included some tantalizing video of possible UI for Windows 8. This concept design is incredibly cool! My favorite part is that they completely re-designed Windows Explorer which was in worse need of a makeover than Susan Boyle!
From what I could tell in the short video, some of the new design concepts included:
- New Windows Explorer Interface- Makes it easier to switch between views (a pain in Vista) and allows you to find the information you need about a file.
- New Start bar and Taskbar- There is already a new taskbar in Windows 7, but I’m not sure if I really like it. It’s impossible to tell the difference between a program that is running and a quick launch button. The new design concept for Windows 8 is obviously based on the Windows 7 design but looked more friendly to use. My favorite part? You can re-arrange the tabs. This is really awesome if your OC like I am and expect tabs to be in certain places. The new design focuses on screen real-estate and has a very minimalistic feel to it. It looks amazing!
- There is a new feature that will allow a shortcut to launch multiple programs at once. I don’t think I would ever use this but if I were say a customer service person who had to have 10 apps open all at once it might be nice to have this for after I rebooted the machine.
- Multiple current users- It looked from the video like you may be able to quickly switch between user sessions & desktops. You can kind of do this in Windows XP Pro, but it feels more like you are logging out and logging back in as someone else. This feature kind of looked like I could switch to a new desktop as easily as I can switch between two running applications.
- The notification area is smaller and sexier! It is small and looks like most of your nuisance/superfluous notification icons are hidden by default.
Here is the Video of the Windows 8 Concept UI:
Copenhagen User Experience from
Copenhagen Concept on
Vimeo. I think Microsoft has the right concept going with this kind of publicity. While Windows Vista isn’t a great user experience (It’s pretty, but less usable) it has a lot of enhancements under the hood. Enhancements that make a big difference to a user like me. They have learned their lesson from Vista and Windows 7 is all about user experience and some minor enhancements under the hood. There is no information available about what kind of enhancements are in store for Windows 8 other than we do know that it is still based on the Vista / Windows 7 Kernel. I just hope that Windows 8 has the right mix of usability improvements, kernel / system improvements, and features that create an ROI (Return On Investment) so it’s easier for businesses to justify the upgrade.
Here are some screen shots of Windows 8. I took them from the video in case you didn’t want to watch that.
One of the headlines on my news feed came across about anti-tax ‘tea parties’ being held across the U.S. These demonstrations are a form of protest to wasteful government spending. I was quite disappointed that the article included a blurb that in my opinion threatened the neutrality of the article. The paragraph stated that this event “[has] been co-opted by the Republican Party.” It then goes on to try to discredit the official Tax Day Tea Party website by accusing the website owner of being a conservative, as if somehow that is a bad thing.
Deficit Spending and the National Debt
The protests and the demonstrations aside, I do think it's maybe not so much about taxes but more about Government spending and entitlement programs. People in the forum were quick to note that the 2008 tax year is a President Bush legacy. Former President Bush really ran up a deficit so he is not guilt free.
Nearly all of the states in the US are prevented from deficit spending by their state constitutions and that means that while states have to make some very difficult decisions in years like 2008 & 2009, they can be very efficient in the recovery years and hopefully build up a reserve of cash for next time.
The Federal Government, on the other hand, can pretty much incur as much debt as it wants. This is not a good idea and I maintain that the constitution should be amended to prohibit deficit spending. Think of it this way; lets say that we spend $100 billion deficit for healthcare. That is a $100 billion loan, right? Okay, lets be conservative here and say that the US Government gets the amazing rate of 1.5% on that loan. Lets also assume that it’s going to take us 10 years to pay that loan back, which is very optimistic as we have to stop borrowing before we pay anything back.
This means that for the $100 billion we borrowed to pay that bill we will be paying $897,914,997.95 / month or $10.77 billion / year for the next ten years. I actually had to write a special calculator to amortize that amount – no online calculator could handle it! If we continue deficit spending we will in effect be paying more for less as all of the tax revenue has to be applied toward the debt first and social programs last. Debt is a lot like barnacles on a ship, the more of them you have the more drag you have and it takes more “wind” to move you places. Get too many and you might as well have stayed on the doc because your not really going anywhere.
Of course we know that our current proposed deficit is $1.7 trillion which works out to be $15 Billion / month or $183 Billion / year. Remember, this is just to pay for one year of deficit spending. Our current national debt is ~$11.17 trillion dollars, as of 4/15/09. That means that we are now paying $100 billion / month or $1.2 trillion / year to make payments on the national debt! That is $3.2 billion / day, $137 million / hour, $2.2 million / min, and $38 thousand per second! In 2008 the national debt climbed to 73% of GDP (source: Wikipedia). The $100 Billion we borrowed for our experiment here may seem like a drop in the bucket compared to the national debt but every little bit counts.
This country is literally putting bills on the credit card and it’s only a matter of time before we run out of money. The longer we wait to fix the problem the more money we end up borrowing and the more painful it is going to be. Imagine if we had to cut out Medicare, Medicaid, and Social Security AND raise taxes? This is not impossible and could happen. The bottom line is that you can not borrow yourself into prosperity! It is completely irresponsible to borrow money to create social entitlement programs!
Personal Retirement Accounts
I don't want Social Security, but I have no choice but to pay it and there is little chance that there will be anything for me to collect when I reach retirement age. Any personal retirement I do save for is taxed so heavily it can't even keep up with inflation! That is absurd! I would really like to opt out of Social Security and put that money in my retirement account tax-free, but even if I have to pay it, I still need to be able to save for my retirement tax-free. Just to keep pace with inflation.
If I were to reform retirement, I would create something called a Personal Retirement Account (PRA). This would be an alternative to the current Social Security program and would allow people to save for their own retirements tax-free.
The basis would be a function as such:
( (Inflation Base * 100,000) / (Age / Retirement Age) = Maximum Annual Contribution )
Inflation Base is the percentage of inflation since the bill passed. If the bill passed in 2009 and inflation for that year was 3.0% then in 2010 the number is 3.0%, then in 2010 if it rose by 2%, the rate is then 5%.
The idea behind my PRA idea are these simple axioms:
- The closer to retirement you are the more money you should be allowed to save for retirement. Conversely, the younger you are the less you need to put away as the money should grow over time and is tax free.
- Taxes should not be levied on the sums of money being put into these accounts.
- Taxes should not be levied on the sums of money being withdrawn from these accounts if done so within the bounds of the rules of the accounts.
- The current rate of $100k / year is a comfortable amount of money to live on.
- The amount you are allowed to contribute should be adjusted annually for inflation.
- If you would like to save more money than the maximum annual contribution amount, then taxes should be paid up front (much like an Roth IRA).
- There needs to be some rules to limit risk to accounts of individuals that are closer to retirement.
- Participation in a retirement program becomes mandatory once a worker turns 30. They may either opt for traditional Social Security or Personal Retirement Accounts. The minimum amount for the Personal Retirement Accounts plan is the current social security withholding amount.
- You should be able to switch between the two programs. If you are switching from Social Security then the amount contributed should be put toward the Personal Retirement Account Plan – no interest accrued. If you switch to Social Security then your account is transferred but you do not get additional benefits and must pay if the value of your account is less than the cumulative Social Security contribution amount.
- Because these retirement accounts are tax-free, the money should be invested more conservatively to mitigate risk.
- Retirement Age should be between 55 and 65 years old.
- It’s in the best interest of our society to have people financially prepared for retirement. This is why the accounts should always remain tax-free.
Summary
The problem with entitlement programs, such as Social Security, Medicare, Medicaid, etc. is that they are never run efficiently and the completely eliminate peoples ability to choose something that works better for them. They take away from people the ability to dictate our own futures and supplant it with a poor-at-best replacement.
I lived in the UK for two years where medical care is fully socialized. I can vouch first hand that while they do not have the same problems as Americans they do envy the quality of American Health Care. Indeed, I believe that the level of health care provided in America is the envy of the world. Rather than fixing problems like ER wait time, cost, etc. nationalization will add to the national deficit and would lower the quality of health care across the board.
Once we socialize medical care we will never be able to get rid of it, and I don't think most people are going to like what they are going to get. President Obama may not completely nationalize the health care system this go around but he's going to get enough of a foot in the door that the only option for future presidents is going to be full nationalization.
We need to seek to find answers to social problems that are efficient, accountable, optional, sustainable, and above all, responsible.
It may come as no surprise to those who know me that I have recently confirmed that I am certifiable! After all, when you have been doing what I do for as long as I have been doing it it’s hard not to be affected. It happens to a very large number of people in my field and that number continues to grow.
Although I have been certified before, after some exhausting battery of examinations, this online examination is nice as I can quickly determine my status even if there is some kind of doubt – just for my minds sake.
Thanks to Microsoft there is now an online tool to check your IT status as Certifiable! What, you thought I meant mentally unfit or crazy? Nope, I’m talking about the uber-geeky Microsoft Certifications. For some time now they have had the Measure Up practice tests for study preparation, but now there is a new skill-building tool, Are You Certifiable. Rather than a boring, dry, practice test this new site is a game show!
This actually makes a lot of sense to me because when I was Microsoft Certification Coordinator for STG I found the best way to get the material to sink-in was to have fun with it. That usually included some form of study group Jeopardy. Facts just don’t sink in as well when your mind is not very stimulated and some of the questions can be quite dry.
Here is a screen shot of me capturing the high score for guests. It will ask you if you are an IT professional or a Developer and gives you questions relevant to your position. The questions vary greatly and it takes a very well-rounded skill set to do really well, but it’s fun regardless.
My only critique is that it is not practical to practice for a specific certification test you plan to take because you don’t get to pick which topics or banks of questions you get. It is a lot of fun and has some great “thinking music”! Leave a comment if you happen to beat my score.
I would like to also mention that it is built using Silverlight 2.0 as it is a great example of the power of Silverlight.
Links
It's time for another episode of Good Idea / Bad Idea:
Good Idea! Catching a specific exception from a suspect numeric conversion and showing a polite input error message.
Bad Idea! Catching all exceptions and "swallowing" the exception.
Okay, so it's not as funny as it is on Animaniacs, but true none-the-less.
Exception Handling in C#
In terms of exception handling I am a big fan of "catch it only if you can do something with it" and/or "catch it only if you mean it". Putting a try / catch around every method makes debugging very difficult and can leave your application in an unexpected state. Besides the code is less readable, more complex, and slower performing.
Before I get in to good practices, lets review some bad ones. The first and most obvious is throwing away exceptions (without regard to what they are). Example:
// Anti-pattern #1: Throw away the exception
private void button1_Click(object sender, EventArgs e) {
try {
AddPerson(new Person() { Name = txtName.Text });
} catch { }
}
Another example of what not to do is what I call the “catch just because” pattern. Example:
// Anti-pattern #2: Needless Try / Catch
private void DoStuff(string shipping) {
try {
// Call down to middle tier to do the shipping calculation
decimal ShippingCost = MyApi.Shipping.GetShippingCost(orderNum);
} catch (Exception ex) {
throw ex;
}
}
// Needless Try / Catch
private void button2_Click(object sender, EventArgs e) {
try {
// CalculateShipping has it's own Try / Catch; see below.
CalculateShipping();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
There are multiple problems with the second example. First, there was no reason for “DoStuff” to catch the exception if all it was going to do was re-throw any exception it encountered. Second, “DoStuff” is catching any exception rather than limiting the scope to the kinds of exceptions it might expect like “Unknown Zipcode”, “Order not found”, etc. Next, the “button2_Click” is catching any exception and showing the raw message.
Rather than showing the exception message which is only part of the clues given in the exception object you should either show a user-friendly message indicating the kind of error that has taken place and save the exception information for later debugging. Alternatively, you can show ex.ToString() which will show you all information in the exception class. This is very unimpressive for end-user applications but can be acceptable with internal corporate apps and a simple screen shot will give you the information you need to find and take care of the problem.
Remember, an exception doesn’t necessarily mean that there is a bug in the software. If you do show a user an “unfriendly” exception message they will immediately think that the software has a bug when the issue could be as simple as the network is down or a database is temporarily unavailable. I always recommend taking the time to display user-friendly messages and saving the exception information elsewhere.
In the next section I will show some good examples on what "layer" to catch and/or re-throw an exception.
Presentation Layer
Personally I think that any event here should catch any/all expected exceptions and show them in a user-friendly manor. Notice I said "expected exceptions", this could be pretty vague unless you have an design pattern in place for exceptions in your applications so I'd start with that. One way to start is to make some "base" exceptions like "DataException", "ValidationException", "InputException", etc. More specific types of exceptions can be derived from these.
When do you make a new type of exception? Well, the exception should have the information needed to solve the problem. Stack traces and exception information are like clues; leave your self a breadcrumb trail to follow later. Throwing an ApplicationException because you couldn't connect to the database isn't very helpful.
It is also acceptable to use pre-defined / framework exception types when appropriate. For example:
public void DivideMyObjects(MyObjectType o1, MyOtherObjectType o2)
{
if (o1 == null || o2 == null)
throw new NullReferenceException(
"The numerator or the denominator cannot be null!");
if (o2.Value == 0)
throw new DivideByZeroException(
"Denominator may not be zero!");
if (o1.Value == null)
throw new ArgumentException(
"There is no value for the numerator");
...
}
You may notice in the code example above that a null reference may occur organically. I am a strong believer in organic exceptions as good practice. I define an organic exception as an error that is thrown by the Framework. The only exception to that rule is when there isn’t enough information from that exception to track down the problem. Remember, you need to leave yourself enough clues that you should be able to know what is wrong from the exception information given rather than expecting users to be able to remember what steps led up to the exception. Few, if any, end users will be able to help you reproduce any particular error. If this can’t be accomplished by an organic exception then you may want to re-throw that exception with the appropriate information and/or change the type of the exception to be more appropriate for the callers.
// Presentation Layer Good Example
private void Calculate_Shipping(object sender, EventArgs e) {
try {
decimal shippingCost = MyApi.Shipping.CalculateShipping(order);
txtShippingCost.Text = shippingCost.ToString("C");
} catch (UnknownZipcode uzipEx) {
// Specific
MessageBox.Show(
"Could not locate shipping information for this zip code!");
btnSave.Enabled = false;
} catch (ShippingException shipEx) {
// Less specific, but still helpful to the user.
MessageBox.Show("Unable to calculate shipping!"
+ Environment.NewLine +
shipEx.Message);
MyLogging.Log(shipEx);
} catch (Exception ex) {
MessageBox.Show(
"An unknown error has occured, Please report this error");
MyLogging.Log(ex);
Close();
}
}
In general you are pretty safe catching exceptions in the presentation layer. The only real thing to watch out for here is that your control states don’t become invalid because an exception is caught but the event still altered the state. For example, if a call to “Calculate_Shipping” throws an exception you will want to be careful to invalidate the shipping cost control and disable the “save order” button.
You will notice in the code above that I did catch generic exception. The presentation layer is usually okay doing this so long as it is taking adequate measures to protect application integrity. You will notice that I am closing the order form if I get an exception back that that is unknown. Of course this will give you plenty of motivation to make sure you know what kinds of exceptions are expected as end users will generally hate having their order forms close. You may be tempted to leave the form open or take lesser action but it is very important that you keep application integrity. Otherwise you will spend your life chasing down un-reproducible bugs.
Middle Layer
Most of your code should end up being middle layer code. We want the presentation layer to be as light as possible! The middle layer should act as the API of the application. Anything that the application “does” this layer should do it either directly or indirectly. In this sense the middle layer needs to be very up front in which exceptions are possible from any given call.
Take for example a method call in the middle layer that inserts a new customer into the database. Because you use the database objects you are exposed to any exceptions that are possible from the objects that you use such as SqlExceptions. You will either need to publish that you are going to allow SqlExceptions to be bubble through this API or you need to catch the expected exceptions from those objects and throw your own brand of exception.
Here is an example of publishing the exceptions that are known to be thrown:
// Middle Layer Exceptions
/// <summary>
/// Calculates shipping for a given order
/// </summary>
/// <param name="order">The order to calculate shipping for</param>
/// <returns>the shipping amount applied to the order</returns>
/// <exception cref="UnknownZipcode">Unknown Zip Code / Zip Not Found</exception>
/// <exception cref="BadWeightException">The weight of the order is zero or unknown</exception>
public decimal CalculateShipping(Order order) {
...
}
Simply using ndoc XML style comments will give the consumer of the API enough information to make good decisions regarding the use of exception handling from the intellisense.
Another thing you should avoid while designing your middle tier is the use of exceptions as “message handling” in non-exceptional cases. Remember, the reason you are throwing an exception is because something happened that was catastrophic enough that you were unable to continue with the normal flow of the method. I admit that there is still a lot of gray area here. Some of that gray area can be demonstrated in the sample code already shown. For example, rather than throwing an exception in the “CalculateShipping” method we could refactor so an exception wouldn't be necessary. Anytime this can be done cleanly I usually opt for these types of changes.
- Refactor to return a ShippingResult class that contains information about the calculation along with the rate. Such information could include whether it was able to successfully get a shipping rate.
- Create a ValidateShippingAddress method that looks up the address before the calculate shipping is run. It could return true if we know we can get shipping information for that address.
- We could pass back a nullable decimal result. A null return would indicate a failure to retrieve shipping information. We would want to make sure it was clear in our ndoc comments that this is why the value is nullable.
- We could pass pack a zero or negative result. Again, making sure this behavior is documented.
- We could implement the “Get Last Error” pattern; though at this point I’d rather see an exception.
Another question I am often asked is “When is it appropriate to re-throw an exception”. The answer to that questions is, of course, it depends. The next few sections will discuss some of these nuances of this question.
Bottom Layer
The bottom layer of an application could be a database layer, a Framework of some sort but the philosophy is very different from the middle layer. As the bottom layers deal with primitive classes and data and as such can stick pretty well to exception handling ideals. One of the big differences is that you won’t be using nearly as many user defined exception types. It is not taboo to use a user defined type in a Framework layer but it’s just likely to be unnecessary. The difficulty here is the exception message that you are going to pass along. There could be any number of middle layer calls that call your method so by nature these messages are going to be far more generic. Generic, however, does not mean it can’t be insightful. You should include as much information as possible about the exception and the data that caused the exception. Take the two following exception statements:
- “Invalid DateTime”
- “The date ‘4/11/2089’ is an invalid birth date! The date cannot be in the future!”
The first exception tells us that there is an invalid date time but other than a stack trace gives us no other information. The second exception is extremely helpful and specific, including as many clues as possible. The user may have entered the value ‘4/11/89’ and the computer may have just assumed the wrong century. The first error message would cause greater confusion whereas the second, if the user were to see that message, could be helpful.
Summary
Of course there are lots of different ideas and philosophies on exception handling so you need to do what makes sense for your project. Simply avoiding the two anti-patterns on the top of this blog will improve your code a lot. MY ONE LAST PEICE OF ADVIECE IS THAT SOMETIMES YOU REALLY WANT TO USE A DEBUG.ASSERT RATHER THAN AN EXCEPTION! The advantage of the assertion is that only debug builds show these messages. This is good for testing scenarios in which you want to be aware of a certain condition but it’s not necessarily an exception.
Links:
I’m not easily impressed by even the best of software. There is usually some little thing that ruins my user experience. I tell you this so you know that what I say next is something special. Visual NDepend is AWESOME! Everything meet or far exceeded my expectations! If you are not yet running this software, you should be! This is not one of those ‘nice to have’ pieces of software like you might thing. This is a must have! If Microsoft was smart they would do everything they could to package this in with Visual Studio 2010.
What does it do? It’s hard to answer that question in a paragraph or two. The basic answer is that it gives you a set of different representations of your software in such a way that you can understand the architecture and complexity. This can be a huge help before undertaking large refactor efforts. It also gives you an idea or the quality of the code based off of some metrics. This quality score can be a really good indicator of wither your code is going to be maintainable and if it’s not it can help you get it there. Before I go through the quick walkthrough of the software it’s self I’ll just say this – If you’re not paying attention to code metrics and the maintainability of the code from the earliest stages of development your likely not going to develop code that is easy to maintain. And as you probably know, software maintenance is usually more than 3/4ths the cost of the software lifecycle. Therefore, if you can get a build process established early and use a tool like NDepend to keep a close watch on some important metrics I can guarantee you will be creating much higher quality software than you would have otherwise.
Installation Experience
This is the best kind of install – you simply unzip the files. I bet you didn’t think I would do a whole section on install when there is nothing to the install. I suppose if it were any other product there would be a lot under this section.
Analyze a Project
The user interface is very intuitive. I installed integration with Visual Studio 2008 and .NET Reflector with minimal effort and started to analyze my assembly.
It took a while to analyze but this particular assembly is quite large! It also pulls in any referenced assemblies so the graph can be complete. It allows you to specify multiple assemblies just in case you have sets of assemblies in the same project that have no direct relationship. In this case I had a WCF service that would need to be added separately as it’s technically not a direct dependency. Once the analysis is complete it’s INFORMATION OVERLOAD!
Results
There are six or seven main results to view. The most obvious is the bubble chart at the top. This gives you a visual representation of different aspects of the code. For example it’s currently set to Method level and the metric shown is number of lines of code. the larger the bubble, the larger the method is in relation to the others. I can select from Method, Field, Type, Namespace or Assembly. In addition there are 11 different metrics that you can plot in the bubble chart.
The next thing you notice is the dependency graph. Unfortunately this project doesn’t have a dependency graph like in my other blog post. Visual Studio makes it really tough to make circular dependencies but it is possible to create them if not all of your projects are loaded into the same solution. And as I said in the other post, circular dependencies are very bad! It’s also good to know what references what. You might be surprised to see what kind of references get worked in over time. On a recent project the data layer code kept working it’s way up to the UI even though it didn’t belong there.
The next section is the code metric-centric part. This is my most favorite portion of the results generated and can be a real good indicator of how maintainable a codebase is. Of course it’s impossible to avoid all complexities in software so you probably can’t have a perfect score with every project but you can use this information to figure out what kinds of habits you have that contribute to un-maintainable code. As you can see from the image below when you select a metric it is highlighted in the bubble chart. In fact, all of these reports are “active” so anything that is relevant to another will be indicated. By the way, this application has amazing performance. I’m pretty sure it’s using WPF under the hood.
Another really cool feature is the Dependency Matrix. This takes some practice to use but it helps identify which pieces of which assemblies access pieces of other assemblies. Again, great for refactoring efforts and a good indication of how an application is put together. You may have to stair at the image below for a while to figure out what it’s trying to tell you but after a while it makes perfect sense.
Last, but certainly not least is the comprehensive report compiled into HTML. This is the kind of thing that I’d love to see emailed to me each day, so I hope it’s easy to put this into a build process. The report is awesome! My favorite part of the software and I really like this software. Below is the screen shot of the table of contents that is generated at the top.
The only feature I didn’t get a chance to try is code coverage results. I would have loved to see that in action! Too bad I don’t have a project with very good code coverage results and I’d be embarrassed to find out anything in detail about my code coverage. Of course code coverage isn’t everything but it is a useful tool when taken into context and can be made more useful with nDepend.
Overall, I would give this software very high marks! I can’t wait to make this part of my build process! It is worth the time and money!
Links:
I fell in love with WPF the first time I saw it in action! WPF is a thing of pure beauty! Anyway, from the second I saw how the data binding worked I knew that there was going to be a lot to figure out there! It also seems as though there is no real data binding expert -- or the experts don't blog too much about it. I created my XAML Cheat Sheet shortly after feeling like I had some kind of grasp on the concept. It is still a great reference for basic bindings, but when you are real serious about binding you'll have to do better than that.
So I have been working on a project in my spare time called SmartForms 2.0 (more on that later) and I have had to do some very difficult things using bindings. In my previous experience with WPF I would either create a cleaver type converter and/or just give up and set the value/state of the controls in code (eww!). This time is different and I have to make data binding work.
Example #1
Lets say that you need to bind a bool? (nullable boolean) type to a checkbox.
<CheckBox IsChecked="{Binding SomeBooleanField}">Checkbox</CheckBox>
Produces:
You will notice that the checkbox is in a neither checked nor unchecked state. Setting IsThreeState="False" doesn't help you as it is false by default. I want the checkebox to be unchecked by default but have no control over the type or the initialization of the type. Check this out:
<CheckBox IsChecked="{Binding SomeBooleanField,
TargetNullValue=false}">
Checkbox
</CheckBox>
And now we have normal looking checkboxes! The best part is that this method doesn't mutate our property. This was exactly what I was looking for!
Example #2
The following XAML is pretty straight forward. It is simply a text box that we expect to put a city into.
<StackPanel Width="130" Height="40" HorizontalAlignment="Left"
VerticalAlignment="Top">
<TextBlock>City</TextBlock>
<TextBox Text="{Binding SomeTextField}" />
</StackPanel>
Produces:
What if the item we are attempting to data bind to is not available. It's not going to be null, the binding will just fail. This should work well:
<StackPanel Width="130" Height="40" HorizontalAlignment="Left"
VerticalAlignment="Top">
<TextBlock>City</TextBlock>
<TextBox Text="{Binding SomeTextField,
FallbackValue=UNBOUND}" />
</StackPanel>
Produces:
Example #3
This is a much more common occurrence. You have a number that you need to format in a textbox. This example shows the decimal value with no real format at all.
<StackPanel Width="130" Height="40" HorizontalAlignment="Left"
VerticalAlignment="Top">
<TextBlock>Cost</TextBlock>
<TextBox Text="{Binding SomeDecimalField}" />
</StackPanel>
Produces:
There are a few ways to get the format we desire. The first example uses a static resource:
xmlns:clr="clr-namespace:System;assembly=mscorlib"
<StackPanel Width="130" Height="40" HorizontalAlignment="Left"
VerticalAlignment="Top">
<StackPanel.Resources>
<clr:String x:Key="formatStr">{0:C}</clr:String>
</StackPanel.Resources>
<TextBlock>Cost</TextBlock>
<TextBox Text="{Binding SomeDecimalField,
StringFormat={StaticResource formatStr}}" />
</StackPanel>
You can put the string inline but it looks really funny and for some reason the there has to be a non-whitespace character before the formatting expression which you may not want:
<TextBox Text="{Binding SomeDecimalField,
StringFormat=Cost: {0:C}}" />
This formats the string to look like "Cost: $1,2398.00". You can see how that could cause lots of confusion and would be undesirable. There is a way we can get the binding to work a little better:
<TextBox Text="{Binding SomeDecimalField,
StringFormat={}{0:C}}" />
OR
<TextBox>
<TextBox.Text>
<Binding Path="SomeDecimalField"
StringFormat="{}{0:C}" />
</TextBox.Text>
</TextBox>
The result is a nicely formatted output:
Notice how the binding was applied? This is how you apply MultiBindings which is the next topic.
Example #4
What if you want the value of one or more fields to exist in a single binding? That is where MultiBindings shine! Check out this very easy example:
<StackPanel Width="130" Height="40" HorizontalAlignment="Left"
VerticalAlignment="Top">
<TextBlock>Name</TextBlock>
<TextBox>
<TextBox.Text>
<MultiBinding StringFormat="{}{0}, {1}">
<Binding Path="LastName" />
<Binding Path="FirstName" />
</MultiBinding>
</TextBox.Text>
</TextBox>
</StackPanel>
Results:
Example #5
Validation can happen at the point of binding. This can be handy if the objects you are binding to have logic built in. For example, lets say you have a property for birth date. Obviously the person can not be born in the future! Here is how we avoid such rotten input!
public DateTime birthdate;
public DateTime BrithDate {
get { return birthdate; }
set {
if (value > DateTime.Today)
throw new ArgumentException(
"Person can not be born in the future!");
birthdate = value;
}
}
And the XAML:
<StackPanel Margin="5" Width="130" Height="40"
HorizontalAlignment="Left"
VerticalAlignment="Top">
<TextBlock>Birthdate</TextBlock>
<TextBox Text="{Binding BrithDate,
Mode=TwoWay,
StringFormat=d,
NotifyOnValidationError=true,
ValidatesOnExceptions=true}" />
</StackPanel>
Result:
The error can also be styled if required. Shown is the default style (nothing custom).
Example #6
The last example is for something called PriorityBinding. This is poorly named in my opinion as it would be better called CascadingBinding. The point to PriorityBinding is to name multiple data bindings in order of most desirable to least desirable. This way if the first binding fails, is empty and/or default, another binding can take it's place. You may have to be a little imaginative to think of such a scenario, but this kind of thing could be useful so I'm glad it's there. Just for fun, I am using the IsAsync field as well. This tells WPF to use a thread other than the GUI thread to retrieve this property. This is important for properties that take a long time to return as it will leave your app unresponsive until the value is bound. In the case of this example without that attribute the window will not show until the 5 seconds had elapsed.
private string fname;
public string FirstName {
get {
Thread.Sleep(5000);
return fname;
}
set { fname = value; }
}
Xaml:
<StackPanel Margin="5" Width="130" Height="40"
HorizontalAlignment="Left"
VerticalAlignment="Top">
<TextBlock>Name</TextBlock>
<TextBox>
<TextBox.Text>
<PriorityBinding>
<Binding Path="LastNameNonExistant"
IsAsync="True" />
<Binding Path="FirstName"
IsAsync="True" />
</PriorityBinding>
</TextBox.Text>
</TextBox>
</StackPanel>
Result:
Another neat little thing to know is that the Hierarchy for Binding is Binding -> BindingBase -> MarkupExtension -> Object. Unlike much of the rest of the .NET Framework you can actually inherit from any of these classes and provide support for your customized binding needs. That is exactly what I am doing for SmartForms 2.0! I created a binding class called DataBinding and it looks a little like this:
xmlns:db="clr-namespace:SmartForms2.Binding;assembly=SmartForms2"
<TextBox Name="firstName" Width="175"
Text="{db:DataBinding Data, DataSource=DB1}" />
My DataBinding class inherits directly from MarkupExtension so all I had to do is implement the abstract method ProvideValue.
Links:
This post has been sitting in my drafts for months! Because my friend Phil just posted his post on Lambda Expressions I'll simply link to his post and present the rest of this as supplemental examples.
// Delegates
// My Blog Engine is having trouble showing these so there may be some extra spaces
public delegate IntMathExpression (int x, int y);
public delegate IntMathExpressionSingle (int x);
public delegate FloatMathExpression (float x, float y);
// Basic Lamda Expression
IntMathExpression a = (int x, int y) => x * y;
IntMathExpression b = (int alpha, int brovo) => alpha * brovo;
IntMathExpressionSingle c = (int x) => x * x;
// "such that" =>
// Parameters => function body
// (param1, param2) => param1 + param2
// Lamda Expression using Type Inference
FloatMathExpression d = (x, y) => x + 3.14f * y;
// There is usually no need for custom delegates
Func<float, float, float> e = (x, y) => x * 100.0f + y;
// Example using a lamda expression
List<int> primes = new List<int>() { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 };
var p = primes.Where( prime => prime.ToString().EndsWith( "3" ) );
// Deferred Execution
foreach (int i in p) {
MessageBox.Show(i.ToString());
}
// Query Expression Format
var p2 = from prime in primes
where prime.ToString().EndsWith("3")
select prime;
List<int> results = p2.ToList();
// Lamda Expressions mixed with Extension Methods
List<string> str = new List<string>() { "The Lord of the Rings", "Star Wars, Eposode III", "Ratatouille" };
var p3 = from movie in str
where movie.CountVowels() > 5
select movie;
List<string> movieResults = p3.ToList();
There are things that people do that are in poor taste. Some things that come to mind is scavenging at the dump (yeah, I saw this guy do that one time), yelling at the waitress for onions on your burger, or leaving the lavatory without property sanitizing your hands. If you do any of those things you are likely guilty of poor taste.
Now, I don't really like Bush nor do I like Obama but I do show proper respect to both of these individuals. Being a Republican without a party I tend to starkly disagree with much of President Obama's platform. I understand that many people have a lot of pent up emotion and anger toward the decisions the previous administration has made. Personally I have much of it toward both former President Bush and President Obama, but there is absolutely no way I would ever boo either of them at the inaugural ceremony! Apparently many of those in attendance choose to boo anytime President Bush and Vice President Cheney where shown on the screen. Having recently undergone back surgery, Vice President Cheney was in a wheel chair for heavens sakes!
I have personally never been to an inauguration, but I should think that the kind of patriotic atmosphere that exists would prohibit such disgustingly undignified acts. To those who choose to boo, you have none of my respect! I place you below the people who use profane language, below people who put gum under restaurant tables, below people who throw lit cigarettes out the window, and even below people spit on the ground while indoors. You people have no sense of taste and could never earn respect from anyone who does.
There have been a lot of buzz around Windows 7 lately. Most people plan to migrate from XP straight to Windows 7, skipping Vista altogether! Personally I have really liked Vista. The only real issue I had is it wouldn't run a really old game that I used to play on Windows XP. Considering the game was developed for Windows 98 I am pretty impressed it ran on XP! I also really like the idea that most of my programs are not running with Administrator permissions. I also must admit that I purchased hardware specifically geared toward Vista compatibility. I also switched to 64 bit because 3GB of RAM just isn't enough for me, but that would have been independent of XP or Vista.
I've installed a copy of Windows 7 64-bit on a virtual machine. To me it looks and feels just like Vista. I was impressed that the memory foot-print was much smaller but a recent fresh install of Vista wasn't too much larger. It also featured an improved installer and some new features. If someone can tell me why it wants to make a 100MB partition and what that is used for please leave a comment here.
Microsoft has decided that it's better to have more eyes on something than less so they have made Windows 7 Beta 1 an open invitation. The caveat is that the download link is only valid until (or so I am told) the 24th of Jan 09. So if you think you may want to tinker you better get downloading! Especially since the download servers have been saturated since the beta was made public.
Download Windows 7 Beta 1
This announcement on Scott Gu's blog touts the success of the launch of Silverlight 2.0 and announces Silverlight 3.0. Out of the success stories noted on the blog one of the coolest applications is the new Netflix player! Having worked only a little in Silverlight but a lot in WPF I have been very disappointed with the lack of databinding in Silverlight 2.0! It sounds like I am not alone in this line of thinking so Silverlight 3.0 promises to fix a lot of that. Another great feature is hardware acceleration (using OpenGL?) which would be really sweet! These tools should be available early next year.
Here is a screen shot (taken from Scott's Blog):
I really hope that they bring WPF and Silverlight more in line with each other -- increasing capability and compatibility! It's ridiculous to think that we have three different but strikingly similar tools that don't interop! Of course the three being WPF, Silverlight and MCE Media Center.
Links:
I know this is a little off topic for my blog as I only usually blog about technical stuff, but I LOVE 7-layer bean dip! I have been "perfecting" the recipe ever since I've been married and I have a pretty good recipe on my hands. Of course many of these ideas are not my own but rather borrowed, but I don't know of anyone else that does this combination. My recipe is based on the principal that the dip should never break a chip and that you should be able to get something from all seven layers in each bite.
Shopping List
- Refried Beans - Get the good quality, name-brand beans! You can really taste a difference if you don't.
- Sour Cream - Small
- Taco Seasoning
- Pace Salsa
- 1 can medium or small olives
- 1 Firm Avocado
- 2 Firm Medium Roma Tomatoes
- 1 pkg Cheddar Pizza Cheese (or a block of Cheddar will do)
- 5 green onions
Preparation
Open the can of beans and dump into a medium mixing bowl. We want to "thin" out the refried beans a little bit. I like to use Salsa! Add about 1/4 cup salsa to the beans and mix thoroughly. Add more Salsa if needed to get the beans to a soft but "stiff" (not runny) texture. I consider this to be an original idea but I am really not sure if I was the first to think of this. Spread the beans evenly in an 8x10 casserole dish.
Open up the container of sour cream and empty into a smaller mixing bowl. Add about 1 Table spoon of taco seasoning (half a regular package). Mix and spread thinly and carefully on top of the beans. Make sure the sour cream is not "too deep" or "too thin" in places.
Open the can of olives and cut them into ringlets. I prefer to use smaller olives as they usually have better taste, are firmer, stay fresh longer, and allow people to get a ringlet of olive in every bite. They do sell cans of "pre-cut" olives and you can use them but these are no where near as good as quality! Hand-place the ringlets of olives on top of the sour cream. It's important to hand place these because their shape can make the dip uneven looking. Also the olives form a moisture barrier between the layers that keeps keep the dip fresh longer. It is also important to make sure the ringlets are completely dry before applying to the dip.
Next we want to chop the avocado into little chunks. The avocado needs to be a bit firm (usually a day or so before ripe) or the dip will not keep for long. Also, in the context of the dip pre-ripe avocado tastes better than fully-ripe avocado. Also, I always prefer fresh avocado to guacamole. Sprinkle the pieces of avocado onto the dip and salt. The salt will improve the flavor and help the dip keep.
The tomatoes come next. Quarter the tomatoes top-wise and remove the "tasty slimy" inner parts of each quarter (shown below). The insides of a tomatoes add too much moisture to the dip so they have to go! They also don't stay fresh for long. Chop the remaining bits of the tomato and sprinkle evenly onto the avocado. Salt again.
Next comes the cheese! The pizza cheese is dry, stays fresh a long time and is the right flavor for the dip. If you do not have the packaged cheese you can grate cheddar cheese or a similar flavor. When grating remember to use the "small" grater to make smaller diameter cheese threads. Also don't press the cheese into the grater very hard as that tends to create longer threads when we want short ones. Spread the cheese evenly. You can use as much or as little as you like but I like to use a whole package.
Green onions are optional. I like them but they add a very strong smell! If you are going to use them chop them into ringlets and apply lightly to the top. After the dip is finished keep covered in the refrigerator. If made and kept properly it will last 3-4 days or more.
Personally I think it's better if you can serve it fresh, but if you made it the night before a party then let it "warm up" by letting it sit out of the fridge for 10-20 min's before serving.
Give it a try and let me know what you think. If you have any of your own recipe tweaks let me know about it.
There is Expression Blend, Visual Studio, XamlPad that we are all aware of and use on a regular biases for creating our XAML. One that I am adding to the top of my XAML editor list is Kaxaml! This is the lightest weight most useful XAML editor I have ever seen! It's got a great WPF/Blend look and is light and fast. No more waiting 10-30 seconds for Visual Studio to fail to load your XAML documents! If there were a way to replace the Visual Studio editor with this I would totally do it!
Unlike Blend it has code insight. Unlike Visual Studio 2008 it is fast and functional! My favorite feature is the XAML Scrubber which will "pretty up" your XAML by organizing the tags and attributes. It will even put the most important attributes at the start of the tag. It removes much of the pressure of writing XAML!
Hopefully some future versions will include a visual tree and perhaps even a feature where you can click on an click on an object and be taken to the applicable part in the XAML. The XAML Scrubber only uses spaces and I am a tab guy -- oh how I wish it supported tabs! Also, I noticed that once I added an event to a control it said I had to compile the XAML -- not sure what that means. That means it's probably mostly useful for creating the user interface before you start hooking code into it.
If you need a good place to hammer out some design -- this may be your best bet!
Links:
Sometimes those transaction logs get a little large and unwieldy! For dev machines I almost never want the transaction log to ever be larger than 1GB. I often find some transaction logs of 10GB and larger and there is little in the way of GUI tools to help you free up that wasted space. Luckly there is a really good command for SQL Server 2005 & SQL Server 2008 that will allow you to truncate the existing transaction log.
DUMP TRAN [DATABASE_NAME] WITH TRUNCATE_ONLY
That's it! You would think they would include a button or something in SQL Server Management Studio, but as I understand it this would be a bad thing to do in a production environment.
Hope this helps someone -- if so leave a comment!
EDIT:
If you are doing this is SQL Server 2008 then it no longer recognises the DUMP command. The best way to do this going forward is:
ALTER DATABASE [DATBASE] SET RECOVERY SIMPLE
The problem with this approach is that it will change your recovery mode from whatever it was to 'SIMPLE'. You will need to chage the recovery mode back after you run the command.
Singularity is a Managed operating system started by Microsoft Research. It's last version 1.1 target the .NET 1.1 framework and was a very fast OS (if not all that functional). The latest version supports the 2.0 framework, 64-bit processing, additions to the Bartok (MSIL-to-native) compiler, and updates to the Sing# compiler (C# style language used to build the Kernel).
Here is the architecture map of the project:
Some of the interesting things about Singularity are:
- The use of Managed code in the Kernel (also includes a small amount of C and assembly, but not much); therefore device drivers can be build using a C#-style language called Sing#.
- SIP's (Software Isolated Processes) means that processes don't communicate without a "Channel", they are also not allowed to share memory directly or change their own code. They are also very lightweight and allow the operating system to make guarantees about running code.
- Channels are interfaced-based process communication that are meant to be safe and fast
- Static Verification is used before starting a SIP to verify that the code that is about to be run "follows the rules" of the operating system. This helps eliminate "harmful" code -- that is code that has a negative effect on the system as a whole.
You can download the RDK here.
Links:
I have been wanting to add JavaScript to my posts for months but have never gotten it to work. I can usually get around using JavaScript but I decided that I wanted to add a Digg tag at the bottom and that requires some JavaScript.
- Open the communityserver.config file in the root of the Community Server 2008 install.
- Remote the line that reads:
<add name="WeblogPostandArticleHtmlScrubbing" type="CommunityServer.Blogs.Components.PostandArticleHtmlScrubbing, CommunityServer.Blogs" />
Links:
More Posts
« Previous page -
Next page »