Posts

Showing posts with the label C#

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

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

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

MonoRail

I'm working on a new website for work. I've decided to use ECO for the business model due to how much time it saves me. I took a look at the new MVC ASP approach provided by Microsoft recently and was a bit disappointed. There were bugs in some pretty basic errors that would have been an annoyance to code around, and it just didn't feel "ready". So, I've decided to take another look at MonoRail. I'd already written an ECO implementation for MR in the past but I decided to start the implementation from scratch. This was mainly inspired by the new EcoSpaceManager in ECOIV for ASP .NET. Using an EcoSpaceManager you can easily utilise many instances of different types of EcoSpace in the same page. I decided I would do the same. Unlike the EcoSpaceManager I haven't gone for unique string values for identifying the EcoSpace instance I want. That approach is good in ASP .NET where you want to bind different components together to generate your HTML bu

Single application instance

I needed my app to be a single-instance app. It was easy to implement, like so: bool mutexIsNew; Mutex mutex = new Mutex(true, "SomeUniqueID", out mutexIsNew); if (mutexIsNew) Application.Run(new MainForm()); A problem arose though when my app started to need to receive command line arguments. How do you also pass those onto the original app? There is a class for this purpose named "WindowsFormsApplicationBase", it's in Microsoft.VisualBasic.dll 01: Add a class to your project like so: internal class SingleInstanceApplication : WindowsFormsApplicationBase { private MainForm MainFormInstance; internal SingleInstanceApplication() { IsSingleInstance = true; EnableVisualStyles = true; MainFormInstance = new MainForm(); MainForm = MainFormInstance; } protected override bool OnStartup(StartupEventArgs eventArgs) { return base.OnStartup(eventArgs); MainFormInstance.AcceptCommandArguments(eventArgs.CommandLine); } protected o

RSA signed streams

I'm writing an app that needs me to be able to write to a file and make sure that nobody changes it. The idea that I had was to create 2 classes: WritableSignedStream: Accepts a targetStream parameter + a privateKeyXml string. I add some space at the beginning of the target stream to reserve it for header info. You then write to the stream as normal (it reports a smaller Length than that of the target stream so your app is unaware of the header). When you close the stream it writes the public key to the stream + an RSA encrypted hash of the data part of the file. ReadableSignedStream: Accepts a sourceStream parameter in the constructor. Just before you read for the first time it will compute an MD5 hash of the data part of the file, and then compare it with the signed hash in the file (which I first decrypt using the stored public key). These classes therefore provide two functions: You can sign a stream, the app can check the stream was signed by you by inspecting the public key w

No symbols loaded

This has been driving me mad for hours now! Whenever I run my PocketPC compact framework app I cannot debug it! None of the breakpoints will stop, each breakpoint just shows as an empty circle instead of a solid one. So, what was the solution? I tried deleting all PDB files on my hard disk but that didn't do it. In the end manually deleting all of the files previously deployed to my PPC did the trick. Maybe VS couldn't overwrite them or something? No idea, but at least it works now :-)

Derived properties that you don't want cached

I'm rewriting a Win32 application using ECO. One of the things this application allows the user to do is to specify their preferred unit of measurement for height, distance, depth, weight, and speed. To achieve this I have an ECO class ApplicationSettings which is a singleton which identifies the units to use. I then have 2 properties for each value.... InternalLandingDistance DisplayLandingDistance The idea is that I should never expose Internal* properties in the GUI but display their corresponding Display* property instead. The Display* property will read/write the Internal* property and perform some kind of conversion on it. If I always store my values using the unit with the highest accuracy (Distance = feet, Depth = millimetres, Weight = Pounds, Speed = KPH) then I just need to convert them by the correct factor when reading/writing from the Display* properties. This isn't rocket science, obviously I can just implement these as reverse derived attributes right? The pr

RetrieveChanges(out ignoredChanges)

Here's another quick blog about a new ECO IV feature. I asked for this during development because I had a particular problem I had to solve. My new application has a class named "PlannedCall". When the user logs in they see a list of planned calls that are A: Active B: Not already actioned C: Assigned to the current user, or not assigned to anyone D: EarliestCallTime <= Today + 1 As time goes on there will be a lot of instances of this class in my DB, so obviously I want to use the OclPSHandle to select my objects otherwise I will end up with a whole load of objects in memory that I do not need. However, when another user actions the planned call the Actioned property becomes true. If I use an ExpressionHandle then this planned call would disappear from the presented list, but with OclPSHandle it will not. This is where the new feature comes in! When you call PersistenceService.RetrieveChanges a collection of DBChange will be sent to the client from the server. T

More secure passwords

Storing a plain-text password in a DB leaves your system open to abuse from anybody with access to the tables (sys admin for example). Here is the technique I recently used. Instead of storing the password itself I store a hash of the password, and a random "salt" that was used to create the hash to make it less predictable. [UmlTaggedValue("Eco.Length", "255")] private string PasswordHash { get { ... } set { ... } } [UmlTaggedValue("Eco.AllowNULL", "True")] [UmlTaggedValue("Eco.Length", "40")] private string PasswordSalt { get { ... } set { ... } } As you can see I do not store the password, just a hash + salt, both of which are private. Here are the methods used to set the values of these properties. public void SetPassword(string newPassword) { if (newPassword == null) throw new ArgumentNullException("password"); if (newPassword.Length < 6) throw new