tag:blogger.com,1999:blog-41420615596839501262024-03-13T22:12:52.054+11:00Caleb's ConversationsCaleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.comBlogger19125tag:blogger.com,1999:blog-4142061559683950126.post-61379549955674386762011-09-27T18:43:00.001+10:002011-09-27T18:45:37.734+10:00Always use a comma in property initializers<p>C# has a feature that lets you always have a comma after an item in initializers even if they are the last property or item. For example this is all valid code:</p><script src="https://gist.github.com/1244609.js?file=example.cs"></script> <p>I am of the opinion that you should always include the comma even when it is the last item as it makes source diffs cleaner later if you need to add or remove an item. For example compare this diff where a comma wasn’t included for the last property, with the next one where a comma was used for the last item.</p><script src="https://gist.github.com/1244609.js?file=example-without-comma.patch"></script><script src="https://gist.github.com/1244609.js?file=example-with-comma.patch"></script> <p>I think you will agree it is much easier to identify what changed in the second example. The same holds true for when you remove a property or item from you initializer. The source diff will always be clean if you always use a comma, so use it!</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com1tag:blogger.com,1999:blog-4142061559683950126.post-89909468812110878932011-08-28T19:43:00.001+10:002011-08-28T20:05:36.982+10:00What to do when your Sharepoint WebPart is causing authorisation issues<p>Whilst working with a client to customise some of their public facing Sharepoint pages I developed a number of custom web parts. One of these web sites was getting some of its information by enumerating the different sub sites of the site collection. Unfortunately while this worked well when the site’s users were authenticated it didn’t work if they were anonymous users, which of course the majority of the sites users would be. When an anonymous users navigated to a page with this webpart they were prompted for their credentials.</p> <p>There is a simple solution to this problem which is to us the SPSecurity.<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx">RunWithElevatedPrivileges</a> method, passing in a delegate to the work that is requiring authentication. Your code would look something like this:</p> <script src="https://gist.github.com/1176479.js?file=RunWithElevatedPrivilegesExample.cs"></script> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-41528341182470954232011-08-21T16:37:00.001+10:002011-08-28T20:06:30.456+10:00GuessWho a sample data library<p>I just published by first <a href="http://nuget.org/">nuget</a> package. It is a library for generating sample identity information. It allows you to write code like this:</p> <script src="https://gist.github.com/1160248.js?file=guesswho-sample.cs"></script> <p>Which produces this output:</p> <script src="https://gist.github.com/1160248.js?file=Output"></script> <p>For more information I recommend you check out the project page over at <a href="https://github.com/caleb-vear/GuessWho">github</a> or <a href="https://bitbucket.org/calebvear/guesswho">bitbucket</a>.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com1tag:blogger.com,1999:blog-4142061559683950126.post-51563476732808964842011-07-20T20:03:00.000+10:002011-08-28T20:03:50.859+10:00Creating a custom SharePoint navigation menu<p>While working on a public facing SharePoint website I was asked to build layout that worked well with mobile devices. For the most part I achieved this by editing the master page and then choosing which CSS file to link to based on whether or not it was the mobile page was being requested. This approach worked well for most of my content, but the standard SharePoint navigation menu was somewhat problematic in that it lays itself using tables and is rather complicated. I wanted it to be much simpler and just use a simple unordered list.</p> <p>I ended up writing a custom ASP.NET control to do just that. Of course I want the new menu to respect the same visibility settings for the different links and to stay in sync with changes to the sub site names. The best way to achieve this is to use SharePoint’s built in site map. My code ended up looking like this:</p> <script src="https://gist.github.com/1176491.js?file=Codebehind.cs"></script> <p>And the markup:</p> <script src="https://gist.github.com/1176491.js?file=Markup.ascx"></script> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-45870893657505934602011-07-03T22:45:00.001+10:002011-07-03T22:45:37.415+10:00What is wrong with WPF?<p>When WPF was first announced, I got me extremely excited. I watched a number of the early demos and saw what was possible in terms of styling and animation and it just seemed amazing. One demo showed how simply a ListBox’s template could be changed to display as a map of the world and each item was a country. Combine that with the promise of rich media support and hardware acceleration and I was convinced WPF was going to be the best thing ever.</p> <p>Such was my excitement that I started working with WPF as soon as I could get my hands on it. I have been working with it professionally since 2006 and over that time I have found a number of problems that routinely rear their ugly heads. I find it hard to stop thinking about a problem until I have a solution, but the nature of the problems combined with the fact WPF closes up so many possible extension points means I haven’t been able to come up with a solution using WPF as we know it today.</p> <p>This combined with my OCD desire to solve problems has caused me to spend a lot of the time I should be sleeping thinking about how I could design a successor to WPF that was free of these problems. Unfortunately I don’t have enough spare time to actually build the thing so I asked the tweeps to convince me I shouldn’t waste my time by starting to write a replacement. <a href="http://twitter.com/#!/jtango18">@jtango18</a> asked me why I would want to in the first place and this post will attempt to answer that question.</p> <h3>Poor design experience<br></h3> <h1></h1> <p>One of the much touted features of WPF was supposed to be how it enabled designers and developers to focus on what they were good at. Blend being the tool for designers and Visual Studio being the tool for developers. The problem is that Blend is only any good for doing a design when you have some data to display and tends to fall down quite badly if you have certain constructs in your XAML or code behind. Everything will work when you run the application but the designer just blows up.</p> <p>Blend does have tools for generating some design time data, but this is limiting because of the time it takes to set it up and it also won’t work if you have different data templates which are selected based on the type of the object you are displaying. There are many other small annoyances with using the designers, but the thing that frustrates me the most is that I often have to run my app, navigate to the part I am working on look at it, then go back and tweak the design and repeat infinitum. When you are trying to decide on the best margin or colour for something in a data template I find my self wasting enormous amounts of time repeating that cycle.</p> <p>My UI framework would be built with this in mind and would allow the designer to attach straight to the running process and edit the view live. You could make use of the real data and get instant feedback as you made changes even when you are 3 or 4 templates deep. I think this might actually be achievable with WPF as some of this can be done using tools like <a href="http://snoopwpf.codeplex.com/">Snoop</a>, but it would take a lot of work to get it to the same level of functionality that Blend supports.</p> <h3><strong>Poor Animation Performance</strong></h3> <p>I simply cannot understand this one, but I suspect it boils down to rendering performance. I have often found animations involving a few objects, especially objects that have a few effects applied (eg drop shadow) do not animate smoothly into position. I refuse to believe that my laptop is incapable of rending a few UI vector shapes moving around with a couple of simple effects applied smoothly. For crying out loud it can render this @ 60 frames per second at 1920 x 1200 and it has to do extra work like updating physics for 100s of objects:</p> <p><a href="http://lh5.ggpht.com/-SJymts0JAY8/ThBkauXmgEI/AAAAAAAAACQ/6HL5lECeAdE/s1600-h/98205967111.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="982059671" border="0" alt="982059671" src="http://lh3.ggpht.com/-WM3BCw1nF-c/ThBkbsu0x9I/AAAAAAAAACU/HOwYBxk5gU8/982059671_thumb17.jpg?imgmax=800" width="646" height="327"></a></p> <h3></h3> <h3>Animations Fail To Play</h3> <p>Quite often when you have a UI component that has different states you would like it to look different in each state. In .NET 4.0 the <a href="http://msdn.microsoft.com/en-us/library/system.windows.visualstatemanager(v=VS.100).aspx">VisualStateManager</a> was added to help with this sort of thing. However I sometimes find animations between states, or animations that should loop while in a given state simply fail to play some of the time. I have never been able to get it to work 100% of the time, it will work most of the time and then just fail for no apparent reason.</p> <p>I encountered similar issues before the <em>VisaulStateManager </em>was added to the framework and in those situations it boiled down to not being able to apply the animation, because another animation was already applied to the object. Given that animation was one of the key things WPF was supposed to make easier it is more than a little silly how many workarounds I have to use to get it to work properly.</p> <h3>Drag and drop </h3> <p>There is no inbuilt support for doing drag and drop with nice Windows shell effects, such as drag descriptions and thumbnails. WPF is supposed to be about creating rich user experiences, but it doesn’t even let you easily do shell style drag and drop. I have implemented a bunch of Blend behaviours which make this possible, but you wouldn’t believe how much trouble and how many hacks I had to use to get them to work properly without flickering. Not to mention how MS decided to make the methods for accessing the mouse’s screen coordinates internal, you need the screen coordinates to prevent accidental drag and drop operation when the view is scrolling.</p> <h3>Missing effects</h3> <p>When you are trying to design a nice looking UI, gradients and drop shadows can go a long way. Inevitably though you wind up wishing you could use a bevel, inner shadow, inner glow and maybe an outer glow. If you have worked with Photoshop you will know how these effects can be used to create some quite striking visuals, but alas WPF doesn’t have support for them.</p> <p>You can off course get some of these by using the old bitmap effects, which works fine as long as the object you are applying it too is tiny, but as soon as you add it to a big object things start to chug very very badly. No worries I hear you say, you can just write your own graphics shader to do it for you. Unfortunately WPF doesn’t support multi-pass shaders which are required for these effects. Well actually it sort of does, the built in shadow effect does use multiple passes, but they don’t expose that functionality to you so you’re stuck with a single pass. The end result is that you end up using lots of PNG images made by Photoshop and you can kiss your resolution independence goodbye.</p> <h3>Video and other media support is poor</h3> <p>I have worked on a couple of projects where the level of support for video playback in WPF has been very disappointing. In both cases I ended up having to ditch WPF and go back to WinForms in conjunction with DirectShow. WPF is fine if all you want to do is play a video here and there, but as soon as you want to do more than that you run into problems.</p> <p>For example say you have multiple videos all playing at once and it is imperative that they stay perfectly in sync with one another. This is not possible in WPF because your access to the underlying resources is too limited.</p> <p>Another example, you would like to have one video playing in a loop and then, when the user presses a button immediately start playing another video with no noticeable pause between the videos. However there is no way to tell WPF to buffer a video other than to play it, you can play it and pause it, but you still don’t know when the buffering is complete so it is hard to transition between the two.</p> <h3>Triggers are messed up</h3> <p>When I was first learning about triggers I thought they were awesome, but after you learn the limitations it starts to disappoint you. For example you can’t use data triggers outside of a data template, why is that? Then there is how you can’t say you want the trigger to fire when the value is not equal to the one you provide. I actually spent quite a bit of time digging about in <a href="http://reflector.red-gate.com/">Reflector</a> for a way around that one and eventually discovered that underneath it all triggers actually do support the idea of not equal, but it is never exposed anywhere. I couldn’t make a nice fix for it though, because the trigger collections test to make sure they only receive specific implementations. That just plain sucks, why can’t I write my own triggers? </p> <p>Some would say so I can’t so that I don’t write triggers that perform badly and then blame MS for poor performance, but I think that is the stupidest reason ever. By giving me more power, sure it does increase the ways I can blow my head off, but it also lets me do amazing things that no one has thought of before. Given that I’m a responsible adult let me decide if I want to play with fire or not, I won’t blame you if I burn my self.</p> <h3></h3> <h3>Implementing Virtualizing Panels is Hard</h3> <p>So you have a list that has hundreds or thousands of items and you want to scroll smoothly. You can sort of get away with the built in virtualizing stack panel, but it isn’t smooth and if you have your own layout you can forget about it all together. We need a way to solve this problem that doesn’t take many, many hours to get something that is passable.</p> <h3>Binding Memory Leaks</h3> <p>By default if you bind to a POCO object that doesn’t implement <em>INotifyPropertyChanged</em> you get a memory leak, where the object you are binding too will never ever be garbage collected. This is crap and should not happen.</p> <h3></h3> <h3>Lack of composition and extension points</h3> <p>WPF was supposed to be all about composition over inheritance. Control and Data templates do to some degree achieve this goal, but I just wish they had applied the same thinking to the rest of the framework. For example the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.button.aspx">Button</a> control’s inheritance hierarchy has eight classes before you get back to object. There is a school of thought that suggests that if the team had realised the power of attached properties earlier a lot of the functionality would be implemented as something like Blend behaviours instead of separate classes.</p> <p>This inheritance tree can makes things rather difficult, because quite often you end up having to have a case in your code for both <em>FrameworkElement</em> and <em>FrameworkContentElement</em>, why the hell they don’t implement a common interface I have no idea.</p> <p>When you put this together with so many places where your ability to extend the framework has been deliberately limited (eg triggers, low level video access and multi-pass shaders to name a few) you end up with a sour taste in your mouth. I have spent many hours over the last few years getting around these problems in software projects I have been working on, but if WPF was just built a little differently I wouldn’t have the problem or there would be an elegant solution rather than painful hacks.</p> <h3></h3> <h3>In Conclusion</h3> <p>So am I crazy and these problems only exist for me or have you had these problems too? Feel free to leave a comment or haggle me <a href="http://twitter.com/#!/calebvear">@calebvear</a> on twitter, I would love to hear about your experiences. </p> <p><em>PRIEMTIVE NOTE: I have heard some of the news about Windows 8 and the new DirectUI and Jupiter APIs. Of course at the moment most of what I have heard seems to be largely speculative. I do hope that it will solve many of the issues I have today, but I doubt it will solve all of them.</em></p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com8tag:blogger.com,1999:blog-4142061559683950126.post-51519628738507890532011-04-07T14:00:00.001+10:002011-04-07T14:18:13.172+10:00WPF Bindings Not Updating When PropertyChanged Raised When Bound Against a Proxy Object<p>Last week I came across an issue with binding <em>NHibernate </em>proxy objects to a WPF UI. My problem involved a read only property that was not updated in the UI even though the property changed event was being raised. It worked fine when I first created the object, but after loading it at a later time the updates didn’t work anymore. Upon closer inspection I discovered that the object we were binding to was an <em>Nhibernate</em> proxy object. To understand what was going on better I have put together a simple example, consider the following class:</p><script src="https://gist.github.com/906916.js?file=ExampleOfProblem.cs"></script> <p>This is a very simple shopping cart, we might have a WPF <em>TextBlock</em> bound to the Total property so that we can show the shopping cart’s total value. Everything would work find, but if we loaded this class lazily so for example through a <em>Customer.CurrentShoppingCart</em> property, then the total <em>TextBlock</em> wouldn’t be updated. The reason for this is that in order to delay loading of the shopping cart <em>NHibernate</em> uses a proxy object instead of the actual value when it initializes the Customer’s <em>CurrentShoppingCart</em> property. How the proxy works can be seen in the following diagram.</p> <p><a href="http://lh4.ggpht.com/_iublhN7bBeE/TZ020Yl9iLI/AAAAAAAAAB4/twevoPsP29w/s1600-h/image%5B4%5D.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_iublhN7bBeE/TZ020_FqMnI/AAAAAAAAAB8/5gITW9tuxdE/image_thumb%5B2%5D.png?imgmax=800" width="601" height="340"></a></p> <p>When our <em>TextBlock</em> binds to the Shopping Cart Proxy’s Total property it also subscribes to the <em>PropertyChanged</em> event. The proxy passes this subscription onto the actual shopping cart which adds the event handler to its <em>PropertyChanged</em> delegate and you would think all is well. You of course would be wrong, here is what happens when the Shopping Cart raises a property changed event.</p> <p><a href="http://lh3.ggpht.com/_iublhN7bBeE/TZ07AKhRfjI/AAAAAAAAACI/A3lqvDDwKhg/s1600-h/image%5B19%5D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_iublhN7bBeE/TZ07BAPXvUI/AAAAAAAAACM/FWe0MJm316U/image_thumb%5B11%5D.png?imgmax=800" width="645" height="233"></a></p> <p>Essentially for our event to work we need the sender to be the shopping cart proxy and not the actual shopping cart. To do this we will need to extend one of <em>NHibernate’s</em> proxy implementations. We were using the <em>Castle</em> proxy implementation so the following code will work with that. It would be quite possible to implement something similar with the <em>LinFu</em> version, but I’ll leave that as an exercise for the reader. Before we start I will mention you can get the full gist here: <a href="https://gist.github.com/906916">https://gist.github.com/906916</a></p> <p>First up we need to create a new version of the <em>LazyInitializer</em>, which will intercept calls to add or remove subscriptions and keep track of them in the proxy. We will also subscribe to the target objects <em>PropertyChanged</em> event when it is created so that we can forward on property changed calls, to our subscribers. We will leave everything else as it was.</p><script src="https://gist.github.com/906916.js?file=FixDataBindingLazyInitializer.cs"></script> <p>The next thing we need to do is extend <em>ProxyFactory</em> to create our version of the <em>LazyInitializer</em>. This is pretty straight forward and looks like this:</p><script src="https://gist.github.com/906916.js?file=FixDataBindingProxyFactory.cs"></script> <p>When then have to make our own implementation of <em>IProxyFactoryFactory</em>, our implementation is a straight copy of the one in the<em> NHibernate.Castle.ByteCode</em> assembly only we return our <em>FixDataBindingProxyFactory</em> instead of the Castle version.</p><script src="https://gist.github.com/906916.js?file=FixDataBindingProxyFactoryFactory.cs"></script> <p>And our last step is to update our config so that we use our new <em>IProxyFactoryFactory</em>.</p><script src="https://gist.github.com/906916.js?file=ExampleConfig.xml"></script> <p>We have now solved the problem. I would like to thank <a href="http://www.progware.org/Blog/author/Admin.aspx">Ioannis</a> for a <a href="http://www.progware.org/Blog/post/NHibernate-PropertyChanged-event-and-WPF.aspx">blog post</a> he wrote related to this problem which included a solution although it didn’t fix my problem did point me in the right direction. </p> <p>Happy coding!</p> <p>Caleb</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-28592839481115286372011-03-07T04:08:00.001+11:002011-03-07T04:08:44.844+11:00Resharper Intellisense Annoyance<p>I have been using <a href="http://www.jetbrains.com/resharper/">Resharper</a> for about 5 months now and I must say that generally I have been loving it. It has really helped improve the speed which I am able to do things in Visual Studio. Its all the small things like moving a class to a different project or creating a new file which are just so much easier with Resharper. Not to mention the navigation features like navigating to a specific member in the file your in or opening any file in the solution with ease.</p> <p>The one thing that hasn’t always been pleasant though is that I haven’t been able to figure out a way to make Resharper’s Intellisense parameter info show me generic methods very well.</p> <p><a href="http://lh4.ggpht.com/_iublhN7bBeE/TXO_lRHPwxI/AAAAAAAAABw/6r94xbI-RQY/s1600-h/image%5B9%5D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh6.ggpht.com/_iublhN7bBeE/TXO_m45fWwI/AAAAAAAAAB0/7IX-2QUrACE/image_thumb%5B5%5D.png?imgmax=800" width="589" height="105"></a></p> <p>In this example the first method shown in the tooltip is actually a generic method that takes a generic parameter called TModule, but I can’t tell that from the parameter info tooltip. When I am looking over some code I quite often want to see what other overloads of a method their are so I press Ctrl+Shift+Space to bring up the parameter info tooltip. I have discovered that I can navigate to end of the method name an hit Ctrl+Space to show the method list which does show the generic parameters, but I would like to see it in the parameter list as well. </p> <p>I have been able to find a setting for this and I am wondering if there is any way to achieve it. If you know of a way to do this let me know as I would love to hear it. If I do get an answer on this I’ll update the post accordingly.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-23938969269896206852011-02-27T19:24:00.001+11:002011-02-27T19:24:23.647+11:00Dear vividwireless from a want to be customer<p>Earlier today I sent this email to vividwireless and I will be interested to see what their response is. I have posted it hear so that others can think about it and comment if they like. <blockquote> <p>Dear vividwireless, <p>First of all let me start by saying that your product offering is very tempting and you appear to offer some excellent services. The only sticking point for me is the credit expiry for your prepaid offering. Let me explain: <p>I have excellent ADSL2 broadband at home with 150GBs of download per month, my house is also outside of your coverage area so even if the speed of your service was better than my home line I couldn’t change over (if the speed was just as good and I had coverage your unlimited plan would be extremely tempting). <p>All of that to say that vividwireless would not be my primary connection, however I have to do a bit of travel for work and quite often my travels take me to places that you do have coverage in. When I am staying at hotels it would be very handy for me to have one of your wifi hotspots with me. The trouble is I also sometimes travel in areas where you don’t have coverage and for those places I use a Telstra Next G USB modem. Telstra have coverage in pretty much all of the places you do and a whole lot more to boot. However you have a better connection so when I am in an area you do service I would prefer to use your connection. This brings me to the dilemma. If I buy prepaid credit from you it will most likely expire before I use it all. I understand how that is good for you, but it isn’t good for me. <p>At the moment I purchase $150 of credit from Telstra which lasts for 365 days. This means I don’t have to worry too much about wasting half of my credit due to it expiring on me before I use it all. If I purchase $150 of credit from you it only lasts 180 days so there is a high chance that I will not have used it all before it expires as I don’t need it the majority of the time. Even if recharging before it expires will extend the time on my credit you are essentially asking me to pay $25 per month for something I don’t use all that often, but would like to use when I need to. <p>If you removed the expiry from your credit or at the very least made it last for a year no matter how much I recharge with, then I would sign up right now, but as it is I will just stick with Telstra. So instead of you getting some of the money I give to them you will get none of it as I can’t afford the extra $25 a month for something I might not use very much. I imagine that I am not the only one in this situation and that by changing things you could make that a key selling point and appeal to larger market. <p>I think you guys are doing very well so far and are offering an excellent service (from the feedback I have heard from friends) and are breathing some fresh air into the stuffy telecommunications sector, but I think you can do even better. Think outside the box a little more and ditch the credit expiry and you will remove all reasons for someone not to buy your product. <p>Cheers, <p><b>Caleb Vear</b></p></blockquote> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com3tag:blogger.com,1999:blog-4142061559683950126.post-3997545762583470762011-02-19T22:49:00.002+11:002011-02-19T23:01:37.496+11:00Put your behaviour where it belongsThis past week I have been working on a feature which allows the application to record the net weight of a various loads on a shipment. There are of course certain rules which control whether a weight can be accepted or not and other side affects to accepting a weight, such as setting the date and time the weight was accepted. All of this should of course be controlled by my domain classes, but how often have you seen code that looks something like this:<br />
<script src="https://gist.github.com/835014.js?file=badway.cs">
</script> <br />
I must confess I have been guilty of writing code like that my self, but I have learned a lot since then and I now know that this can be done better. Too often we fall into the trap of making our domain objects just a place to hold our data. If we do this we wind up having our core business logic and behaviours strewn all over our application. More and more I tend to favour having private or protected setters for all my properties. Then the only way to make changes is by calling methods which model the actions that the users actually want to perform. In my shipping example they are accepting the weight, they aren’t just setting it. Accepting the weight is a core business concept and it has rules which apply. My code now looks more like this instead, which in my opinion is a vast improvement:<br />
<script src="https://gist.github.com/835014.js?file=goodway.cs">
</script> <br />
Your methods for changing domain states should be verbs that the business would use to describe the action that is actually taking place. Going back to my shipping example a Weight is made up of multiple Weighs. This is because sometimes a truck is too long to fit on a weighbridge so they need multiple readings. They describe the process as capturing a weigh, so my method is called CaptureWeigh(decimal reading, CaptureType captureType). There are rules when capturing a weigh which are applied in that method. Typically though a lot of code would just add the reading to a collection provided through a property on the Weight class, but that removes the chance to have the business behaviour captured in the object that represents it in your model.<br />
When modelling your domain this way you will find that nearly all of your collections shouldn’t be exposed as <a href="http://msdn.microsoft.com/en-us/library/5y536ey6.aspx">IList<T></a> because you want to control what happens when you add something to them. Rather than exposing IList<T> use <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx">IEnumerable<T></a>. If you need to get the count you can just use the Count() extension method, if the instance you call Count() on is an IList then it will actually just return straight away without looping through the entire sequence. I still return the underlying IList<T> from my IEnumerable<T> property even though I don’t want people to modify it. I realise that that means they can cast it and then make changes, but the fact that I am IEnumerable<T> means they should know that isn’t a supported scenario. If they want to ignore that and muck with it anyway then that is their problem. I have seen people advocate wrapping the underlying list in a <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx">ReadOnlyCollection<T></a> instance to prevent modification, but I feel this is overkill. After all at the end of the day I can’t stop people from accessing the list anyway as they can always use reflection and if they are going to use things in ways that the interface clearly shows isn’t supported then good luck to them and if it blows up in their faces that is their problem!Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-32035807352869392912010-12-30T18:41:00.000+11:002010-12-30T18:41:00.549+11:00My standard .hgignore<p>One of the things that I do as soon as I am starting on a new project is create either a Git or Mercurial repository for the project. At the moment I tend to be using Mercurial more that Git, because bitbucket offerss free private repositories.</p> <p>One of the things you want to do when setting up the repository is add an ignore file so that you don’t add build artefacts and other user specific files to the repository. You don’t want to add these files as everyone that works on the project will be constantly changing these files which will pollute your history with lots of unnecessary changes that don’t really effect the project at all. </p> <p>I thought I might share my current default .hgignore file with you all. I am curious what other people have in theirs.</p> <blockquote> <p><em># use glob syntax.<br>syntax: glob</em></p> <p><em>*.suo<br>*\bin\*<br>*\Bin\*<br>*\obj\*<br>*\_ReSharper*<br>*.ReSharper.user<br>glob:Source/Shell/publish/<br>*.csproj.user<br>*\TestResult.xml<br>*.csproj.VisualState.xml<br>*\App_Data\*</em></p></blockquote> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-5371422132995036552010-12-27T12:41:00.001+11:002010-12-27T12:41:14.054+11:00Deploying ASP.NET MVC 3 RC2<p>I was recently working on a ASP.NET MVC3 proof of concept application. My client wanted to be able to preview my work with daily builds. It was suggested that the simplest way for me to go about this would be to deploy it to Azure. This turned out to work fairly well, but I did have a few dramas getting things to work.</p> <p>The main problem that I had was making sure that I deployed all of the MVC assemblies along with my app. This is required as it isn’t part of the .net framework. I found a few sites indicating which assemblies were needed, but I found I had to add a few more to list before things worked. This was a frustrating process, because I had to wait 15mins every time a tried something that didn’t work before I knew that it wasn’t going to work. </p> <p>To hopefully save others from having the same problem I have included a list of the assemblies I had to deploy along with my app to get it working. To include a referenced assembly in the deployment make sure that <em>Copy Local</em> option is set to <em>True</em> in the properties of assembly reference.</p> <p>Without further ado the assemblies you should include are:</p> <ul> <li>Microsoft.Web.Infrastructure</li> <li>NuGet.Core</li> <li>System.Web.Helpers</li> <li>System.Web.Mvc</li> <li>System.Web.Razor</li> <li>System.Web.WebPages</li> <li>System.Web.WebPages.Administration</li> <li>System.Web.WebPages.Deployment</li> <li>System.Web.WebPages.Razor</li> <li>WebMatrix.Data</li></ul> <p>I was quite surprised to see NuGet.Core and WebMatrix.Data in there as I can’t quite see why the MVC framework should have dependencies on these, but my application did fail to start trying to load these assemblies if I didn’t include them, so it would appear that it was necessary.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-50114954851559081282010-12-14T14:38:00.001+11:002010-12-14T14:38:54.035+11:00Windows Phone 7 Theme Resources<p>Recently I have been working on a windows phone 7 application. In a few of the project template XAML files I noticed references to some <a href="http://msdn.microsoft.com/en-us/library/ms750950.aspx">StaticResource</a> styles and brushes. I couldn’t find a nice way in Visual Studio or Expression Blend to see a list of these resources, so I set out to find one on the web. After a brief search I found the <a href="http://msdn.microsoft.com/en-us/library/ff769552(v=vs.92).aspx">Theme Resources for Windows Phone</a> page on MSDN. The page lists all of the available resources included in the wp7 theme, but doesn’t show you want the look like. I decided to make an app which would show the the theme resources to make choosing the correct resource easier.</p> <p>Please welcome <em>Theme Resource Preview</em> for windows phone 7!</p> <p align="center"><a href="http://lh6.ggpht.com/_iublhN7bBeE/TQbmp6CAfxI/AAAAAAAAAA0/QxQrAd4kJqo/s1600-h/image%5B3%5D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_iublhN7bBeE/TQbmriumrtI/AAAAAAAAAA8/A9P1sD7YzS0/image_thumb%5B1%5D.png?imgmax=800" width="618" height="362"></a><em>A view of the font name resources</em></p> <p align="left">The application contains pretty much all of the resources except for the colour resources. The reason I left the colours out of it is that they seemed to be the same as the brush so figuring out what colour to use shouldn’t be very difficult.</p> <p align="center"><a href="http://lh5.ggpht.com/_iublhN7bBeE/TQbmtOB2YxI/AAAAAAAAABA/LdR0wzC9KZA/s1600-h/image%5B6%5D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh6.ggpht.com/_iublhN7bBeE/TQbmth8tyUI/AAAAAAAAABE/Uj_d_VJ_jko/image_thumb%5B2%5D.png?imgmax=800" width="136" height="244"></a><a href="http://lh4.ggpht.com/_iublhN7bBeE/TQbmuyfiRiI/AAAAAAAAABI/c3byi1yPcM8/s1600-h/image%5B9%5D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh4.ggpht.com/_iublhN7bBeE/TQbmvQtI8xI/AAAAAAAAABM/sOK3-snS2J8/image_thumb%5B3%5D.png?imgmax=800" width="136" height="244"></a><a href="http://lh4.ggpht.com/_iublhN7bBeE/TQbmwrpfFNI/AAAAAAAAABQ/91CArRLIz1A/s1600-h/image%5B12%5D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_iublhN7bBeE/TQbmxfjp7iI/AAAAAAAAABU/KQJOfzxWZy4/image_thumb%5B4%5D.png?imgmax=800" width="136" height="244"></a><a href="http://lh4.ggpht.com/_iublhN7bBeE/TQbmySPAWbI/AAAAAAAAABY/-68EYrD2L5Q/s1600-h/image%5B15%5D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh6.ggpht.com/_iublhN7bBeE/TQbmzEtLN3I/AAAAAAAAABc/3WfEfV2mAJ4/image_thumb%5B5%5D.png?imgmax=800" width="136" height="244"></a><br><em>Some more shots of the application in action</em></p> <p align="left">I have posted the source code for the application to my bit bucket account so for anyone who is interested you can grab a copy of the source here: <a href="https://bitbucket.org/caleb_vear/wp7themeresourcepreview">https://bitbucket.org/caleb_vear/wp7themeresourcepreview</a></p> <p align="left">Or for your convenience you can use one of the following hg commands to clone (one is https and the other ssh):</p> <blockquote><pre><font face="Arial">hg clone <a href="https://caleb_vear@bitbucket.org/caleb_vear/wp7themeresourcepreview">https://caleb_vear@bitbucket.org/caleb_vear/wp7themeresourcepreview</a></font></pre><pre><font face="Arial">hg clone </font><a href="ssh://hg@bitbucket.org/caleb_vear/wp7themeresourcepreview"><font face="Arial">ssh://hg@bitbucket.org/caleb_vear/wp7themeresourcepreview</font></a></pre></blockquote><pre><font face="Arial">The only requirement for the application is that you will need a copy of Visual Studio 2010 and the Windows Phone development tools. The express version of Visual Studio should to just fine, although I used ultimate.</font></pre> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-38891745605138635452010-11-24T18:07:00.001+11:002010-11-24T18:07:47.765+11:00SkipObject Bug Solution<p>Yesterday I blogged about a bug I was having while implementing a serializer for my append only file storage. I blogged about it <a href="http://calebvear.blogspot.com/2010/11/where-is-bug.html">here</a>.</p> <p>The problem with the code is found by gaining a better understanding of how the <a href="http://msdn.microsoft.com/en-us/library/sa7629ew.aspx">+= operator</a> works:</p> <blockquote> <p><em>x += y;</em></p></blockquote> <p>Is equivalent to writing</p> <blockquote> <p><em>x = x + y;</em></p></blockquote> <p>The problem in this case can is explained in the following snippet:</p> <script src="https://gist.github.com/711325.js?file=SkipObjectExplained.cs"></script> <p>The fixed version of the function can be seen here:</p> <script src="https://gist.github.com/711325.js?file=SkipObjectFixed.cs"></script> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-17633787678386270512010-11-23T16:50:00.001+11:002010-11-23T16:51:06.398+11:00Where is the bug?<p>I was recently working on an append only file data store. I am building a list of the data at load time. The code that builds the index doesn’t know how to read anything, but the header information for an object. I have another class which implements ISerializer to handle reading and writing the objects that I want to store. The ISerializer interface has a method called <em>SkipObject</em> which is supposed to advance the the stream past the object, which will have it at the start of the next object’s header. The serializer can know how long the object is because the first 4 bytes of the object make up an integer that is the length of the object in bytes.</p> <p>Here is what I initially had for the SkipObject method:</p> <script src="https://gist.github.com/711325.js?file=SkipObject.cs"></script> <p>Can you spot the bug? I'll post the answer tomorrow.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-64084741854291227572010-10-30T21:23:00.000+11:002011-08-28T20:23:54.798+10:00Customising the SharePoint search box<p>On a recent project I worked on some custom branding for a SharePoint site. One of the things I wanted to do to help layout the page they way the wanted was to change the mark-up that was used by the search text box. I found an excellent MSDN article detailing how to do this and as it worked splendidly I decided to share it with you. Head on over to the article here: <a href="http://msdn.microsoft.com/en-us/library/ms470880%28v=office.12%29.aspx">How to: Customize a Delegate Control</a></p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-29589103603670005642010-10-11T14:24:00.001+11:002010-10-11T14:24:51.864+11:00ACT Libraries Rock!<p>I needed to meet up with a fellow Readifarian today so that we could work together on a joint PD (professional development) project. We needed to decide on a place to work and I suggested the Woden library. The last time I went there they had a couple of tables upstairs where people could study, the only facilities were the tables and chairs, but I figured that was better than a table at a coffee shop. </p> <p>When we arrived today we were pleasantly surprised to discover a fantastic setup including free WiFi internet and power outlets at some of the tables. We were able to whip out our laptops and get straight into business in a clean, quite environment with absolutely no hassles.</p> <p>If you are in the ACT and need a nice peaceful place to work I highly recommend checking out the local library.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-6841857629723961332010-10-03T13:10:00.001+11:002010-10-06T14:20:51.408+11:00Event Sourcing: Automatic Registration of Domain Event Handlers<p>Recently I have been investigating the use of the Command and Query Responsibility Segregation (CQRS) pattern combined with event sourcing for a personal project. I need individual client applications to be able to run completely disconnected from my server processes, but when they come back online they need to synchronise both their changes and changes made by others while they were disconnected.</p> <p>Currently the software tries to achieve this by capturing each change to the data as events detailing what changed. The problem with this approach is that we lose the “why” of the change. This becomes a problem when we have conflicting or duplicate changes which can’t determine that they are duplicates. For example someone might end up charging a client twice for something. The domain classes would normally not allow that to happen, but the data sync doesn’t know about domain rules so puts the invalid data in the database anyway.</p> <p>While investigating CQRS + Event Sourcing I have found <a href="http://cre8ivethought.com/blog/2009/11/12/cqrs--la-greg-young/">Mark Nijhof’s articles</a> and <a href="http://github.com/MarkNijhof/Fohjin">sample code</a> to be particularly helpful in demonstrating an effective implementation of those two patterns. I highly recommend checking them out.</p> <p>I have been developing a proof of concept to prove that I will be able to solve my main problems by applying these patterns. For the prototype I have been borrowing heavily from Mark’s sample code, but making modifications as I need to. One change that I have made to Mark’s code is to add a convention for registering domain event handler methods. In the sample solution Mark is registering each method manually. In his article about event handlers he does mention the possibility of setting up some sort of convention for registering them automatically, which is what I have done and I am going to share my implementation in this post. </p> <p>The only way to find methods that meet the conventions criteria is to use reflection. Calling methods by using reflection is slower than calling them from statically compiled code. I wanted my solution to be fast, but I was willing to sacrifice some speed for more painless setup. The first thing whenever performance is a question is to measure your current performance so you have something to compare against. </p> <p>My first step was to setup the following test program:</p> <p><script src="http://gist.github.com/608184.js?file=Program.cs"></script> <p></p> <p>I haven’t shown the Account class’ implementation here, but it isn’t really important. With manually registered event handlers as used in the Fohjin.DDD project it produces the following output:</p> <p><script src="http://gist.github.com/608184.js?file=ManualWireupOutput.txt"></script> <p></p> <p>For the sake of completeness the apply event method looks like this:</p> <p><script src="http://gist.github.com/608184.js?file=ManualDelegateAggregateSnippet.cs"></script> <p></p> <p>My first attempt was to simply use reflection each time an event is applied to find the method that should handle the event. My implementation looked like this:</p> <p><script src="http://gist.github.com/608184.js?file=BasicReflectionAggregateSnippet.cs"></script> <p></p> <p>And produced the following output:</p> <p><script src="http://gist.github.com/608184.js?file=BasicReflectionOutput.txt"></script> <p></p> <p>We can see from this that using reflection takes about twice as much time as manually mapping the call. That sounds bad, but the reality is that this solution is still performing well enough that it would only be in rare situations anyone would care, but seeing as how I am a little OCD when it comes to optimising things I decided to see if I could do better.</p> <p>My next approach was to do my reflection search once and then cache the results to be shared between all instances of the class. I use a static class called EventHandlerMappings (I don’t quite like that name so if you can think of a better one let me know) to manage the mapping and get my reference to the handler dictionary in the constructor and then uses it in the Apply method like so:</p> <p><script src="http://gist.github.com/608184.js?file=CachedReflectionAggregateSnippet.cs"></script> <p></p> <p>We now arrive at the following performance results.</p> <p><script src="http://gist.github.com/608184.js?file=CachedReflectionOutput.txt"></script> <p></p> <p>Now we are taking roughly 1.5 times the baseline instead of twice as long, but I still think we can do better. Instead of just caching the method info we can create a delegate from it and use that instead. The downside to this is that the first time we will pay a higher price for the conversion. This isn’t quite as straight forward as it sounds, because delegates parameters are strongly typed. We want the parameters of our delegate to be for the base types of IDomainEvent and AbstractAggregateRoot, but our method will take a specific type. To solve this problem we need to wrap our delegate call in another delegate that will cast the parameters to the correct type.</p> <p>Here is my implementation for the EventHandlerMappings:</p> <p> <p><script src="http://gist.github.com/608184.js?file=EventHandlerMappings.cs"></script> <p></p> <p>And here is my implementation of the Apply method now:</p> <p><script src="http://gist.github.com/608184.js?file=CachedDelegateAggregateSnippet.cs"></script> <p></p> <p>Which give me the following output:</p> <p><script src="http://gist.github.com/608184.js?file=AutoDelegateOutput.txt"></script> <p></p> <p>This result surprised me at first, because it is faster than the original manual implementation. After looking over things I am fairly certain that the reason it is faster is that our original code creates the handler mapping dictionary for each instance and I am guessing that is where the extra time comes from.</p> <p>It is worth mentioning that the caching code puts additional overhead on the first call for a given type. So if you are only running one or two iterations worth of code in a typical application life time then you would be better off with the straight reflection implementation.</p> <p>So there you have it, convention based automatic wireup of event handlers in an Event Sourced entity.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-76640240559862283922010-09-03T11:23:00.001+10:002010-09-03T11:23:17.151+10:00How to set a binding on a DependencyObject from code.<p></p> <p></p> <p>Sometimes it is useful to be able to set bindings on <a href="http://msdn.microsoft.com/en-us/library/system.windows.dependencyobject.aspx">DependencyObjects</a> in code. If the object you are working in derives from <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.aspx">FrameworkElement</a> you can just use the object’s <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.setbinding.aspx">SetBinding</a> method, but what if the object is derived from something else such as a <a href="http://msdn.microsoft.com/en-us/library/system.windows.freezable.aspx">Freezable</a>?</p> <p>The answer is that you use the static <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingoperations.aspx">BindingOperations</a> classes' <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingoperations.setbinding.aspx">SetBinding</a> method, which unsurprisingly is what the implementation of <em>SetBinding </em>on <em>FrameworkElement</em> calls to do its work anyway.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0tag:blogger.com,1999:blog-4142061559683950126.post-92064041981119387152010-09-02T11:13:00.000+10:002010-09-03T11:21:25.587+10:00Hello Blogosphere<p>My name is Caleb Vear and I am a software developer currently living in Canberra, Australia. I have just accepted a new role as a developer with <a href="http://readify.com.au">Readify</a>, a leading Australian-based consulting company. As part of my new role I will be doing a fair bit of travel and I hope to work on improving my skills by working on small projects that interest me during this time (along with any other free time). My hope is that I will be able to learn new technologies at the same time as making something I find useful. The plan is to share my experiences with you on this blog.</p> <p>Along with posts relating to software development I may also post about other things which I think are interesting from time to time. To make things easier my posts will be tagged so if you are only interested in a particular topic you can just subscribe to that. The following is a list of tags I am currently planning to use, others may be added later and will hopefully be self explanatory.</p> <blockquote> <p>Tech – the post relates somehow to technology.<br>Dev – the post relates to software development.<br>Politics – the post relates to politics :S.<br>Life – the post is something about my life in general.</p></blockquote> <p>This is my first post for my new blog. Previously I had a blog over on live spaces, but I hadn’t updated it in a while and I decided to start a new one with a new look. I will be reposting some of the better posts from my old blog to this one so that nobody misses out.</p> <p>That will be all for now – Caleb out.</p> Caleb Vearhttp://www.blogger.com/profile/15569349832210169851noreply@blogger.com0