Posts

Using Vista Aero theme in XP WPF apps

I found this article on the web recently which shows how to use the Vista Aero theme on XP in your WPF apps. I found two things: 01: It is less complicated that the article states. 02: It is a bit different if you already have stuff in your app resources, such as styles or control templates etc. So here are my steps 01: Add PresentationFramework.Aero to your applications References list. It is listed in the [.NET] tab. 02: Edit your App.xaml and change it from this <Application.Resources>   <!-- Your stuff here --> </Application.Resources> to this <Application.Resources>   <ResourceDictionary>     <!-- Put your stuff here instead -->     <ResourceDictionary.MergedDictionaries>       <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/aero.normalcolor.xaml"/>     </ResourceDictionary.MergedDictionaries>   </ResourceDictionary> </Application.Resources>

Selecting WPF ListView row in code

An app I am considering migrating to WPF uses a DevExpress grid to show a list of events, as I animate my composition I highlight the current event in the grid. Things I have learned about WPF: 01: You can create a data grid type view like so: <ListView Name="ListView">   <ListView.View>     <GridView AllowsColumnReorder="False">       <GridViewColumn DisplayMemberBinding="{Binding Path=Title}" Header="Title"/>       <GridViewColumn DisplayMemberBinding="{Binding Path=FirstName}" Header="FirstName"/>       <GridViewColumn DisplayMemberBinding="{Binding Path=LastName}" Header="LastName"/>     </GridView>   </ListView.View> </ListView> 02: Don’t put a ListView in a <StackPanel>! It renders all of the data at once. When you have 6K rows of data for example it takes about 1 second to select the next row. Instead you should put it in a grid <Gri

Creating a drop shadow

Requirement: Take a PNG image that has an alpha mask and from it generate a new bitmap which has the same alpha mask but every pixel is black. Solution: private Bitmap GenerateDropShadowImage(Image image) {   Bitmap bitmap = new Bitmap(image);   BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);   IntPtr bottomScanLine = bits.Scan0;   int bytesPerRow = bits.Width * 4;   unsafe   {     byte* pixelValue = (byte*)bottomScanLine.ToPointer();     for (int count = 0; count < bits.Width * bits.Height; count++)     {       pixelValue[0] = 0;       pixelValue[1] = 0;       pixelValue[2] = 0;       pixelValue = pixelValue + 4;     }   }   bitmap.UnlockBits(bits);   return bitmap; }

WPF custom button templates

Image
I’ve had a bit of a play with WPF for the first time today. I decided to create my own button template. The idea of a template is that you can redefine the visual elements that make up the control. Create a new WPF application Now add a button within the grid like so  <Grid>   <Button Content="Click me" Width="150" Height="50"/>  </Grid> So that we can see what we are designing add a gradient background to the window. Within the <Window> node add  <Window.Background>   <LinearGradientBrush>    <GradientStop Color="Black" Offset="0"/>    <GradientStop Color="White" Offset="1"/>   </LinearGradientBrush>  </Window.Background> Now to start designing the button template. Within the <Window> node add  <Window.Resources>  </Window.Resources> this is where we will add the template, within that new node add the following  <ControlTemplate x

Binary response in ASP MVC

Today I wanted to give access to certain files on a website only via my DownloadController. This was so that I could ensure the current user had purchased the item in question first, and also sign any license info into the download aswell. I tried getting a URL like this to work http://localhost/download/1/SomeFileName which would remap to the DownloadController public void Index(int id, string fileName) This worked fine, and because the URL ended with "SomeFileName" it would get saved as the correct filename too, but this was no use because SomeFileName has no file extension. As soon as I added .zip on the end the request no longer went via the new HttpHandler in the MVC web extensions. Even when I added it in the <httpHandlers> section of web.config it just wouldn’t work. My problem was in relying on the url for the filename. This is apprarently not the way it should be done. Instead I should have stuck to the standard URL approach http://localhost/download/1 an

Silverlight and webservices

First download the binaries you need from here: http://silverlight.net/GetStarted/ Next run VS2008 and create a new project. Select the Silverlight node and then the Silverlight Application node. ProjectName = MySilverlightApp Tick the checkbox "Create directory for solution" Click OK On the wizard page you want the default values: * Add a new page to the solution for hosting the control Project type = Web Site Name = MyWebService Now delete the two ASPX files, we wont be needing those. Rename the HTML page to Index.html and set it as the project start page. Right click the website project and select "Add new item". Select "Web Service". Name = DateTimeService.asmx Click ADD Change the HelloWorld method to public DateTime GetServerDateTime() {   return DateTime.Now; } Right-click the References node on the Silverlight project and select "Add service reference". Click the "Discover" button, and in the tree view that appears select the Da

Postal codes within a radius

My hobby MVC website allows people to place adverts. When searching for adverts I would like the user to be able to specify a UK postal code and radius to filter the adverts down to ones within travelling distance. The trick to this was to record a list of UK postal codes and their latitude/longitude. The first step is to write a routine which will give a straight line distance between to coordinates: public static class MathExtender {   public static double GetDistanceBetweenPoints(double sourceLatitude, double sourceLongitude, double destLatitude, double destLongitude)   {     double theta = sourceLongitude - destLongitude;     double distance =       Math.Sin(DegToRad(sourceLatitude))       * Math.Sin(DegToRad(destLatitude))       + Math.Cos(DegToRad(sourceLatitude))       * Math.Cos(DegToRad(destLatitude))       * Math.Cos(DegToRad(theta));     distance = Math.Acos(distance);     distance = RadToDeg(distance);     distance = distance * 60 * 1.1515;     return (distance);   }   p

Test Driven MVC and ECO

I have decided that mocking IEcoServiceProvider is not the way to go. Your controller will use the mocked provider during testing but   You don’t want to have to mock every service the provider may return, it’s a lot of work!   You don’t want your controller using a mocked service, and then the EcoSpace using the real one! At first I was mocking every possible service request. IUndoService, IPersistenceService, IOclService, etc. I get bored typing them out in this blog, so doing it in tests was really annoying me. I decided I would instead only mock the service in question. So if I were ensuring that an action wont save an object with broken constraints I would mock GetEcoService<IConstraintProvider> and ensure that I always got a broken constraint. The problem was that the test to ensure I can save a valid object would then invoke the IPersistenceService.UpdateDatabaseWithList method. In my EcoSpace I have decorated my persistence service so that it checks every object i

ECO, LINQ, Anonymous types, and Web Extensions

I’ve been finding LINQ + Anonymous types really compliment ECO and the new ASP web extensions approach to writing websites. I may have mentioned recently that I don’t like the idea of passing instances of my business objects to the presentation layer. The reason is that someone else will be writing the views for this site and I want to be able to control what they are capable of displaying. It’s not just that though, the fact is that your view might need to look completely different to how your business classes are structured, one layer should not dictate the structure of another. The example I am about to show does in fact have similar structures for the view and model. Having said that there is a slight difference in that the MinorVersion class has its own "int VersionNumber" property, and gets the major part of the version number from self.MajorVersion.VersionNumber. Anyway, now to get on with it. My requirement was to show all major versions, within each major versio

Custom config sections

The website I am writing will sell some software I have already written. In addition it will sell "Collateral", which is basically support files for the software. The software itself will only run if it finds a license, which is an RSA signed binary file containing information such as the email address of the licensee. In addition some kinds of collateral will also be RSA signed with the licensee’s email address so that it will only work for that user, but not all collateral types are signed, for example a Character is a custom file format and is signed but a WAV file will not be signed. So this website needs to sell software + provide a license. It also needs to sell collateral, some of which will require signing and some of which will not. Software and Collateral are both types of Product, and you can buy a Product. The problem is how should I deal with the 3 different types of licensing (license file, signed binary, no license)? In addition to this should I really cr

All users

Yesterday I needed my app to read and write data from a folder to which all users have access. Having the data in the current user's data folder was unacceptible as this would have resulted in duplicate data storages, the MSI installer even generates a compiler warning telling me I shouldn’t use this folder! So I went for Environment.GetFolderPath(SpecialFolder.CommonApplicationData); This seemed to work fine until I tested on Vista, at which point my app would "stop responding" and quit. With a bit of investigation I discovered that CommonApplicationData maps to c:\ProgramData on Vista, which to me looked good until I tried creating a read/write FileStream in that path and received an access denied exception. So, where was I supposed to store my data? Checking each of the values in the SpecialFolder enum I was surprised to see that there doesn&#8217't seem to be a suitable value. So, I reflected over Environment.GetFolderPath and copied the code. I then sta

Embedded Firebird, error trying to write to file

This error has been really annoying me tonight! I have an app that uses Embedded Firebird for its DB so that I don't need to install a DB server. On Vista my app throws an exception "Error trying to write to file (the correct path here)". I recreated the DB on my development machine (XP) and tried running it, it should work, it has for months, but it didn't! The same error too! For the life of me I couldn't work out why it would suddenly stop working on both machines, what did they have in common? I uninstalled stuff, reinstalled it, etc, no joy. The answer on my XP box was simple. I used the local server to create the GDB file + generate my DB structure using ECO. What I hadn't thought of was the fact that the firebird server then holds a file handle open on that GDB file in case I want to use it again. Embedded firebird needs an exclusive lock on the file so this was the problem on my XP box. I wish the error had read something like "Error tryin

Test driven ECO

Here are my latest revelations :-) 01 Instead of having to mock IEcoServiceProvider and IOclPsService in order to avoid DB access simply use PersistenceMapperMemory. This way I can create the objects I want, UpdateDatabase, and then run my tests. It’s much easier to read, and more importantly less typing. 02 My page controllers no longer use an EcoSpace. Instead the code always uses a ServiceProvider property of type IEcoServiceProvider. When I want to test my controller I create an instance and set its ServiceProvider property. Now whenever the controller needs to do anything it will go through the ServiceProvider I specified. This is beneficial for a number of reasons. Firstly it means that I can create an EcoSpace in my test and set its PersistenceMapper to PersistenceMapperMemory before activating it. Secondly I can also opt to pass a mocked IEcoServiceProvider which either returns the real service requested or returns a mocked one. An example of this is that I validate my

ECO, should we mock it?

I watched a video on Rhino Mocks yesterday. What a great framework! Obviously I wanted to know if I could use this with ECO so I thought I'd give it a try. In my website's AccountController there is a method like so public void AttemptLogin(string emailAddress, string password, string redirectUrl) { } Now I could just go ahead and write some OCL to find the user, but instead of doing this I really want to separate the code a bit. So I created a class public class UserRepository {   private readonly IEcoServiceProvider ServiceProvider;   public UserRepository(IEcoServiceProvider serviceProvider)   {     ServiceProvider = serviceProvider;   }   public User GetByEmailAddressAndPassword(string emailAddress, string password)   {     string searchEmail = BusinessClassesHelper.EscapeOcl(emailAddress);     string criteria = string.Format("->select(emailAddress.sqlLikeCaseInsensitive('{0}'))", searchEmail);     return BusinessClassesHelper.SelectFirstObject<Us

Unit testing MonoRail controllers

I spent yesterday finishing off (mostly) my business model, then the end of yesterday + today writing test cases for those classes. Everything was going great, I found at least 3 errors in my code that I hadn’t realised was there and also realised there were a few more things I needed. Then it was time to start testing the controllers in my MonoRail site. What a disaster! Attempt 1: [Test] public void AdminOnly_Home() {   AdminController controller = new AdminController();   controller.Home();   Assert.IsTrue(Controller.Response.WasRedirected, "Should have been redirected"); } The problem with this was pretty obvious, Controller doesn’t have a Response etc set up. So along came attempt 2: [Test] public void AdminOnly_Home() {   AdminController controller = new AdminController();   PrepareController(controller);   controller.Home();   Assert.IsTrue(Controller.Response.WasRedirected, "Should have been redirected"); } Now the controller is set up with mock objects a

Validation

I have a model like so Product 1----* ProductVersion ProductVersion 1----* ProductEdition ProductVersion can been in one of two states: UnderDevelopment / Released ProductEdition has a DownloadUrl:string attribute which is only required if self.version.status = #Released The validation for ProductEdition works perfectly, I cannot leave the DownloadUrl blank if the ProductVersion has already been released. Unfortunately when I already have a number of ProductEdition instances with no DownloadUrl and then make my Productversion live the editions are not validated because they are not dirty. So I needed some way to ensure that when ProductVersion is validated all related ProductEdition instances are also validated. Step 01: Add a way to allow ProductVersion to identify other objects to be validated. In the business classes project I added the following interface. public interface IValidationExtender {   IEnumerable GetConstraintedObjects(); } My ProductVersion can do this IEnumerable

EcoRail

The whole idea of having a controller and a view is so that the view renders only exactly what it is given, and the controller is able to give it whatever data it likes from wherever it needs to obtain it. After working with ECO and Monorail for a while it has been a real pleasure, but I am starting to think that maybe exposing ECO objects directly to the view is not the right approach. If for example I put an Employee into the PropertyBag the view can easily display $Employee.Salary. This might not be a problem when you develop both the controllers and the view but in my case someone else will ultimately create the views. Do I really want them to be able to have access to this information? In addition, what if the view engine they use has a scripting language that is able to set values? Setting $Employee will merely set the PropertyBag["Employee"] value, but setting $Employee.Salary could see a certain view developer buying a new car next month. I am very tempted to chan

Your bug is my bug

I recently released an update to some software and a bug slipped through the net. It introduced some odd behaviour with a control named SmartGrid. After some testing I was able to determine that it wasn't my fault and that I could reproduce a bug in SmartGrid. I hate bugs in other people's source code, I can't fix it, I am at their complete mercy. Thankfully the Resco support was amazing! I posted on their forums and immediately someone sent me instructions on where to send my project. The next morning I was disappointed to see an email saying that the project worked fine. I posted again and almost immediately someone had offered to chat on skype. We did that for a while, both confused by the problem. We then went on to use Remote Assistance so that he could observe my bug which he wasn't experiencing. In the end the problem was very confusing. I had Version A of the DLL in which the error occurred. I upgraded to the latest version (B) and it still occurred. T

Converting a recurring decimal to a fraction

For a couple of hours a week I am doing a beginner's level maths course. The topic today was converting recurring decimals into fractions. For example (the [] are the repeating digits 0.[6]  1x = 0.[6] 10x = 6.[6] 9x = 10x - 1x 9x = 6.[6] - 0.[6] = 6 Therefore the answer is 6/9, or 2/3 When it got to numbers like 0.12[34] (ie 0.12343434343434.....) the lesson was really complicated, but I came up with a more simple approach, so here it is if ever you need it. My first observation was that we need a large number and a small number. So let's start with the 10x we used above  1x = 0.12[34] 10x = 1.2[34] therefore 9x = 10x - 1x which is  1.2[34] -0.12[34] This is going to give us 1.1(something) My second observation is that fractions cannot have decimal values in them. In order to get rid of the fraction we need the big number to have the exact same fraction as the small number. e.g.  B.[34] -S.[34] =X.[00] So our small number needs to end with [34]. Given the number 0.12[34]

MaxLength

Implementing HTML maxlength was a bit of a pain. Not to write the helpers though, that was easy.... $EcoModelHelper.AttributeLength($Product, "ID") But when it came to specifying that in the <input> it was too much work! This is how it is done statically... $FormHelper.TextFieldValue("Product.ID", $Product.ID, "%{maxlength='32'}") Now I had to replace the static 32 with the EcoModelHelper code. #set ($ProductIDLength = $EcoModelHelper.AttributeLength($Product, "ID")) $FormHelper.TextFieldValue("Product.ID", $Product.ID, "%{maxlength='$ProductIDLength'}") This was starting to look like too much typing! So instead I have decided to add new methods to the EcoFormHelper. Here is the first: $EcoFormHelper.ObjectTextField("Product.ID", $Product, "ID") This will output something like this <input type="text" id="Product_ID" name="Product.ID" value="Alt

EcoRail validation

Here is yesterday's update. I wanted a way to validate the user input. Seeing as there are constraints in the model to me this was the obvious approach to take. The HTML in my main layout (MasterPage) was changed like so <body>   #if ($Errors && $Errors.Count > 0)     <ul class="errors">       #foreach ($currentError in $Errors)         <li>$currentError</li>       #end     </ul>   #end   $childContent </body> This outputs all errors passed in PropertyBag["Errors"] or in my case I used Flash["Errors"]. To validate my product input I changed my controller like so: [AllowEcoSpaceDeactivateDirty(true)] public void Modify([EcoDataBind("Product", Allow = "ID,Name", NoObjectIdAction = ObjectIdAction.CreateNewInstance)]Product product) {   PropertyBag["Product"] = product;   IList<string> errors = GetErrorsForAllDirtyObjects();   if (errors.Count > 0)     Flash["Erro