Posts

Single instance application

An app I am working on needs to be a single instance. It is associated with certain file extensions so that when I select a character or license file it will be imported automatically. When the user buys a character or license (etc) from the website it will be downloaded and opened, and then imported. Obviously it is a pretty poor user experience if they have to close the app, download, close the app, download... So what I really needed was a way to have the 2nd instance of the application to invoke the first instance and pass the command line parameters. Here is a simple solution I implemented using remoting. 01: An interface public interface ISingleInstance { void Execute(string[] args); } 02: A class that implements the interface public class SingleInstance : MarshalByRefObject, ISingleInstance {   private static object SyncRoot = new object();   private static Form1 MainForm;   static SingleInstance()   {     Application.EnableVisualStyles();     Application.SetCompatibleText

More leak fixes

I have changed the DirtyObjectCatcher so that it initially only hooks Form.Disposed - Automatically disposes the DirtyObjectCatcher Form.Closed - Unhooks all additional form events (below) Form.Shown - To hook additional form events (below) ==Additional form events== Form.Activated Form.MdiParent.Activated Form.MdiChildActivate The additional events are to ensure that the DirtyObjectCatcher's undo block is moved to the top. The reason that these events are now unhooked is so that there is no strong event references from the application's main form (Form.MdiParent) to this component, keeping it alive. Now we only have long-term event references from the owning form itself. Really though this is just an added precaution against something I may not have thought of :-) The true memory saver comes from only holding a WeakReference to the owning form. Otherwise in an MDI application we have the following MainForm.MdiChildActivate->DirtyObjectCatcher->Form In such a case c

Memory leaks

As a follow up to yesterday's post here is a list of problems I found... 01: The following code for some reason causes the form holding the DirtyObjectCatcher to remain referenced. if (Owner.MdiParent != null) { Owner.MdiParent.Activated += new EventHandler(MdiParent_Activated); Owner.MdiParent.MdiChildActivate += new EventHandler(MdiParent_MdiChildActivate); } The odd thing about this is that it really is the events that matter! I subscribe Shown, Disposed, Activated on the Owner (which is a form) and that doesn't cause the same behaviour. The reason is that the Owner normally gets disposed and takes out the DirtyObjectCatcher with it, however, if I have Owner.MdiParent events referencing DirtyObjectCatcher then the form will never get disposed because DirtyObjectCatcher has a strong reference to Owner. Maybe I should change it, but for now the Shown and Activated events seem to be doing the trick. 02: This one was a real pain! DirtyObjectCatcher creates its own Undo

DirtyObjectCatcher

Oh boy, what a nightmare! After days of messing around I finally found where the memory leak is in my app, it was in DirtyObjectCatcher! The DirtyObjectCatcher used to subscribe to the DirtyListService, so that it was notified whenever an object was made dirty. I experienced this problem... 01: User creates a "Call" to a customer site. 02: User edits a purchase order. 03: Save purchase order (merges the undo block to the Call undo block and closes the form) 04: Edit the purchase order again from the Call form The PurchaseOrder is already dirty so it wont get triggered again, this used to result in no constraints being checked etc and the possibility of entering dodgy data. The solution at the time was to have a static list in DirtyObjectCatcher private List Instances; whenever a new instance was created it would be added, whenever Dispose was called it would be removed. I then hooked into the cache chain and whenever a value changed I would call a static method on DirtyObjec

TeamCoherence - disaster!

That's it, my short evaluation of TC is over! Problem 1: I emailed support with a question weeks ago, didn't get a response. Not impressed. Problem 2: I reinstalled my O/S recently so had to restore my version control folder. When I try to check files out I now get an "Object not found" error, whatever that means? Some searching reveals it is a bug that has been fixed in the version I have, I beg to differ. Problem 3: This one was the worst! I use TC client for a customer already which is why I decided to try out the server. I connected to the customer server, checked out loads of files, upgraded my VS2005 project to VS2008 and then checked everything back in. What a disaster! TC had replaced the source in the customer files with source from my private local server! I couldn't believe it! As I looked through Assembly.cs files I could see WinForm code from the last project I worked on locally! This is obviously bad because I had exposed source code from one concern

TimeBasedSyncHandler

I recently had to tweak my remote persistence server settings. I noticed that I had leaft the SyncHandler.HistoryLength at the default value of 10,000 items. This was overkill because my clients sync every 3 seconds. I thought maybe I should drop this down to about 100, that should be okay? Each client only does about one update every few minutes so I it should, right? Problem is not all of my users are people. One user is a messenger service which looks for unsent messages, sends them one at a time, marking each in turn as sent and updating the database. This gets run every five minutes so probably sends about fifty messages at the most, but what if someone decides to change it to ten minutes, or thirty? So maybe I should increase the HistoryLength to about 200? Then there is the other client, this one syncs with an external database. This could perform hundreds of updates every minute. If the messenger is set to run every thirty minutes...I'm not sure what a good History

Making a generic type from a Type

List<Person> p = new List<Person>(); This works fine, but what about this? Type someType = typeof(Person); List<someType> p = new List<someType>(); Nope! But you can do this... Type genericType = typeof(List<>).MakeGenericType(someType); Why would I want to? Because I am creating a tool that generates plain old .NET objects from an EcoSpace's model, and I wanted to implement multi-role association ends as public List<Building> RoleName; rather than just public Building[] RoleName;

Returning a binary respose in ASP MVC RC3

In a previous post I showed how to return a binary file from a controller action, well, this no longer works in release candidate 3 of the framework. Instead you have to create a new ActionResult descendant to do the job for you. This is how I did it.... return new BinaryResult(data, Path.GetFileName(productFileName)); and the class is implemented like so: public class BinaryResult : ActionResult { private string ClientFileName; private byte[] Data; private string VirtualFileName; public BinaryResult(string virtualFileName, string clientFileName) { if (string.IsNullOrEmpty(virtualFileName)) throw new ArgumentNullException("VirtualFileName"); if (string.IsNullOrEmpty(clientFileName)) throw new ArgumentNullException("ClientFileName"); ClientFileName = clientFileName; VirtualFileName = virtualFileName; } public BinaryResult(byte[] data, string clientFileName) { if (data == null) throw new ArgumentNullException(&q

ASP MVC preview 3 released

I'm trying to upgrade from Preview 2 to Preview 3. I think the idea of having each action return an ActionResult was a good one, so far it has actually made my code slightly smaller. What I don't understand though is why Html.Select seems to have disappeared... Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1501: No overload for method 'Select' takes '5' arguments Source Error: Line 8: Product Line 9: Line 10: <%= Html.Select("SoftwareID", (object)ViewData["SoftwareList"], "Name", "ID", (object)ViewData["SoftwareID"]) %> Line 11: Line 12: When I go into the APX and type Html. there is no Select method listed along with

Hooking into ECO multi-association events

Although I have not (yet) needed this myself I can see myself needing it in the future and the question has been asked before. "Setting HasUserCode=True on a Child.Parent single role does what I want, but how do I handle the scenario where Parent.Children.Add(item) is called on a multirole?" By default you can’t, but with the addition of a single class and a small amount of tweaking you can get it to do what you want! Here is how to do it: 01: Mark Parent.Children’s association end with HasUserCode=True in the modeler and then generate code. 02: In the source code of your class (not within an ECO region) add the following   private EcoMultiAssociation<Child> m_Children; This is a class that does not yet exist, I will show the source code for it later. 02: In the source code locate the "Children" property and change it like so   public IEcoList<Child> Children   {     get     {       if (m_Children == null)       {         m_Children= new EcoMultiAssocia

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