Cymen's Blog

Archive for the ‘Web Development’ Category

ASP.NET MVC and DropDownList: One approach…

leave a comment

One thing that I’m not particularly fond of in ASP.NET MVC is figuring out where to put additional data one needs for views. If one is using a “model per view” approach it is simple — stick it in that model. Otherwise you can choose to add it to a model that won’t always need it or pass it via ViewBag/ViewState. I currently lean towards the last option.

The other annoyance is how best to transform a list of objects into a IEnumerable<SelectListItem> collection cleanly with the special case of handling a default value. I have started to approach this with extension methods and am very happy with how it is working.

Transforming your List<MyObject> to IEnumerable<SelectListItem>

Our current data tier has a manager class for each object type. When that object type is going to be used in a select list, I add an extension to IEnumerable<MyObject> like so:

    public static class MyObjectManagerExtensions
    {
        public static IEnumerable AsSelectList(this IEnumerable list, int? value)
        {
            return (from item in list
                    select new SelectListItem
                    {
                        Selected = value.HasValue && item.Id == value.Value,
                        Text = item.Name,
                        Value = item.Id.ToString()
                    });
        }
    }

To support the option of a default value, I have an extension method that applies to IEnumerable:

    public static class SelectListExtension
    {
        public static IEnumerable WithDefault(this IEnumerable list, string defaultLabel = "Select one...", string value = "")
        {
            return (new[] { new SelectListItem { Text = defaultLabel, Value = value } }).Concat(list);
        }
    }

Here is an example of an actually call to this methods in:

ViewBag.MyObject = myObjectManager
                       .GetAllMyObjectBy(isForFoo: true, orderBy: MyObjectColumns.Name)
                       .AsSelectList(myObjectId)
                       .WithDefault();

Written by Cymen

November 18th, 2011 at 8:55 am

Posted in ASP.NET MVC

Mime types for ASP.NET

leave a comment

One of the annoyances working on the Windows/IIS stack is that getting mime types is a pain. They are located in multiple places and there is no really ideal “best practice” method to get mime types without what I consider overly-complicated solutions. In light of this observation I wrote a basic C# program that fetches the mime.types file from the Apache project and converts it to a C# Dictionary keyed by file extension. It is a basic program but might be useful for others wondering why in the world this is so complicated.

ApacheMimeTypesToDotNet on github

The output looks like this: ApacheMimeTypes.cs

using System;
using System.Collections.Generic;

namespace ApacheMimeTypes
{
	class Apache
	{
		public static Dictionary MimeTypes = new Dictionary
		{
			{ "123", "application/vnd.lotus-1-2-3" },
			{ "3dml", "text/vnd.in3d.3dml" },
			{ "3g2", "video/3gpp2" },
			{ "3gp", "video/3gpp" },
			{ "7z", "application/x-7z-compressed" },
			{ "aab", "application/x-authorware-bin" },
			{ "aac", "audio/x-aac" },
			{ "aam", "application/x-authorware-map" },
			{ "aas", "application/x-authorware-seg" },
			{ "abw", "application/x-abiword" },
			{ "ac", "application/pkix-attr-cert" },
			{ "acc", "application/vnd.americandynamics.acc" },
			{ "ace", "application/x-ace-compressed" },
			{ "acu", "application/vnd.acucobol" },
			{ "acutc", "application/vnd.acucorp" },
			{ "adp", "audio/adpcm" },
			{ "aep", "application/vnd.audiograph" },
			{ "afm", "application/x-font-type1" },
			{ "afp", "application/vnd.ibm.modcap" },
			{ "ahead", "application/vnd.ahead.space" },
			{ "ai", "application/postscript" },
			{ "aif", "audio/x-aiff" },
			{ "aifc", "audio/x-aiff" },
			{ "aiff", "audio/x-aiff" },
			{ "air", "application/vnd.adobe.air-application-installer-package+zip" },
			{ "ait", "application/vnd.dvb.ait" },
			{ "ami", "application/vnd.amiga.ami" },
			{ "apk", "application/vnd.android.package-archive" },
			{ "application", "application/x-ms-application" },
			{ "apr", "application/vnd.lotus-approach" },
			{ "asc", "application/pgp-signature" },
			{ "asf", "video/x-ms-asf" },
			{ "asm", "text/x-asm" },
			{ "aso", "application/vnd.accpac.simply.aso" },
			{ "asx", "video/x-ms-asf" },
			{ "atc", "application/vnd.acucorp" },
			{ "atom", "application/atom+xml" },
			{ "atomcat", "application/atomcat+xml" },
			{ "atomsvc", "application/atomsvc+xml" },
			{ "atx", "application/vnd.antix.game-component" },
			{ "au", "audio/basic" },
			{ "avi", "video/x-msvideo" },
			{ "aw", "application/applixware" },
			{ "azf", "application/vnd.airzip.filesecure.azf" },
			{ "azs", "application/vnd.airzip.filesecure.azs" },
			{ "azw", "application/vnd.amazon.ebook" },
			{ "bat", "application/x-msdownload" },
			{ "bcpio", "application/x-bcpio" },
			{ "bdf", "application/x-font-bdf" },
			{ "bdm", "application/vnd.syncml.dm+wbxml" },
			{ "bed", "application/vnd.realvnc.bed" },
			{ "bh2", "application/vnd.fujitsu.oasysprs" },
			{ "bin", "application/octet-stream" },
			{ "bmi", "application/vnd.bmi" },
			{ "bmp", "image/bmp" },
			{ "book", "application/vnd.framemaker" },
			{ "box", "application/vnd.previewsystems.box" },
			{ "boz", "application/x-bzip2" },
			{ "bpk", "application/octet-stream" },
			{ "btif", "image/prs.btif" },
			{ "bz", "application/x-bzip" },
			{ "bz2", "application/x-bzip2" },
			{ "c", "text/x-c" },
			{ "c11amc", "application/vnd.cluetrust.cartomobile-config" },
			{ "c11amz", "application/vnd.cluetrust.cartomobile-config-pkg" },
			{ "c4d", "application/vnd.clonk.c4group" },
			{ "c4f", "application/vnd.clonk.c4group" },
			{ "c4g", "application/vnd.clonk.c4group" },
			{ "c4p", "application/vnd.clonk.c4group" },
			{ "c4u", "application/vnd.clonk.c4group" },
			{ "cab", "application/vnd.ms-cab-compressed" },
			{ "car", "application/vnd.curl.car" },
			{ "cat", "application/vnd.ms-pki.seccat" },
			{ "cc", "text/x-c" },
			{ "cct", "application/x-director" },
			{ "ccxml", "application/ccxml+xml" },
			...
		};
	}
}

Written by Cymen

September 14th, 2011 at 12:28 pm

Idea: enhancing msdeploy with .skip, .skip-production, etc…

leave a comment

At work we use Jenkins (formerly Hudson) for continuous integration and for pushing out releases to our staging and production servers. It works well for this however the configuration for msdeploy is a bit of a cluster due to it being in a batch script — adding or removing directories to skip for deployment is a pain.

I realized today one way to solve this might be to support creating a .skip or .skip-TARGET (so in our case, .skip-production and .skip-staging) files. Than add a batch or simple program to scan the project directory (for script, can use “dir /S /B FILENAME” seems to be equivalent of UNIX “find FILENAME”) and add a skip for the directory. That way anyone can add the skip option and it is clear in source control what is and what is not getting pushed out.

It seems like a simple enough idea to implement…

Written by Cymen

August 16th, 2011 at 10:46 am

Posted in ASP.NET MVC

Yet another round on the ModelState PercentComplete() extension

one comment

So there were a few issues with the previous version — at least when I wanted to extend it for some custom calculations so here is yet another version:

        public static int PercentComplete(this ModelStateDictionary modelStateDictionary, int? ScalePercentWithValueAsZero = null, int? MaxValue = 100)
        {
            int totalItems = 0;
            int validItems = 0;
            int percentComplete = 0;

            if (MaxValue.HasValue && (MaxValue.Value < 0 || MaxValue.Value > 100))
                throw new ArgumentOutOfRangeException("MaxValue must between 0 and 100!");

            if (modelStateDictionary.IsValid)
            {
                percentComplete = MaxValue.Value;
            }
            else
            {
                foreach (var item in modelStateDictionary)
                {
                    totalItems++;
                    if (item.Value.Errors.Count == 0)
                        validItems++;
                }

                if (totalItems > 0)
                    percentComplete = (100 * validItems) / totalItems;

                if (ScalePercentWithValueAsZero.HasValue)
                {
                    if (ScalePercentWithValueAsZero.Value >= percentComplete)
                    {
                        percentComplete = 0;
                    }
                    else
                    {
                        percentComplete = Convert.ToInt32(Math.Ceiling((double)(percentComplete - ScalePercentWithValueAsZero.Value) / (100 - ScalePercentWithValueAsZero.Value) * 100));
                    }
                }

                if (MaxValue.HasValue)
                {
                    percentComplete = percentComplete * MaxValue.Value / 100;
                }
            }

            return percentComplete;
        }

And if a model has a particularly complicated percentage complete calculation in which one needs to manually check some things and add to the total that can be done:

        public int CustomPercentComplete(Func<int?, int?, int> PercentComplete)
        {
            // scale percent complete 50-100% as 0-100%
            int basePercentAsZero = 50;

            // actually, scale 50-100% as 0-91%
            int max = 91;            

            // call default PercentComplete
            int percentComplete = PercentComplete(basePercentAsZero, max);

            // implement here your custom percente complete for the remaining 9%

            return percentComplete;
        }

An example of calling the custom percentage complete calculator on your model:

        myModelInstance.CustomPercentComplete(ModelState.PercentComplete);

And if you need to call either calculator but your controller action doesn’t bind to an instance of the model you need to calculate the percentage on, you can add a method in your controller like this one (hopefully there is a better way — let me know if you know of one):

        // Work around for getting percentage complete when in another action where the model is not the application
        // like so:
        // int percentComplete = MyPercentComplete(application);
        private int MyPercentComplete(MyApplication application)
        {
            return Convert.ToInt32(MyPercentCompleteAction(application).Content);
        }

        // Work around for getting percentage complete when in another action where the model is not the application
        // like so:
        // int percentComplete = Convert.ToInt32(MyPercentComplete(application).Content);
        private ContentResult MyPercentCompleteAction(MyApplication application)
        {
            return Content(application.CustomPercentComplete(ModelState.PercentComplete).ToString());
        }

Written by Cymen

August 16th, 2011 at 10:09 am

Posted in ASP.NET MVC,C#

Another round on the ModelState percentage complete calculator

one comment

Update: The mathematics is wrong — not sure what I was thinking. See the updated version here.

So the prior version has a bug — it works fine if the scaling value is 50 however it fails at other values. Whoops! That has been fixed and now we have a MaxValue scaler too. The MaxValue scaler is useful if you want to calculate the percentage done as maxing out at say 91% because you want to manually calculate the remaining 9%.

    public static class ModelStatePercentCompleteCalculator
    {
        // Very rough but reusable % complete calculator that is an extension so can be
        // called simply as ModelState.PercentComplete() in a controller action. Iterates
        // over the items in ModelState returns percentage complete where a complete field
        // is seen as having no errors. If the ModelState.IsValid returns true, the
        // model is 100% complete.
        //
        // ScalePercentWithValueAsZero: if you calculate the % done on a model and it says say 40%
        // really it is 0% than set ScalePercentWithValueAsZero=40 and it'll treat 40% as 0% and
        // scale it appropriately to 100 or maxValue
        //
        // MaxValue: if you want the maximum value to be less than 100 than set it here so you can
        // accomodate calculating to 100% based on some other criteria too (which you're
        // responsible for)
        public static int PercentComplete(this ModelStateDictionary modelStateDictionary, int? ScalePercentWithValueAsZero = null, int? MaxValue = 100)
        {
            int totalItems = 0;
            int validItems = 0;
            int percentComplete = 0;

            if (MaxValue.HasValue && (MaxValue.Value < 0 || MaxValue.Value > 100))
                throw new ArgumentOutOfRangeException("MaxValue must between 0 and 100!");

            if (modelStateDictionary.IsValid)
            {
                percentComplete = MaxValue.Value;
            }
            else
            {
                foreach (var item in modelStateDictionary)
                {
                    totalItems++;
                    if (item.Value.Errors.Count == 0)
                        validItems++;
                }

                if (totalItems > 0)
                    percentComplete = (MaxValue.Value * validItems) / totalItems;
            }

            if (ScalePercentWithValueAsZero.HasValue && ScalePercentWithValueAsZero.Value > 0 && percentComplete >= ScalePercentWithValueAsZero)
            {
                percentComplete = (percentComplete - ScalePercentWithValueAsZero.Value) / (MaxValue.Value - ScalePercentWithValueAsZero.Value) * 100;
            }
            else
            {
                percentComplete = percentComplete / 100 * MaxValue.Value;
            }

            return percentComplete;
        }

Written by Cymen

August 4th, 2011 at 1:29 pm

Posted in ASP.NET MVC

When not to use AutoMapper

leave a comment

AutoMapper is great but it is both specialized, heavy duty and lacking in documentation. The lack of documentation can bite you: if you need to map two objects in different ways in different places things may not work as you expect. For example, say I have Mapper.CreateMap() with a number of .ForMember(x => x.Something, opt => opt.Ignore()). Now if I create the same mapping elsewhere but with different .ForMember options the prior .ForMember mapping options persist into my current map. To fix this, one can do a Mapper.Reset() which will blow away the global mappings. But creating mappings is expensive. Food for thought.

Written by Cymen

August 3rd, 2011 at 8:48 pm

Posted in ASP.NET MVC

AutoMapper and Mapper.Reset()

leave a comment

Did you know that AutoMapper’s Mapper.CreateMap() persists even if you use different options on the mapping? So if you have this in one place in your code:

Mapper.CreateMap()
    .ForMember(x => x.BrainSize, opt => opt.Ignore());
var person = Mapper.Map(anotherPerson);

And then later this:

Mapper.CreateMap();
anotherPerson.BrainSize = 5000;
var einstein = Mapper.Map(anotherPerson);

That second usage won’t map BrainSize! This is quite confusing… The cache makes sense but it would be more intuitive if the cache was sensitive to .ForMember() usage and other options so that the exact same mapping is cached not any mapping.

The solution is to use this (potentially both before and after your use of AutoMapper):

Mapper.Reset();  // don't want some other area's usage polluting us
// create some mappings here that we don't want to pollute other areas
...
Mapper.Reset();

I haven’t read the source yet but this is a very non-intuitive aspect of AutoMapper. Basically on the level of a deal breaker almost in my opinion.

Written by Cymen

June 17th, 2011 at 2:55 pm

Posted in ASP.NET MVC

ASP.NET MVC, ModelState and Simple Generic Percent Complete Helper Method

leave a comment

Say you have a number of models that are mostly comprised of plain old CLR objects and you need a rough percent complete calculator. Assuming you are using the standard ASP.NET MVC validation rules (via attributes), here is a rough helper method that can calculate the percentage complete for the model based on the number of fields with validation errors divided by the total number of fields.

 

        public static int PercentComplete(this ModelStateDictionary modelStateDictionary)
        {
            int totalItems = 0;
            int validItems = 0;
            int percentComplete = 0;

            if (modelStateDictionary.IsValid)
            {
                percentComplete = 100;
            }
            else
            {
                foreach (var item in modelStateDictionary)
                {
                    totalItems++;
                    if (item.Value.Errors.Count == 0)
                        validItems++;
                }

                if (totalItems > 0)
                    percentComplete = (100 * validItems) / totalItems;
            }

            return percentComplete;
        }

Written by Cymen

June 9th, 2011 at 4:08 pm

Posted in ASP.NET MVC

msdeploy – custom rules

leave a comment

Writing Custom Rules for Web Deployment Tool

This is some very useful information. It’s somewhat frustrating that msdeploy is similar to rsync but seems much less functional from the stand point of what is baked in for rules. And this approach is unofficial and all that so…

Written by Cymen

June 2nd, 2011 at 1:09 pm

Posted in ASP.NET MVC

Tagged with

ASP.NET MVC Route Registration and Areas

leave a comment

I need to be able to register a route via an instance of RouteCollection to an area. I couldn’t put it in the normal area route registration as it had to be registered last. It took a while to figure out that this works:

public static void RegisterAreaRoute(RouteCollection routes) {
    routes.MapRoute(
        "MyRouteName",
        "{*path}",
        new
        {
            // options
        },
        new[] { "_Namespace_.Areas._Area_Name_.Controllers" }
    ).DataTokens.Add("area", _Area_Name_);
}

Written by Cymen

July 9th, 2010 at 5:09 pm

Posted in ASP.NET MVC