On the Silverlight Insiders mailing list there’s been a discussion about the difficulties of handling animations when trying to use an MVVM architecture. I’m not going to go into the details here, as I am going to cover this more fully in a future blog post, but still, I could not resist showing off the elegant way that Caliburn solves this problem. Here is some XAML:
<TextBox x:Name="username" /> <PasswordBox x:Name="password" /> <Button Content="Login" pf:Message.Attach="Login(username.Text, password)" />
public IEnumerable<IResult> Login(string username, string password) { _credential.Username = username; _credential.Password = password; var result = new Result(); var request = new GetUserSettings(username); yield return new ProcessQuery(request, result, "Logging In..."); if (result.HasErrors) { yield return new ShowMessageBox("The username or password provided is incorrect.", "Access Denied"); yield break; } var response = result.GetResponse(request); if(response.Permissions == null || response.Permissions.Count < 1) { yield return new ShowMessageBox("You do not have permission to access the dashboard.", "Access Denied"); yield break; } _context.Permissions = response.Permissions; yield return new OpenWith<IShell, IDashboard>(); }
Please note that the 1st, 2nd and 3rd yield statements above are all *asynchronous*, but the code within this action is executed in sequential order. The 1st yield also triggers an animation...I can also do things like this:
yield return new BeginAnimation("MyCoolAnimation"); yield return new BeginAnimation("This animation is next"); yield return new BeginAnimation("This animation plays last");
This gives the View Model a declarative way to handle animations without a need to reference the view. Also, it should be noted that the above action relies on several UI services, but I can unit test this action without needing to mock anything. The declarative nature of the action allows me to iterate over the results and simply use normal Asserts on the values. Async programming becomes synchronous and playing Animations is peachy ;)
More on this later, but I just had to show some code because I’m not sure many people know you can do this with Caliburn. On my current Silverlight project, we are making extensive use of this. It makes calling web services a breeze.
This is a recent question raised in NHibernate Users Group. The user wanted to realize the following query with Criteria api.
var result = db.Person.Where(x => x.Pets.Count > 0 && x.Alive) .OrderBy(x => x.Name);
This is not a simple query, but it has a solution
DetachedCriteria crit = DetachedCriteria.For(typeof (Person), "p2") .CreateCriteria("p2.Pets","Pets") .Add(Restrictions.EqProperty("p.Id", "p2.Id")) .SetProjection(Projections.Count("Pets.Id")); ICriteria c = s.CreateCriteria(typeof (Person), "p") .Add(Restrictions.Gt(Projections.SubQuery(crit), 0)) .Add(Restrictions.Eq("p.Alive",true)) .AddOrder(Order.Asc("p.Name"));
What we had to do is to create a DetachedCriteria and on that execute CreateCriteria so that we can do querying on our collection.
The other way is simpler, but requires you to use criteria (below query is provided by Fabio Maulo)
session.CreateQuery("from Person p where size(p.Pets) > 0 and p.Visible = true order by p.Name")
or
session.CreateQuery("from Person p where p.Pets.size > 0 and p.Visible = true order by p.Name")
I hope this helps.
This is just a quick little rant on my part. In my opinion a property should be used for simply getting/setting of a value. You should NOT have any logic inside your getter/setter (ok, I will add a 'caviot' to this rule and say that I am ok with doing string formatting on the getter). If you need to have logic in either your setting or your getter I think it is about time to use a method, not a propery. WHY?Because, once you start adding behavior to the property you are masking this behavior and a method will better convey your intent.Again, this is just my thoughts/opinion, but I like to convey intent of methods/logic and wrapping logic inside a property does not convey intent.Till next time,
There’s been a lot of talk lately about MVVM (Model-View-ViewModel) in the WPF and Silverlight space. Recently, Ward Bell had an interesting post on the subject where he digs into some of the patterns he is using to support his MVVM triads. The WPF/Silverlight community is constantly droning MVVM, but almost no one goes beyond stating their use of the pattern or giving an overly general description of it. That’s why I enjoyed Ward’s post. He’s trying to get into the nitty-gritty of his UI architecture rather than just chanting “I'm using MVVM" and leaving it at that.
I’m pleased that the WPF/SL community is taking UI architecture seriously, but I think we have a long way to go. We need to dig deeper into the “how” of the MVVM and realize that a solid implementation is more that just creating a model and binding it to a view, with a dash of the Command pattern thrown in for good measure. In fact, saying you are using MVVM for WPF/Silverlight is sort of like saying you are using MVC for web development. It more or less states the general design approach you are taking to the UI architecture, but doesn’t say much about how the pattern is implemented or how individual features are represented within the context of that design. If you’ve been following the blogs on ASP.NET MVC, you’ve probably discovered that there is a lot more to it than just having Models, Views and Controllers. It is easy to use the MVC pattern very poorly and the same goes for MVVM.
Speaking of context…
When I first read the GoF book, I was baffled by its insistence that patterns were not tied to implementation. Sure, I understood that the Iterator pattern would be implemented differently in C++ than in C#, but I didn’t understand that other context-specific factors had a massive affect on the details of its implementation. This “phenomena” manifests itself in greater degrees with respect to how high-level the pattern is. A high-level pattern like MVC is a fine example of this. Consider how the implementations would differ between a WinForms and an ASP.NET implementation of this pattern. They would not resemble each other much at all. The WinForms version would likely look a lot like an Observer or Mediator while the ASP.NET version would be very similar to a Strategy. In fact the WinForms version would look so different, you might not even call it MVC anymore, though you started out with an MVC mindset. You could force the WinForms and ASP.NET implementations to look alike, but you would be creating a leaky abstraction by forcing an artificial context for your design to live in.
In the next couple of posts I am hoping to examine MVVM within the context of WPF/SL. What does the base form of it look like? What do more complex forms look like? Why is this pattern a good fit for WPF/SL? How does this pattern relate to MVP and MVC?
MVVM – A Simplistic View
If we take MVVM as a high level pattern, like MVC, then it becomes our general approach to architecting user interfaces. It means that we will have components in three of the following broad roles:
Models – These are the business-oriented components that are intended to be displayed or manipulated by the application. They might be traditional business objects rehydrated from the DB, messages from a web service or anything else that has business meaning independent of presentation.
Views – WPF/Silverlight is a view framework and is thus intended to provided these components. Their role is to display something on the screen. Nothing more, nothing less.
View Models – This is a special type of model, intended to be an abstraction of the UI. You can think of it as a logical representation of the UI. It is “connected” to the view at runtime through databinding.
My guess is that you probably feel pretty comfortable with the idea of a Model or a View. You can picture them in your mind. But when it comes to View Models, things get foggy. It means that we need to have a lot more discussion around what our View Models look like. But, we cannot just discuss them abstractly. We must look at specific scenarios and see how ordinary design patterns interplay to create a meaningful model of the UI. In a few words, here’s my general philosophy and what I hope will become clear as we proceed:
The same OOD techniques you use to build your backend systems are used to construct your View Models.
To that end, I am hoping to put together several posts on the subject. I am planning to contact several of my previous clients with the intention of gaining permission to discuss small portions of their applications; or to discuss them at a very high level. I want to show specific problems and demonstrate how we used common design patterns to build a rich View Model. It is my hope that this will begin a richer discussion on the topic within our community.
Ok, so this sounds like it should be drop dead simple and it is, however it is not (at least to me) 100% intuitive how you could accomplish this.
Here is what I wanted to do. I wanted to be able to copy ALL of my compiled dlls from my build to a ‘staging’ location and I wanted to do this in a simple manor. The first thing I did of course was to jump out to the nant project page to refresh my memory on the <copy> feature. Sadly after reading the doc, i did not find anything that stuck out and said ‘hey, if you need to copy an entire folder structure do this’.
However, with a bit of googling I was able to figure out a simple way to do it.
<target name="copy.nightlyBuild.to.staging.location"> <property name="dir.nightlyBuild.destination" value="C:\NightlyBuilds_Output\Build" /> <mkdir dir="${dir.nightlyBuild.destination}" if="${not(directory::exists(dir.nightlyBuild.destination))}" /> <copy todir="${dir.nightlyBuild.destination}" includeemptydirs="true" overwrite="true" verbose="true"> <fileset basedir=".\SOME_FOLDER_TO_COPY_FROM"> <include name="**/*.*" /> </fileset> </copy> </target>
What makes this process work is the **\*.* in the include section. the **\ tells nant to do a recursive copy.
Hope this helps
Till next time,
Here are two user group events that are happening soon and that I'm directly involved.
0-60 With Fluent NHibernate See the full description of the session over at the Chicago ALT.NET home page. We will have Hudson Akridge tell us all about Fluent NHibernate, a project that has been instrumental in getting people on NHibernate by simplifying a lot of that ORM's configuration chores.
The Chicago ALT.NET meetings start at 6PM in the Sears Tower. Check the website for complete location details.
JavaScript - Beyond the Curly Braces I'm taking my little JS presentation to the WI.NET UG in Milwaukee. The group's website hasn't been updated with the presentation details yet but it's basically the same presentation given at other local UGs.
The meeting starts at 7PM. Come ready to be surprised.
I was thinking of writing post series on NAnt but then I decided to write some on MsBuild first.
This post will briefly introduce you the basic concepts of automation of build, why we need build tools/scripts, and what alternatives we have.
Let’s first start with the definition of build script/tool.
What is a build script?
A build script is all about automation. When we compile projects, we also want to perform some other steps such as running tests, compiling documentation, create an examples package, move some files from one location to another, and in the end zip them, or create an installer for the project. Doing them by hand is not really an option, and you may have thought of preparing a batch file/shell script before you learnt the build files.
For me, Makefile was the first place that I heard about the term “build script”. It is mainly used in Linux to compile applications.
When we take a look at a sample makefile
OBJS = main.obj io.objCC = bccMODEL = sCFLAGS = –m$(MODEL) project.exe : $(OBJS) tlink c0$(MODEL) $(OBJS), $(.TARGET),, c$(MODEL) /Lf:\bc\libmain.obj : main.c $(CC) $(CFLAGS) –c $(.SOURCE)io.obj : io.c $(CC) $(CFLAGS) –c $(.SOURCE) $(OBJS) : incl.h
First we have several properties which we’ll use later, they are like variables. Then we have some targets which has “:” on the right. On the right of “:”, we have their “dependencies”. A dependency is a unit that has to be run before the dependent, or a file that our file depends on. For example, main.obj depends on main.c and in case main.c is modified, we will run that target again. The lines after the target are the commands which will be run as part of the target.
This dependency idea is key to every build system and main points in writing a build script is to find dependencies of your project. After you define them, the rest is a piece of chocolate cake!
OK, i spoke too much Linux for a .net blog :) Let’s turn to our beautiful .net World.
In .net world, there are 2(AFAIK, if not please comment) build tools written specifically for .NET. One is the famous NAnt, and the other is MsBuild. NAnt is usually used in OpenSource project. MsBuild is being used since VS 2005, and it is part of the framework. Your csproj files are actually MsBuild files.
Most people say that that nant is more flexible and mature, but they also say that the nativeness of MsBuild into visual studio is a plus. Some they say that they delegate the build to MsBuild while using Nant for other stuff.
In the next post, we’ll write(and use .csproj) a basic MsBuild script.
If you like the post, please kick it and shout it.
This is a killer feature of TeamCity against other CI servers, I believe.
TC allows you to test your changes before committing them to the Source Control Repository, which means that you don’t have to worry about breaking the build, because you won’t :)
I needed this in order to try a fix that I had for an issue in NH, it worked on my machine but not sure if it works on another one.
Krzysztof Kozmic told me in the same evening that he’s going to try a fix against DP with personal build, and I thought it was a great idea!
Then it runs your changes on one of the build agents.
There we go! Patch didn’t break anything (even though it may not be how it should be)
Keep up the good work, JetBrains!
This feature of SVN is very handy. After you build your projects, there will be dlls in bin folders etc which you don’t want to commit.
Using svn:ignore property of SVN, you can eliminate the possibility of committing those files!
As many other things, I learnt this from NH :)
If you are not familiar with the Code Contracts library which is coming out of Microsoft R&D labs, you need to check this pretty cool little library out. As of Vs2010/.Net 4.0 this library will be making the jump out of the R&D labs.
Over the next few blog posts we will be taking a look at the topics below.
In this post we are going to take a look at what I think is one of the coolest features of the Contracts Library. The concept of Object Invariants.
What is Object Invariant validation?
This part of the library ensures that when the state of an object is changed that the object remains in valid state. If the state of the object is to become invalid then your contract would fail and this would be an issue.
Imagine you have a class called ReportCard, this class is used by a timekeeping system and is used to store instances of daily report cards (a daily report card holds the time/hours worked for that employee). We want to setup a rule which says that depending on the employee type they are not allowed to work > 40 hours (the actual number is not important). We also want to setup the ability to ensure they do not work < 0 hours.
Prior to code contracts you would need to create your state checking method and then place calls to the validator at location where the state changes. This is both tedious and error prone because as your add more code (hopefully you follow the Open/Close principle and extend the class not keep piling on new code, but that is a different post) you have to remember to add the state checking logic. With invariants you do not need to do that. All you need to do is below.
[ContractInvariantMethod] public void EnsureReportHoursIsInValidRange() { Contract.Invariant( EmployeeID > 0 ); var totalHours = TotalHours(); // Calcs total hours Contract.Invariant(totalHours >= 0); Contract.Invariant(totalHours <= 40); }
Taking a look at this code there are a few things you should know
Here is the same code above, but this time POST code weaving.
public void AddDailyReport(DailyCards dailyCards) { this.DailyReportCards.Add(dailyCards); this.EnsureReportHoursIsInValidRange(); } [ContractInvariantMethod] public void EnsureReportHoursIsInValidRange() { if (!this.$evaluatingInvariant$) { this.$evaluatingInvariant$ = true; try { __ContractsRuntime.Invariant(this.EmployeeID > 0, null, "EmployeeID > 0"); double num = this.TotalHours(); __ContractsRuntime.Invariant(num >= 0.0, null, ""); __ContractsRuntime.Invariant(num <= 40.0, null, "totalHours <= 40"); } finally { this.$evaluatingInvariant$ = false; } } }
The key thing to notice when looking at the reflected code is how the weaver added the call this.EnsureReportHoursIsInValidRange(); in the AddDailyReport() method.
2 Things to watch out for when utilizing the Object Invariant
A few weeks back I sat down with Larry Clarkin to record an episode of the Thirsty Developer (a podcast that he and Dave Bost put out) prior to my doing my SOLID session with the WI-Ineta group. Larry and I sat down at a local starbucks to chat about the session as well as just talk shop (Dave was off on assignment some place, but was there in spirit).
Well, Larry went off and actually released the episode (hey, when you chat with me the quality mileage may vary :) ) back a week or so ago while I was on a 2 week hiatus from the net (1 week vacation and 1 week of client visits for work) so I am a little behind in making the announcement about this.
Anyway, if you want to listen to our conversation you can check out here. I hope you like it and I am looking forward to sitting down with them in the future to chat again.
Also, if you do not currently subscribe to their RSS feed I would strongly suggest you give them a listen, they are great guys and a ton of fun
Quite often there is a fear that surrounds open source tools and frameworks. For most shops the deciding factor against open source software is the apparent "risk" that is associated with a framework/tool that is not attached to any business entity.
In this post I want to share an interaction that occurred this last weekend to show you that the open source ecosystem is alive and very healthy. And while I won't go so far as to say the "risk" doesn't exist (you have to come to that conclusion on your time when your own fears are allayed) I do hope that this post puts some of those fears to rest.
Saturday morning before I went off to work there was a question posted to the RhinoMocks mailing list (for those who don't know RhinoMocks is an open source mocking framework). Before the end of the day the problem was resolved to a satisfactory conclusion. The "solution" (I put in quotes because there appears to be a bug but at least now we know there is a bug...hence "solution"). The result is not as important as the events that transpired to reach that conclusion below is the timeline.
12:22 AM - Kenneth posts the problem he is encountering 6:53 AM - I respond on the mailing list back to Kenneth with my findings and let him know that I will get some experts in DynamicProxy involved 6:56 AM - I enlisted the help of Krzysztof Kozmic on twitter (Krzysztof is a committer on DynamicProxy by Castle as has a great tutorial series on Dynamic Proxy) 8:38 AM - Fellow Devlicious blogger Tuna Toksoz (also a committer on the Castle project) hopped on the case and reported his findings 9:22 AM - Krzysztof responds to Tuna's findings reporting back on the root cause 10:23 AM - Kenneth reported back with feedback of Tuna's fix
12:22 AM - Kenneth posts the problem he is encountering
6:53 AM - I respond on the mailing list back to Kenneth with my findings and let him know that I will get some experts in DynamicProxy involved
6:56 AM - I enlisted the help of Krzysztof Kozmic on twitter (Krzysztof is a committer on DynamicProxy by Castle as has a great tutorial series on Dynamic Proxy)
8:38 AM - Fellow Devlicious blogger Tuna Toksoz (also a committer on the Castle project) hopped on the case and reported his findings
9:22 AM - Krzysztof responds to Tuna's findings reporting back on the root cause
10:23 AM - Kenneth reported back with feedback of Tuna's fix
Ultimately, as I mentioned earlier the fix was that it was found that RhinoMocks "relies on the buggy behavior, hence the error" (Krzysztof's words). Again the result here isn't what is important but rather the journey. Often people fear the support ecosystem around open source software but the exchange above and the players involved should give you some bit of confidence in the support of open source. It is worth pointing out that all of this happened on a Saturday, something you'd pay a premium for in a closed source model.
Whatever your roll in the software world is, one aspect you have to consider when choosing any solution is risk. The traditional thought has been that with commercial software the support would be better when backed by a reputable name. I think the exchange showcased above demonstrates that support for open source software can compete (and potentially surpass) support that any commercial piece of software could offer. Keep that in mind the next time you are evaluating commercial software versus open source software.
Today I was reading the latest one of the many excellent blog posts Patrick Smacchia has put out on the topic of code metrics and caring for your code's quality.
The passion this guy has for that topic is such that he has created the best tool for analyzing your code. But he doesn't stop there. He wants to make sure we understand what is going on behind the seemingly magic CQL queries that ship with NDepend. He wants you to understand your code's DNA; with the added bonus that you can actually improve that DNA.
That's Science with capital S.
I simply hate when someone criticizes Patrick's posts as being just marketing material for his product. Let me tell you this. If I had that much dedication for software quality, to the point that I had created a great product to empower everyone, I'd also be trying to explain the problem to you using the tool I wrote. Heck, I'm pretty sure if someone else had written NDepend Patrick would still be writing about these things and using the tool in the process.
I like code metrics and static analysis a lot as well, not nearly as much as Mr Smacchia though. I'm very excited that very soon I'll get to use it in our code base, in our CI server. I can't wait to learn more about this science and inflict positive changes in our code. Like everybody else, we know there's dirt and bad smells in our code and it's just awesome that there's a tool that can help us clearly identify, mitigate, and track it.
My hope is that I'll be able to come back here and share what I've learned about my code and how the process we went through to improve it.
Ok, so it is official I have jumped on the ‘gotta have a mac bandwagon’. The week prior to father’s day my lovely wife decided that I could get a new MacBook Pro (well, Dimecasts was going to pay 75% of the cost and she would pay the other 25%). I decided that I was not going to make this new machine my primary box, so I went small and picked up the 13.3 model.
So, why did I get one? Because I could silly :). No, mostly to learn and play. I want to learn how to code in a different environment and with different languages. On my list is Ruby (of course), Objective-C and maybe some playing with Java. I do plan on building a iPhone app for Dimecasts (just need to find the time now).
With about 2 weeks of using/playing under my belt and I have to admit the transition has been pretty easy. About the only real annoyance is the fact that they keyboard is a bit different than a PC, but over time.
Anyway, thought I would share with the world that I got a new toy. BTW, Windows 7 runs SUPER fast under VM on this box.
We’ve been getting many requests on having fluent configuration for NHibernate Integration Facility, and as I like programmatic configuration more than XML configuration (did I mention that I hate XML?), I decided to work on it. After 2-3 hours, I got the below more or less working
container.Register(Fluently.ConfigureFacility() .Id("nhibernateFacility") .DefaultConfigurationBuilder<DefaultConfigurationBuilder>() .DefaultConfigurationPersister<DefaultConfigurationPersister>() .AddFactory( Fluently.ConfigureFactory() .Alias("myAlias") .Id("myId") .UsingConfiguration( FactoryConfigurator.DefaultBuilder() .ConnectionProvider("…………………………") .ConnectionDriver("…………………………") .ConnectionString("…………………………") .Dialect("…………………………") .ProxyFactory("…………………………") .Assemblies("…………………………"))) .AddFactory( Fluently.ConfigureFactory() .Alias("myAlias") .Id("myId") .UsingConfiguration( FactoryConfigurator.XmlBuilder().File("myFile.xml"))));
The pieces in Italic are not necessary to write as they have their defaults, also we have some generic overloads for things like Dialect, ProxyFactory and ConnectionProvider.
What the above interface does is that it actually converts all the above configuration to IConfiguration and add them to the container as Facility Configuration, this is actually what is done behind the scenes when you use XML configuration.
I asked for a review over the syntax from several tweeps (@kkozmic, @dagda1, @mikehadlow, @chriscanal) and from one other NH Facility user, German Schuager, and got great feedback.
One of the issues that they pointed out with the above interface is that it is less discoverable. You have to find Fluently class, and then FactoryConfigurator class. Another issue is that it feels less natural to configure the facility like this. Instead, they prefer the configuration take place right on the facility.
This one is what German Schuager has suggested
container.AddFacility<NHibernateFacility>("nhibernateFacility", cfg => cfg .DefaultConfigurationBuilder<DefaultConfigurationBuilder>() .DefaultConfigurationPersister<DefaultConfigurationPersister>() .AddFactory("id1", f => f .Alias("myAlias") .UsingConfiguration<DefaultBuilder>(c => c .ConnectionProvider("………") .ConnectionDriver("………") .ConnectionString("………") .Dialect("………") .ProxyFactory("………") .Assemblies("………") )) .AddFactory("id2", f => f .Alias("alias") .UsingConfiguration<XmlBuilder>(c => c .ReadFrom("myfile.xml") )) });
and similar one from Krzysztof Kozmic.
Looks like i was the only one that is fan of Castle Microkernel style Fluent Interface.
Let’s see what I’ll come up for the second take, If I ever do it.
About The CodeBetter.Com Blog NetworkCodeBetter.Com FAQOur Mission Advertisers should contact Brendan
Subscribe Google Reader or Homepagedel.icio.us CodeBetter.com Latest ItemsAdd to My Yahoo!Subscribe with BloglinesSubscribe in NewsGator OnlineSubscribe with myFeedsterAdd to My AOLFurl CodeBetter.com Latest ItemsSubscribe in Rojo
Member ProjectsDimeCasts.Net - Derik Whittaker
Friends of Devlicio.usRed-Gate Tools For SQL and .NETNDependSlickEdit SmartInspect .NET Logging NGEDIT: ViEmu and Codekana LiteAccounting.Com DevExpressFixxNHibernate ProfilerUnfuddle Balsamiq MockupsScrumyJetBrains - ReSharper <-- NEW Friend!
Site Copyright © 2007 CodeBetter.Com Content Copyright Individual Bloggers