RSS

Author Archives: coalvilledave

Populating Url Link properties in RESTful asp.net WebAPI projects

I recently started developing a WebApi solution that needed to return Json in the response and discovered what seems to be a common problem with populating urls in the response.

Basically it’s good practice to send urls to help clients navigate around your API. In my example, we have two entities, SoftwarePackage and Version:

SoftwarePackage:
Id : string
Name : string
CreatedOn : DateTime
Versions : IEnumerable

Version:
Name : string
Package : SoftwarePackage
Number : string
Publisher : string
CreatedOn : DateTime
Hash : string

So we populate the SoftwarePackage respository, and a GET request to /api/packages should return:

[
    {
         "id": "package-1",
          "name": "Package 1",
          "createdOn": "2017-09-08T11:32:10.1990243+01:00",
          "versions": [{
              "name": "0-0-4-5",
               "number": "0.0.4.5",
               "publisher": "John Coleman",
               "createdOn": "2017-07-09T09:42:50.1990243+01:00",
               "hash": "12345",
               "link": {
                   "title": "0.0.4.5",
                   "hRef": "http://packages.local/api/packages/package-1/0-0-4-5"
               }
           },
          {
               "name": "0-0-4-3",
               "number": "0.0.4.3",
               "publisher": "Pete Dierdon",
               "createdOn": "2017-07-26T10:46:50.1990243+01:00",
               "hash": "1223",
               "link": {
                   "title": "0.0.4.3",
                   "hRef": "http://packages.local/api/packages/package-1/0-0-4-3"
               }
           },
           {
               "name": "0-0-4-2",
               "number": "0.0.4.2",
               "publisher": "Aliyah Patel",
               "createdOn": "2017-08-19T14:17:30.1990243+01:00",
               "hash": "434243",
               "link": {
                   "title": "0.0.4.2",
                   "hRef": "http://packages.local/api/packages/package-1/0-0-4-2"
               }
           }
         ],
         "link": {
         "title": "Package 1",
         "hRef": "http://packages.local/api/packages/package-1"
     }
 },

You can see that each entity has a Link property containing a title and an hRef property to help clients consume the api. We could quite easily populate these in code but I though it would be nice to have some declarative mechanism that uses attributes and the MVC route table to generate them prior to returning the response.

I therefore created the following attributes to help us generate the urls:

RouteNameAttribute – A class attribute that tells us which route to use – the route is specified by its name
RouteParentAttribute – A property attribute that indicates that the property value should be used to generate the url for this entity
RouteParameterAttribute – This will tell our method which property to use as a route value, along with the route parameter name

I realise this may be a bit confusing so we’ll use the following as an example:

The package route is called “Package” and is as follows:
“api/packages/{id}/{v}” whereby {id} is the package id and {v} is the optional version to use.

We therefore decorate our SoftwarePackage class with the following attributes:

[RouteName("Package")]
public class SoftwarePackage : IEquatable, ILinkedResource
{
[RouteParameter("id")]
public string Id { get; set; }</code>

[LinkTitle]
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
public IList Versions { get; set; }...

The Version entity uses the same route but with the {v} parameter populated, so we can specify the attributes on our Version class like this:

[RouteName("Package")]
public class PackageVersion : IEquatable, ILinkedResource
{
[RouteParameter("v")]
public string Name { get { return Number.Replace(".", "-"); } }</code>

[RouteParent]
[JsonIgnore]
public SoftwarePackage Package { get; set; }

[LinkTitle]
public string Number { get; set; }
public string Publisher { get; set; }...

So now we need a method that can use reflection to analyse our new attributes and construct urls by first getting the route name, and then constructing a dictionary of route values using those attributes, then passing this data to the ApiControllers’s Url.Link method and using the result to populate the relevant property. I’ve implemented this method as an ApiController extension.

The controller extension will accept an instance of ILinkedResource that specifies that an entity has a Link property of type ResourceLink. It is this property that our method will fill with a title and url.

    public static class ApiControllerExtensions
    {
        public static void PopulateLinks(this ApiController controller, ILinkedResource resource, int depth = 0)
        {
            var t = resource.GetType();

            // Get dictionary containing route values
            var routeVals = GetRouteValues(resource);

            // Get route
            var routeNameAtt = t.GetCustomAttributes(typeof(RouteNameAttribute), false).Cast<RouteNameAttribute>();
            var titleAtts = t.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(LinkTitleAttribute)));

            if (depth > 0)
            {
                var childProps = t.GetProperties().Where(prop => typeof(IEnumerable<ILinkedResource>).IsAssignableFrom(prop.PropertyType));

                foreach (var childProp in childProps)
                {
                    var childResources = (IEnumerable<ILinkedResource>)childProp.GetValue(resource) ?? new List<ILinkedResource>();

                    foreach (var childResource in childResources)
                    {
                        controller.PopulateLinks(childResource, depth - 1);
                    }
                }
            }

            if (routeNameAtt.Count() != 1)
            {
                throw new InvalidOperationException(string.Format("Type {0} doesn't specify a route with the RouteName attribute, or specifies more than one route name", t.FullName));
            }

            if (titleAtts.Count() == 0)
            {
                throw new InvalidOperationException(string.Format("Type {0} doesn't have a property with LinkTitle attribute assigned", t.FullName));
            }

            if (titleAtts.Count() > 1)
            {
                throw new InvalidOperationException(string.Format("Type {0} has more than one property with LinkTitle attribute assigned", t.FullName));
            }

            // populate
            PopulateLink(controller, resource, routeNameAtt.First().RouteName, titleAtts.First().GetValue(resource).ToString(), routeVals);
        }

        private static IDictionary<string, object> GetRouteValues(ILinkedResource resource)
        {
            var results = new Dictionary<string, object>();

            var t = resource.GetType();

            // Get properties decorated with RouteParameter attribute and populate dictionary
            var props = t.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(RouteParameterAttribute)));
            var parentProp = t.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(RouteParentAttribute))).SingleOrDefault();

            foreach (var prop in props)
            {
                var val = prop.GetValue(resource);
                var pars = prop.GetCustomAttributes(typeof(RouteParameterAttribute), false).Cast<RouteParameterAttribute>();

                foreach (var par in pars)
                {
                    results.Add(par.ParameterName, val);
                }
            }

            if (parentProp != null)
            {
                var r = (ILinkedResource) parentProp.GetValue(resource);

                if (r != null)
                {
                    foreach (var kv in GetRouteValues(r))
                    {
                        results.Add(kv.Key, kv.Value);
                    }
                }
                else
                {
                    throw new ArgumentException("Property {0} of {1} must be populated in order to generate route parameteres for links");
                }
            }

            return results;
        }

        private static void PopulateLink(ApiController controller, ILinkedResource resource, string routeName, string title, IDictionary<string, object> routeVals)
        {
            try
            {
                resource.Link = new ResourceLink()
                {
                    HRef = controller.Url.Link(routeName, routeVals),
                    Title = title
                };
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
        }

    }

…and to call it from our controller:

// GET: api/Packages
public IHttpActionResult Get()
{
_repository.ToList().ForEach(i =&gt; this.PopulateLinks(i, 1) );
return Json(_repository, JsonConvert.DefaultSettings());
}

I have included the source code here – please feel free to adapt it and let me know if you see any potential improvements that could be made. This is a different approach to the one taken by Ben foster below which aims to solve the same problem. This is not a finished product and the example site give s rough idea of how this could be used. If you run the solution and go to /api/packages you will see the ‘root’ page.

References:

http://benfoster.io/blog/generating-hypermedia-links-in-aspnet-web-api

 

 
Leave a comment

Posted by on September 7, 2017 in asp.net, asp.net mvc, dotnet, Json, RESTful, WebAPI

 

ASP.NET MVC – Solution Template

I have built a number of large enterprise-grade projects in asp.net MVC over the last few years. Whenever I build new projects now I use the following structure for my solution. It allows for easy unit testing, custom membership and role providers and abstracts out the database operations into repositories.

I am always open to comments and improvements though so feel free to contact me via this site with any suggestions.

Anyway, here it is:

Solution Structure

  • Website
  • Website.Tests
  • ServiceInterface
  • ServiceImplementation
  • ServiceImplementation.Tests
  • RepositoryInterface
  • RepositoryImplementation
  • RepositoryImplementation.Tests
  • Mocks
  • Providers
  • Providers.Tests
  • DomainEntities
  • Extensions
  • Extensions.Tests

Website

This project is the asp.net MVC project as set up by the asp.net MVC project template.

Website.Tests

Contains tests for controller methods in the website. The mocked service implementation should be injected into these controllers so you are basically testing for control flow and nothing else.

ServiceInterface

Contains method signatures for ‘services’. Each fundamental domain entity class (ie such as ‘User’) should possess it’s own service interface. Methods should encapsulate well-defined use-cases such as ‘Register’, ‘PostComment’, ‘CreateGroup’ etc.

ServiceImplementation

Implementations of classes in the ServiceInterface project. Ideally these implementations will in a ‘user context’. In other words all operations are performed from that user’s perspective. Therefore Get() fetches the currently logged in user, PostComment(comment) posts a comment by the logged in user etc. The logged in user can be injected into the service instance on construction. Obviously some methods such as Register are performed anonymously.

Service implementations will more often than not require several Repository instances injecting into them on construction.

ServiceImplementation.Tests

These unit tests will test the logic and return values of the service implementation. In order to isolate the methods, you should inject the appropriate mocked repositories rather than using a repository implementation that is tied to the database.

RepositoryInterface

Classes in this project should contain simple CRUD methods to access the database and materialise the row data into instances of the classes in the DomainEntities project. It’s possible to use a generic base interface to specify the CRUD methods and just derive from that, adding any methods that are specific to each interface.

RepositoryImplementation

Contains implementations of classes in the RepositoryInterface project and will include database-specific code and/or use of any ORM tools.

RepositoryImplementation.Tests

Unit tests the repository implementation – should use a test database which is cleared after the tests have run, making execution of these tests idempotent.

Mocks

Use Mock factory classes to serve up mocks which implement classes in ServiceInterface and RepositoryInterface here. You can then call the factory methods from your test projects.

Providers

ASP.NET uses providers to perform authentication, authorisation and to provide profile information (though I’ve never actually used the latter). These providers are then specified in the web.config file.

You could use the RepositoryImplementation assembly to provide access to any data from the database here. Again, be sure to provide a way to inject any repositories so you can unit test the providers in isolation.

If you want to be able to use the providers in other solutions, just factor out a simple repository interface/class rather than use your existing repositories.

Providers.Tests

Unit tests for providers – inject repository mocks in order to isolate the functionality.

DomainEntities

Classes that provide simple business rules and logic which are used throughout the application. Anything more complicated should be factored into the ServiceImplementation. For example, methods such as User.Block(), ForumPost.Reply(Reply reply) are good candidates to include here. Any logic that alters the state of other classes as well as the one containing the method should be included in the Service Implementation rather than here.

Extensions

Any useful extension methods can go here – you can then re-use this project in other solutions.

Extensions.Tests

Nuff said.

Hope this gives someone out there a bit of a head start when setting up a nice new ASP.NET project.

 
Leave a comment

Posted by on September 24, 2013 in Uncategorized

 

Alternative to switch-case for complex comparisons

I usually try very hard to avoid non-trivial switch-case statements, they look awful. One of the limitations with switch-case is you can only use primitive types. This is fine for most cases, but sometimes you want to do a switch-case with a more complex object. For example, if you were developing a generic method that processed some value according to the type specified in the generic type argument of the method signature, switch case could not be used. Alternatively, you could use if…else if statements to decide how to process the value based on the type, as follows:

public T Parse<T>(string value) where T : struct
{
    T result;
    if(typeof(T) == typeof(int))
    {
        result = int.Parse(value);
    }
    else if(typeof(T) == typeof(long))
    {
        result = long.Parse(value);
    }
    else if(typeof(T) == typeof(short))
    { 
        result = short.Parse(value);
    }
    return (T) result;
}

This method is intended as a convenience method for parsing a string into whatever type is specified in T, we therefore do an if…else if statement on the typeof(T), calling the appropriate static Parse() method and casting/returning the result.

It’s easy to see how unmaintainable this would be once x number of type conditions were added. There is however a nice alternative, which is easily maintainable and won’t take you half an hour to scroll from top to bottom of the code block. We can use a generic dictionary to store type => function mappings and just return the outcome of the function mapped to the type. First, we need to define the dictionary. We can do this as follows:

var mappings = new Dictionary<Type, Func<Type,object>>() {
    { typeof(int), value => int.Parse(value) },
    { typeof(long), value => long.Parse(value) },
    { typeof(short), value => short.Parse(value) }
}

We can then call the appropriate method, depending on the type of T as follows:

return (T) mappings[typeof(T)](value);

This is much more compact than our unwieldy if…else if statement above, and easier to add new mappings for the various other different types should the need arise. Performance-wise I don’t know how this would compare with the if…else if block, but wouldn’t have thought there was that much difference in it for long code blocks, as Dictionary will call the GetHashCode() method of each Type instance in the dictionary’s keys, using it to quickly reference the value (the anonymous function). However I would store the dictionary in an appropriate context rather than constructing it every time the method is called, it’s up to you.

Putting it all together, here’s the whole if…else if method rewritten to use the mappings dictionary:

public T Parse<T>(string value) where T : struct
{
    var mappings = new Dictionary<Type, Func<Type,object>>() {
        { typeof(int), value => int.Parse(value) },
        { typeof(long), value => long.Parse(value) },
        { typeof(short), value => short.Parse(value) }
    }

    return (T) mappings[typeof(T)](value);
}

When you are forced to use a long, unwieldy if…else if statement due to the limitations of switch…case, this technique is well worth considering.

 
Leave a comment

Posted by on September 12, 2012 in Uncategorized

 

Javascript templated MVC framework using dojo and underscore.js

Recently I’ve been working on a client-side MVC setup for web elements and I thought it may be helpful to others if I published it. I used the opportunity to have a look at Dojo as so far I’ve only used jquery for client-side code.

My first impressions of dojo as a noob are that it is better organised than JQuery in terms of loading js files etc, and has very powerful features for writing classes in javascript. The downside in my opinion is that the documentation is inferior to jquery, it is less intuitive and the declarative markup is intrusive.

For my MVC client app I therefore decided not to use dojo widgets, and instead use a templating solution to render the views.

For those not familiar with MVC, it is a design pattern used in Object Oriented applications. Basically it separates data from it’s presentation to the user by:

  • Storing the data in a ‘Model’, which updates all its associated ‘Views’ every time it is changed
  • Using a ‘Controller’ to interact with the UI to change values in the model

I’ve created a simple diagram of how our sample app will work, as you can see, the DOM (ie the UI) interacts with our Controller via event handlers. The Controller changes the appropriate values in its Model, which then updates all its associated views which are rendered back to the DOM:

The first task was therefore to find a suitable templating solution and wrap it in a class so I can potentially change the templating engine if the one I was using fell short in any way.

In jquery I use jqote for all my client-side templating. It’s simple, intuitive and very fast. However for this project I didn’t want to have to include jquery, therefore I opted for the engine in underscore.js, which supports logic within templates and is comparable in terms of performance to jqote.

Here’s the ‘wrapper’ class I wrote to encapsulate the templating functionality:

require(['dojo/_base/declare'],
    function (declare) {

        return declare('dojoSandbox.Templater', null, {

            template: null, // contains compiled template

            constructor: function(templateString) {
                this.template = _.template(templateString);
            },

            render: function(data) {

                return this.template(data);

            }
        })
    });

I now needed to write a base class for a templated view, with some common methods to render and a couple of handlers should I need them, we’ll call the base class _TemplatedView:

require(['dojo/_base/declare',
            'dojo/text',
            'dojo/dom-construct'
            ],
    function (declare, text, domConstruct) {

        return declare('dojoSandbox._TemplatedView', null, {

            // Populate this in your sub-class constructor
            controller: null,

            // Populate this in your sub-class constructor
            containerNode: null,

            // Populate this in your sub-class constructor
            template: null,

            constructor: function() {},

            // Called prior to rendering
            onRendering: function(model) { return true; },

            // Called after rendering is complete
            onRendered: function(containerNode) { return true; },

            // Implement this method in your sub-class
            _initialise: function () {

            },

            update: function (model) {

                if(this.onRendering(model)) {

                    domConstruct.empty(this.containerNode);
                    var html = this.render(model);
                    dojo.place(html, this.containerNode, 'last');
                }
                this.onRendered(this.containerNode);

            },

            // Override this method to return your view's html to the update() function
            render: function (model) {

                return this.template.render(model);

            }

        });
    });

I store an instance of my wrapped template in the template property, which is used by the render method whch injects the model into the template and spits out the resulting html. The update function uses dojo.place to insert this html into a specified containerNode.

Next we need to write a model, a view and a controller for our app. The app we’re writing doesn’t do anything useful, just takes input in a form and displays the inputed data. Once again though, the model will contain methods that are generally useful, therefore we create another base class _Model:

require(['dojo'], function (dojo) {
    return dojo.declare('dojoSandbox._Model', null, {

        views: [],

        constructor: function () {

        },

        addView: function (view) {

            this.views.push(view);

        },

        updateViews: function () {

            for (var i = 0; i < this.views.length; i++) {

                this.views[i].update(this);

            }

        }

    });
});

This class contains a property views which is an array of view instances. The updateViews() method iterates through this array, calling each views’ update() method and passing itself (the model) as the argument for the method.

Now this is done we can create a UserModel class that derives from it, and calls it’s base class’s updateViews() method if any set methods are called on its properties:

So the view is responsible for rendering the html for our app. We’ll write a UserModel class which contains all the properties we want to be able to change, and calls base.updateViews() when any of those properties are changed. this class extends our _Model class:

require(['dojo', 'dojoSandbox/_Model'], function (dojo, _Model) {
    return dojo.declare('dojoSandbox.UserModel', [dojoSandbox._Model], {

        firstName: null,
        surname: null,
        age: null,

        constructor: function () {

        },

        setFirstName: function (firstName) {

            this.firstName = firstName;
            this.updateViews();

        },

        setSurname: function (surname) {

            this.surname = surname;
            this.updateViews();

        },

        setAge: function (age) {

            this.age = age;
            this.updateViews();

        }

    });
});

Not really much to say about this, if any of the set methods are called, it calls its base class’s updateViews() method.

We now move onto the controller class. No need for any base classes here as everything in it is specific to our user application. The controller contains a reference to it’s model, which in theory could be shifted into a base class, but in this instance I didn’t think it worth doing due to the simplicity of the app:

require(['dojo'], function (dojo) {

    return dojo.declare('dojoSandbox.UserController', null, {

        model: null,

        constructor: function (model) {

            this.model = model;

        },

        setFirstName: function (firstName) {

            this.model.setFirstName(firstName);

        },

        setSurname: function (surname) {

            this.model.setSurname(surname);

        },

        setAge: function (age) {

            this.model.setAge(age);

        }

    });

});

For this app we are just calling methods in the model.

Now all this is done, we can finally move onto the view. We’ll use our _TemplatedView class as described above and extend it as a UserView class:

require(['dojo/_base/declare',
            'dojo/text',
            'dojo/on',
            'dojo/dom-construct',
            'dojoSandbox/_TemplatedView',
            'dojoSandbox/Templater'
            ],
    function (declare, text, on, domConstruct, _TemplatedView) {

        return declare('dojoSandbox.UserView', [dojoSandbox._TemplatedView], {

            constructor: function (controller, templateString) {

                this.controller = controller;

                if (templateString) {
                    this.template = new dojoSandbox.Templater(templateString);
                } else {
                    this.template = new dojoSandbox.Templater(dojo.cache('templates', 'UserTemplate.html')); // Use default template string
                }

                controller.model.addView(this);

            },

            _initialise: function () {

                var domNode = this.containerNode;
                var controller = this.controller;

                on(domNode, '#firstName:change', function () { controller.setFirstName(this.value); });
                on(domNode, '#surname:change', function () { controller.setSurname(this.value); });
                on(domNode, '#age:change', function () { controller.setAge(this.value); });

            },

            update: function (model) {

                this.inherited(arguments);
                this._initialise();

            },

        });
    });

The constructor takes a controller as a param, and an optional template string. If no template string is provided, we’ll use a default one stored in an html file (I’ll go through this later).

This means that we can instantiate multiple instances of this View class using different templates which therefore render differently. It gives us a bit of added flexibility.

As you can see, we are caching the default template string using dojo.cache. Once the new Templater instance is created, the template is compiled ready for rendering using the injected object (more on this later).

The update() method overrides the same method in our _TemplatedView class, the only thing is adds to this however is a call to our _initialise() method which adds any handlers to the newly rendered template. In the handler code you’ll see that we are just caling the set methods in the controller instance.

Our default template looks like this:


    <label for="firstName">First Name</label>
    <input id="firstName" type="text" value="<%= firstName %>" />

    <label for="surname">Surname</label>
    <input id="surname" type="text" value="<%= surname %>" />

    <label for="age">Age</label>
    <input id="age" type="text" value="<%= age %>" />

By default, our templating engine uses the blocks to output values. If you look at the render() method in our _TemplatedView class, you’ll see that we are passing the model (which in this case will be an instance of UserModel) into the template. So the properties inside the blocks correspond to properties in our UserModel class. Bare in mind that if any of these properties have null values, ‘null’ will be inserted into the template which is not ideal.

Now thats all done, we can wire it all up in a page:

@{
    ViewBag.Title = "Home Page";
}

@section Javascript
{
<script type="text/javascript">// <![CDATA[
require([
            "dojo/parser",
            "dojo/Stateful",
            "dojo/domReady!",
            "dijit/Tooltip",
            "dijit/_TemplatedMixin",
            "dijit/form/Button",
            "dojoSandbox/_TemplatedView",
            "dojoSandbox/UserView",
            "dojoSandbox/UserController",
            "dojoSandbox/UserModel"
        ], function () {

            // Create the model
            var model = new dojoSandbox.UserModel();
            model.firstName = '';
            model.surname = '';
            model.age = '';

            // Create the controller, attaching the model to it
            var controller = new dojoSandbox.UserController(model);

            // Create 3 different templated views, specifying the controller. The controllers model will have the view assigned to it
            var view1 = new dojoSandbox.UserView(controller);
            var view2 = new dojoSandbox.UserView(controller, '



<h1><%= firstName %>&nbsp;<%= surname %>, aged <%= age %></h1>

');
            var view3 = new dojoSandbox.UserView(controller, '<textarea><%= firstName %>\n<%= surname %>\n<%= age %></textarea>');

            // Specify container nodes for each view
            view1.containerNode = dojo.byId("view1Container");
            view2.containerNode = dojo.byId("view2Container");
            view3.containerNode = dojo.byId("view3Container");

            // Refresh/render the views
            model.updateViews();

        });
// ]]></script>
}</pre>
<h2>View 1</h2>
<div id="view1Container"></div>
<h2>View 2</h2>
<div id="view2Container"></div>
<h2>View 3</h2>
<pre>

You’ll then need to add script tags to the head in your master page to load and configure dojo and our other classes:


<script type="text/javascript" src="@Url.Content(&quot;~/Scripts/underscore.js&quot;)"></script><script type="text/javascript">// <![CDATA[
        dojoConfig = {
            baseUrl: '@Url.Content("~/Scripts")',
            isDebug: true,
            tlmSiblingOfDojo: false,
            packages: [
                { name: 'dojo', location: 'dojo' },
                { name: 'dijit', location: 'dijit' },
                { name: 'dojox', location: 'dojox' },
                { name: 'dojoSandbox', location: 'classes' },
            ]
        };

// ]]></script>

<script type="text/javascript" src="@Url.Content(&quot;~/Scripts/dojo/dojo.js&quot;)" data-dojo-config="parseOnLoad: false, async: true, mvc: {debugBindings: true}"></script>

So the project structure looks like this:

Although I use asp.net MVC for this example, obviously it applies to any type of project and is easily adaptable. As you can see, first we create the model and set its properties, then we create the controller, inserting our model in the constructor. Then we instantiate the views which all use the same controller, but different templates.

All that’s left to do is specify a containerNode for each view. These are elements within our page.

For more complex apps this ‘wiring up’ could be encapsulted in another class with a root container.

I hope this helps anyone who wishes to implement a client-side MVC framework using dojo and templates. The full project can be downloaded here

 
2 Comments

Posted by on August 24, 2012 in dojo, javascript, jquery, underscore.js

 

ASP.NET MVC embedded pdf file always downloads and shows a blank page in Google Chrome

The other day I had to create a controller method to return a pdf file for the browser’s embedded viewer to display. On the whole, this was pretty easy, I quickly got the embedded file to display in IE, Opera and Firefox just using the standard File ActionResult method from the controller:

    [HttpGet]
    public ActionResult GetPdfFile()
    {
        return File("Path/To/My/PDF/File", "application/pdf", "MyPdfFile");
    }

However, on Chrome, I just got a blank page and the file was downloaded rather than displayed in the viewer. In the page that renders the viewer html I had this:

    " width="200" height="200"></embed>

After much searching on t’interweb I found the solution. The file was being downloaded because the Content-Disposition header in the response was being set by the File ActionResult method to ‘attachment; filename=MyPdfFile’. It just happened that the viewers in the other browsers weren’t taking much notice of this and the viewer was displaying it anyway. Chrome however, seemed to be handling it to the letter and downloading the file whilst showing the blank page.

The solution was to set the Content-Disposition response header to ‘inline; filename=MyPdfFile’. Therefore I added the following lines to the controller method:

    [HttpGet]
    public ActionResult GetPdfFile()
    {
        Response.Headers.Remove("Content-Disposition");
        Response.Headers.Add("Content-Disposition", "inline; filename=MyPdfFile");
        return File("Path/To/My/PDF/File", "application/pdf", "MyPdfFile");
    }

Much to my frustration, it still wasn’t working though. Turned out this was because the File method was overwriting the Content-Disposition response header with ‘attachment; filename=MyPdfFile’ because I specified the filename in the third input parameter of the method. So I changed it again to:

    [HttpGet]
    public ActionResult GetPdfFile()
    {
        Response.Headers.Remove("Content-Disposition");
        Response.Headers.Add("Content-Disposition", "inline; filename=MyPdfFile");
        return File("Path/To/My/PDF/File", "application/pdf");
    }

And it finally worked. At which point I punched the air and shouted ‘woohoo’. I just hope you found this post before trawling through various different forums trying to find an answer to this problem, to no avail.

 
2 Comments

Posted by on March 19, 2012 in asp.net, asp.net mvc, dotnet

 

Windows 7 intermittent no network connection on startup issue – how to fix

There seems to be an intermittent issue with Windows 7 whereby the network is not connected on startup. It can be fixed temporarily by right-clicking on the networking icon on the bottom right of the screen on clicking ‘Troubleshoot problems’ and going through that process. However you can fix it permanently by following this procedure:

1. Click Start Menu -> Control Panel
2. Select ‘Network and Internet’
3. Click ‘Network and Sharing Centre
4. Click ‘Change adapter settings’ in the left panel of the window
5. Select your network connection (usually ‘Local Area Connection’)
6. Right-click and select ‘Properties’
7. Click ‘Configure’
8. Select the ‘Advanced’ tab
9. Scroll down the list till you get to ‘Wiat for Link’ and select it
10. Change the value on the right to ‘Off’ using the drop down.
11. Click ‘Ok’

Hope this helps someone out there.

 
Leave a comment

Posted by on February 27, 2012 in windows 7

 

How to add custom assembly folder to the ‘Add References’ dialog in Visual Studio 2010

There are numerous pages devoted to this issue, most saying different things about where the registry key goes, and very little about the path format.

This worked for me after 10 minutes of frustration trying out different locations:

Open regedit by typing ‘regedit’ in the ‘Search Programs and Files’ field in the start menu

Expand HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx

Right click on AssemblyFoldersEx, select ‘New -> Key’

Call the new key ‘MyAssemblies’ or whatever you want

In the right hand panel, double click on the ‘Default’ item

Enter your path as follows:

C:\Path\To\My\Assemblies\Folder\

(ie don’t use ‘\\’ to as a separator and add a trailing \)

On 64 bit machines, it’s slightly different. The location in the registry is:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727\
AssemblyFoldersEx\

So add a new key there called ‘MyAssemblies’ or whatever, then change it’s default value to the path.

Hope this saves a bit of time for someone out there.

 
1 Comment

Posted by on January 19, 2012 in dotnet, visual studio

 

Manipulating the value passed for ‘id’ prior to a jeditable request

I had a proper headache with this today. I (very) occasionally use the jeditable plugin to provide in-place editing on some fields. However, one thing I don’t particularly like about jeditable (it rocks in general) is the way it sends the id of the element that fired it’s event as the value for whatever settings.id is set to. For example, if you have a list of items on the page, each with an in-place editable span, you will need to add some unique reference to each jeditable request so you can retrieve the correct element from the database, change it to whatever the user has entered, and save it. Using jeditable you would need to specify your, say, span, as follows:

<span class="inplace" id="2334">Blah</span>

The problem with this is if you have another list of elements on the same page which also have in-place editable elements. There is therefore a chance that you will render two spans on the same page with the same id. This may cause problems, and it generally isn’t very nice. You should really be ensuring that your editable span has a unique id by using a prefix in it’s id attribute, for example:

<span class="inplace" id="Comment_2334">Blah</span>

You’ve now created a new problem because of the way jeditable works. It will send the following data in the request:

{ id: 'Comment_2334', value: 'Blah' }

Which means that if, like me, you use asp.net MVC, and you use model binding in your action method:

public ActionResult SaveComment(long id, string value)

You will get a parse error when jeditable makes it’s request because it can’t parse “Comment_2334” as a long for the id parameter. You need to alter the id prior to the request being made. I searched high and low for a solution to this, and eventually concocted my own. The following will alter the id prior to the request being made, therefore not breaking model binding and using html elements with unique ids:

$('.inplace').each(function() {
    var clickedElem = this;
    $(clickedElem).editable('/Forum/SaveComment', {
        type: 'text',
        indicator: 'Saving',
        tooltip: 'Click here to edit',
        onblur: 'submit',
        select: true,
        submitdata: { id: clickedElem.id.substring(8) // Alter the id prior to the request being made - basically, omit the Comment_ prefix
    });
});

I really hope this saves someone a lot of time and stress.

 
1 Comment

Posted by on November 22, 2011 in in place editing, javascript, jeditable, jquery

 

Strings and numbers in javascript – a hall of mirrors

One of my colleagues came across an interesting idiosyncracy when coding in javascript today. Consider the following script:

<script type="text/javascript">
    alert("1" - 1);
    alert("1" + 1);
</script>

What would you think that the first alert would display? For starters it would be best to throw an error (in my opinion anyway), but in reality, “1” is convert to an int and decremented by 1, which is fine.

The second alert, however, is a different story. Would you expect it to convert “1” to an int and add 1, in a simlar fashion to the first alert? No. In actual fact the int on the right-hand side of the expression is converted to a string and concaternated onto the “1”, resulting in “11”. Bizarre. This is because of ‘ambiguities in the + operator when dealing with strings’ I’m told.

I imagine this has already confused the hell out of a lot of web developers. However, it’s unlikely that it will be changed, because it would screw up so many web sites.

 
1 Comment

Posted by on October 26, 2011 in Uncategorized

 

Using log4net with Ninject

I recently had to use log4net with ninject’s dependency injection framework and it’s logging extension. It took me a while to work it out and there didn’t seem to be a step by step guide to implementing it, so I decided to post one here.

This guide is in the context of implementing a Logger property from within a single class, in this case it was a RoleProvider to be used on a website. For the sake of the tutorial we’ll just create a simple class called SimpleRoleProvider, with a single method – GetRoles(string username):

namespace coalvilledave.tutorials.ninject
{
    using System;
    using Ninject;
    using Ninject.Extensions.Logging;
    using Ninject.Extensions.Logging.Log4net;
    using Ninject.Modules;

    public class SimpleRoleProvider
    {
        private ILogger _logger;

        public SimpleRoleProvider()
        {
        }

        public string[] GetRoles(string username)
        {
            string[] results = null;
            if (username == &quot;coalvilledave&quot;)
            {
                results = new string[] { &quot;Devs&quot;, &quot;Admins&quot;, &quot;Bloggers&quot; };
            }
            else
            {
                _logger.Error(&quot;User {0} not found&quot;, username);
                results = new string[] { };
            }
            return results;
        }
    }
}

As you can see, pretty straightforward. All we need to do now is populate the _logger field. Our implementation of ILogger is provided by the Ninject.Extensions.Logging.Log4net.Infrastructure.Log4netLogger class, which wraps around the log4net logger class that we all know and love. The Ninject.Extensions.Logging.Log4net.Log4netModule binds an ILoggerFactory with a Log4netLoggerFactory class, which we then use to get our logger. We’ll be using an IKernel implementation to instantiate the ILoggerFactory, so let’s create a little method to return an IKernel (put it just below the parameterless constructor):

protected virtual IKernel CreateKernel()
{
    var settings = new NinjectSettings { LoadExtensions = false };

    //*** PLEASE NOTE, IN LATER VERSIONS OF THE NINJECT LOGGING EXTENSIONS, THE LOG4NET MODULE TYPE NAME IS Log4NetModule (capital 'N') ***
    return new StandardKernel(settings, new INinjectModule[] { new Log4netModule() });
}

Now all we need to do is plumb it all in. We’ll do this from the constructor so our class will initialise as soon as it is instantiated – add the following inside SimpleRoleProvider’s parameterless constructor:

var kernel = this.CreateKernel();
var loggerFactory = kernel.Get&lt;ILoggerFactory&gt;();
_logger = loggerFactory.GetCurrentClassLogger();

Ok, so now we just need to create a test harness of some sort, add the log4net specific stuff to the .config file and fire it up. I’ll just use a console app for this:

namespace coalvilledave.tutorials.ninject
{
    using System;

    public class SimpleRoleProviderTester
    {
        public static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            var roleProvider = new SimpleRoleProvider();
            Console.WriteLine(roleProvider.GetRoles(&quot;coalvilledave&quot;));
            Console.WriteLine(roleProvider.GetRoles(&quot;johnsmith&quot;)); // Will log an error
        }
    }
}

The first line is VERY important, if you don’t call

log4net.Config.XmlConfigurator.Configure()

You WON’T be able to find any of the loggers specified in your configuration file.

Finally, lets configure a Logger in the App.config or Web.config file:

<?xml version='1.0'?>
<configuration>

  <configSections>
    <section name='log4net' type='log4net.Config.Log4NetConfigurationSectionHandler, log4net'/>
  </configSections>

  <log4net>

    <appender name='TestLog' type='log4net.Appender.RollingFileAppender'>
      <file value='C:/ninjecttestlog.log'/>
      <appendToFile value='true'/>
      <rollingStyle value='Date'/>
      <datePattern value='ddMMyyyy'/>
      <layout type='log4net.Layout.PatternLayout'>
        <conversionPattern value='%date [%thread] %-5level %logger [%property{NDC}] - %message%newline'/>
      </layout>
    </appender>

    <root>
      <level value='INFO'/>
      <appender-ref ref='TestLog'/>
    </root>

    <logger name='coalvilledave.tutorials.ninject.SimpleRoleProvider' additivity='false'>
      <level value='INFO'/>
      <appender-ref ref='TestLog'/>
    </logger>

  </log4net>
</configuration>

Job done! – when you run the console app, the log should appear in C:\ninjecttestlog.log

 
15 Comments

Posted by on July 22, 2011 in C# tips, dotnet, logging, ninject