Home Contact

X

Coder, not artist.

News

All code on here is free, but as a consequence it's up to you to check it, ha! If you have any questions, please use the contact button!

Twitter












Archives

Post Categories

Image Galleries

Syndication:

Mocking ITable<T>

I have to do some mocking of an ITable to be able to test some of my code, as you may imagine this is the point where we’re crossing the data boundary… Now, ITable is a total bugger to mock, I’ve tried on (at least) 3 separate occasions to get it mocked, and have only now, finally achieved an 80% solution.

(Nothing is ever 100%)

I’m not using any mock framework, they just take too long to setup (in this case) and instead have a concrete class that implements ITable and uses an IList as it’s base.

Without further ado:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;

public class MockTable<T> : ITable<T> where T : class
{
    private readonly IList<T> _entities;

    public MockTable(IList<T> entities)
    {
        _entities = entities;
    }

    #region ITable<T> Members

    public IEnumerator<T> GetEnumerator()
    {
        return _entities.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public Expression Expression 
    { 
        get 
        { 
            return _entities.AsQueryable().Expression; 
        } 
    }

    public Type ElementType 
    { 
        get 
        { 
            return _entities.AsQueryable().ElementType; 
        } 
    }

    public IQueryProvider Provider 
    { 
        get 
        { 
            return _entities.AsQueryable().Provider; 
        } 
    }

    public void InsertOnSubmit(T entity)
    {
        throw new NotImplementedException();
    }

    public void Attach(T entity)
    {
        throw new NotImplementedException();
    }

    public void DeleteOnSubmit(T entity)
    {
        throw new NotImplementedException();
    }
    #endregion ITable<T> Members
}

To use, in your test, let’s say you have an IDataContext (and why not) looking like this:

public interface IDataContext
{
    ITable<Person> People { get; set; }
}

You can then mock this interface like so:

[TestMethod]
public void Something_DoesSomething_WhenSomething()
{
    //Create seed list
    var people = new List<Person>{ new Person{Name = "Chris Skardon"} };
    
    //Create new Mock
    var dataContextMock = new Mock<IDataContext>();
    
    //Setup the People ITable property
    dataContextMock
        .Setup(dc => dc.People)
        .Returns(new MockTable<Person>(people));
    
    /* Asserts etc */
}

It’s obviously not perfect, I haven’t bothered with several methods, but I’ll get to them later…

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


CSharpCodeDomClientCodeGenerator encountered a fatal exception

I’ve been battling this now for an hour or so, and as all the reponses I’ve seen online haven’t really helped, I thought I’d whack this up..

The error I got was:

The code generator 'Microsoft.ServiceModel.DomainServices.Tools.CSharpCodeDomClientCodeGenerator' encountered a fatal exception and could not generate code for project 'TheProject.csproj':
Exception has been thrown by the target of an invocation.

Now, searching online comes up with loads of things, but the most important one I found was on Microsoft Connect. It’s actually a comment from ArielBH, which says:

From my exprience it is connected to the DataAnnotions attributes when it is looking for types in the resx.
When I tried to manipulate the Buisness Applocation template and move Ria Services link and files to other assembly I had the same issue. When I removed all references to those resx files this issue disappered.

I indeed have a class using DataAnnotations linking to a resx file… So, I removed all the attributes linking to the resx files, (i.e. removing all the validation…) and did another compile…

At this point RIA decides to actually give the correct error, that a method was missing…

So, point of note is that the DataAnnotations will mask the actual error, but once you’ve fixed the error, putting the DataAnnotations back will be fine…

Grrrr

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


InitParams in Silverlight – passed via MVC

The old skool way of passing InitParams in aspx is well documented, adding a:

<param name="initParams" value="<%=InitParams%>" />

which is accessing the public ‘InitParams’ member in the code-behind file, which is inevitably set up via the ‘Page_Init’ handler.

All well and good, but not practical in MVC, so… how to do this?

(NB. This is just how I’ve done it, it’s not the only solution)

There are a few things to change:

1. The Model

I’ve created a SilverlightHostModel, it only has one property in it (at the moment), to hold the InitParams:

namespace Webby.Models
{
    public class SilverlightHostModel
    {
        public string InitParams { get; set; }
    }
}

2. The Controller

The controller is going to create the model and pass it to the view..

public ViewResult Ria()
{
    SilverlightHostModel host = new SilverlightHostModel();
    host.InitParams = "IpAddress=" + System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

    return View(host);
}

3. The View

The view needs to be strongly-typed to the Model, so we add this to the top of the new view:

@model Webby.Models.SilverlightHostModel

and where we’re hosting the Silverlight control itself, we change the param to read:

<param name="initParams" value="@Model.InitParams"/>

4. The App.xaml.cs Application_Startup

You (I presume) already have this done, but you would get your new parameter like so

private void Application_Startup(object sender, StartupEvents e)
{
    //Get the ip address from InitParams
    string ip = e.InitParams["IpAddress"];

    this.RootVisual = new MainPage();
}

Done!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


Ajaxy

Today is the big day, the day I attempt to use Ajax in the app…

I’ve never done this (well, tell a lie, I’ve done it in a ‘tutorial’ site, but that was a while ago now), so it’s going to be interesting..

OK, basics first, let’s start with the @Ajax.ActionLink

Right, first stab:

@Ajax.ActionLink("Click to get latest",
                 "LatestEntry",
                 new AjaxOptions
                   {
                      UpdateTargetId = "ajaxEntrant",
                      InsertionMode = InsertionMode.Replace,
                      HttpMethod = "GET"
                   })

As far as I’m aware, I’m asking to get the ‘LatestEntry’ from the current controller, and in doing so, I will replace the #ajaxEntrant DOM bit with the result. So. I guess I’d better get the result working…

To the controller!

public PartialResult LatestEntry()
{
    var entrant =_db.Entrants.OrderByDescending(e => e.Id).Single();
    return PartialView("_Entrant", entrant);
}

Pretty simple, just returns the last entry in a PartialView… but! I have yet to make my partial view, so onto that!

@model Webby.Entrant

<div class="entrant">
    <h4>@Model.Name</h4>
</div>

Again, super simple, (I’m really just testing at this point)…

All the code is now there (as far as I know), so F5 and in…

And once again, in the traditionally disappointing way of the norm, it doesn’t work, sure… it opens the right view, but it doesn’t replace the #ajaxEntry DOM element, rather it replaces the whole page… The source code (again, as far as I know) looks ok:

<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#ajaxEntrants" href="/Entrants/LatestEntrant">Click to get latest</a>

Changing the InsertionMode to any of the other modes has the same effect..

It’s not the DOM name either, changing that has the same effect.. i.e. none.

It’s not the partial view either, just making that a <p> has (again) no effect…

Ahhhhh --- what a schoolboy error… I had neglected (ahem) to actually put the script bit into the calling page (another save from stackoverflow):

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

I’ve now stuck that into the _Layout.cshtml view temporarily to aid the development process… :)

Onwards and upwards!


  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


Comprehensive redesigns

So, last night I realised that I’d made some bad decisions with the database, structure and naming, so… I’ve now refactored it all, and I’m feeling… hmmm… meh about it. I suspect I will redo it all later, but for now it will do….

I’ve also come to the conclusion that I was maybe trying too much for the initial release, so as a consequence I have removed one part of the project… (which, by-the-by, I intend to have published in a month or so – and yes Andy, that is one month longer than I mentioned to you in that email :))

@Html.DisplayFor()

I find myself using DisplayFor a lot at the moment, is this correct? I mean – it works, but is that really only for forms? Do I need to use it? Should I use it?

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


Registering…

So, I want potential clients to have to enter the least amount of info possible to get an account, to that end, I really don’t see the benefit of a username and email address, I’d rather just use the email address.

Pretty easy, edit the Register.cshtml to remove all traces of a ‘username’ field…

Edit the controller so that it now reads:

   model.UserName = model.Email;
   if (ModelState.IsValid) { /*...*/ }

 

F5 and … no

Hmmm, turns out the ModelState isn’t valid, and that’s down to the fact that I’ve left in the ‘Required’ bit on the UserName property in the AccountModels RegisterModel class.

    //[Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

 

Conceivably, I don’t really need that property at all, and can probably just do away with it later, but for now it can remain… Bigger fish to fry and all that…

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

MVC–Hooking up my randomizer

Structurally, I have 3 projects, the site, the EF database and the randomizer. The randomizer uses entities from the EF database, so all is good on that front.

So, first cut, add a method to my Controller called Randomize, which takes in one of the EF entities:

public ActionResult Randomize(TableB tableB) { /*...*/ }

I’ve even given it an [HttpPost] attribute, now, I’m not anyway sure this is right, time will tell right? Anyhews, simple method:

[HttpPost]
public ActionResult Randomize(TableB tableB)
{
    var res = Randomizer.Randomize(tableB);
    return View(tableB);
}

I have no intention of this doing anything at present, I have breakpoints on both the lines to see what I am going to get..

First flaw – need to create the View, – Right click job…

Nope, that wasn’t it, is it the HttpPost?

Yes-ish

The way I’m linking was again naive… I was doing:

@Html.ActionLink("Randomize", "Randomize", new { tableB = Model})

but this only gives me a null TableB, so, best to follow the suit of things like the default edit link and switch that to an id…

@Html.ActionLink("Randomize", "Randomize", new { id = Model.Id})

aaand the appropriate method update…

public ActionResult Randomize(int id)
{
    var tb = db.TableB.SingleOrDefault(c => c.Id == id);
    if (tb == null)
        return RedirectToAction("Index");

    var rand = Randomizer.Randomize(tb);

    return View(tb);
}

as it happens, I’d also neglected to put any data in to TableB to be randomized, which did cause some minor inconveniences..

Breakpoint wise – we’re now looking good, the stuff is working but I will play with the view things in a bit. I noted that TableB wasn’t populated because I’d forgotten to add another method to allow it to be populated, so I got a bit distracted with that…

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


MVC–Day 2(or 3/4ish, maybe more)

So, my excursion in the web world continues… One of the issues I have coming from silverlight / wpf is that I’m very used to the XAML, MVVM approach to developing, I can knock up a passable interface in XAML in very little time (note, I didn’t say a good interface), but I really don’t know how to do this in CSS..

OK, not totally true, I have a rough guess, I have played with things like Firebug, and modified existing css in the past, but the problem with that, is that I’m just tinkering.

With this site, I want to learn CSS properly, from scratch, I will use the existing site.css (which is now renamed to SitOrige.css due to a ‘touchpad’ fat thumb incident in my rename attempt) to see how some things are done, but as it stands my site is now the plain html that (I presume) a screen reader should see, and I intend to get to grips with the looks soon.

Of course having done that I’m now painfully aware that without content, style is a bit pointless, sooo, on with content… I currently have 6 Controllers, (including the default Account and Home controller) the other four at present representing four of the entities I have. I don’t know if this is right, at the moment it seems like a bit of overkill, but that could be because I’ve implemented the Add/Edit/Delete bit in each controller, I guess with time I will strip those down to bare bones, buuut for now it’ll do.

I’m pretty happy (although I realise this is noddy stuff) that my links are working and I’ve actually done some Razor code hooking my entities together, and the ease of this has been very unexpected. The biggest issue I’ve had so far was when I was attempting to jump from one controller to another, I was naively using:

@Html.ActionLink(item.Name, "Details", "Controller2", new {item.Id})

When I should have been using:

@Html.ActionLink(item.Name, "Details", "Controller2", new {item.Id}, null)

That took a bit of stack overflowing to work out..

My plan forward is to try to add a bit of interactivity, I have some ‘auto-generation’ code to add some stuff into the site which I’d like to get running, at present it’s in a console app and appears to be working ok, so fingers crossed it won’t prove to be too onerous.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


MVC3–The Beginning

OOook, those who know me, or have read my blog probably have a pretty good idea that I’m a silverlight, wpf, wcf, c#, xamly kinda guy. I’ve never really done anything webby, the closest I’ve gotten is doing a bit of backend stuff, well, times change, and quite frankly I wanted to do something new… soooo

I’ve opted to go down the MVC route, for two main reasons – 1, I figured I may as well learn a good framework, 2, Matt Abbott told me that MVC lets you get dirty with HTML, and that’s one of the things I want to learn! It’s important to note..

 

I have no experience in HTML / CSS / JavaScript, so this is a windows developer going into the world of web.

 

I’ve actually been looking at this for a bit now, and I don’t really want to go too far back over what I’ve done, but, to get up to speed I have watched the PluralSight MVC course on www.asp.net/mvc and gone through the Music Store example project on CodePlex.

As it stands, architecturally, I think I’m in an ok stead, the coding looks to be ok, but I fear I will become massively unstuck with the CSS / JavaScript / JQuery side of things, but we’ll see how it goes…

I’ll try and post what I do to learn MVC and hopefully some other people in my situation can tag along Smile

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati


MousePath

Logo

A while ago, (and by that I mean over a year ago now) I was catching up on the blogs I read and came across this post:

http://blog.iso50.com/14644/mousepaths-hiroyuki-hamada/

I thought – Awesomeness! I’ll give that a go… downloaded the app, and ran it, all good – but only on one monitor… :( I work with two monitors, and found that a lot of the time I’d end up with a no lines as I was on the other monitor…

So, I thought I’d give it a go and write one myself… I actually had a working version pretty quickly, but when I say working, what I mean is one of the most impressive memory hogs and (indeed) cpu hogs I’ve written…

Gradually improvements have come along, the cpu / memory issues are much much better due to suggestions from a few people over the time I’ve mentioned it, and there are still shed loads more improvements to come along, the list would be pretty epic.

So – why upload it now? Why not do those fixes and then publish it?

Basically – I will continually tweak bits here and there, and it’ll never be done so no-one else would be able to fix it :)

So here it is, it tracks your mouse, when you pause, and not a lot else, it works on 2 monitors, and should be fine on 1 or more! It generates a picture like this:

 

Separate

Which you can then combine with a PrtScn of your desktop, to get:

Combined

Anyhews, it’s at http://mousepath.codeplex.com/ feel free to play with it etc, (there’s no build at present, so it’s source-code-build for now)…

 

Me…

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati