I just coded a little application and very often I was having to check to see if the object was null before attempting to access one of its properties.  If it was null, I would use an arbitrary default value.  This ultimately was to prevent the dreaded NullReferenceException.

string output;
if (myObj == null) {
    output = "Unknown";
}
else {
    output = myObj.Name;
}

This bit of code was repeated over and over again making my method very long. Bad. And it looked very messy so I made a little helper method:

public static TReturn GetValueOrDefault<TReturn>(object obj, TReturn defaultValue, Func<TReturn> expression) {
    return obj == null ? defaultValue : expression();
}

This also uses the lovely TReturn so you it can handle any type.

Using this helper method is very simple:

return GetValueOrDefault(myObj, "Unknown", () => myObj.Name);
 

There’s quite a little bit of boiler plate code that is required to be written to get this all working so I’m writing it here so we can all learn from it and use it.

Reference StructureMap  in your MVC3 solution.

In your Global.asax file in the Application_Start method, write a line to call a yet-undefined method called “ContainerStrapper.BootStructureMap();”.  This is where the whole IoC gets injected and is an absolute requirement.

This container strapper contains all your concrete mappings to interfaces across the entire scope of the project.

public static class ContainerStrapper
{
	public static void BootStructureMap()
	{
		IContainer container = new Container(x =>
									 {
										 // Controller and Filter
										 x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
										 x.For<IFilterProvider>().Use<StructureMapFilterProvider>();

										 // Constructor Dependencies
										 x.For<IGenericRepository>().Use<SomeSpecificRepository>();
										 x.For<IFooManager>().Use<FooManager>();
										 x.For<IClock>().Use<SystemClock>();

										 // Property Dependencies
										 x.SetAllProperties(p => p.OfType<IGenericRepository>());
										 x.SetAllProperties(p => p.OfType<IFooManager>());
									 });

		DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
	}
}

Next you will need to create a structuremap controller activator as referenced in the first line of that container mapping we just created.

public class StructureMapControllerActivator : IControllerActivator
    {
        public StructureMapControllerActivator(IContainer container)
        {
            _container = container;
        }

        private IContainer _container;

        public IController Create(RequestContext requestContext, Type controllerType)
        {
            return _container.GetInstance(controllerType) as IController;
        }
    }

…and also a StructureMapFilterProvider:

public class StructureMapFilterProvider : FilterAttributeFilterProvider
    {
        public StructureMapFilterProvider(IContainer container)
        {
            _container = container;
        }

        private IContainer _container;

        public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var filters =  base.GetFilters(controllerContext, actionDescriptor);

            foreach (var filter in filters) {
                _container.BuildUp(filter.Instance);
            }

            return filters;
        }
    }

and lastly we make a StructureMapDependencyResolver:

public class StructureMapDependencyResolver : IDependencyResolver
    {
        public StructureMapDependencyResolver(IContainer container)
        {
            _container = container;
        }

        private IContainer _container;

        public object GetService(Type serviceType)
        {
            object instance = _container.TryGetInstance(serviceType);

            if (instance == null && !serviceType.IsAbstract)
            {
                _container.Configure(c => c.AddType(serviceType, serviceType));
                instance = _container.TryGetInstance(serviceType);
            }

            return instance;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _container.GetAllInstances(serviceType).Cast<object>();
        }
    }

You’re all done and ready to go :)

To inject dependencies in to your controllers, put the interfaces as arguments in the controller constructor and set them as private variables if you need them in your actions

 

I’ve just recently attempted to upload an entire directory up to sharepoint.  I did initially try doing this using WebDAV but the speed was unimaginable slow (30 – 40 secs for a 1KB gif image).  I didn’t want to upload the images through the browser as you can only do 100 at a time (I had ~3,500 images plus ~4,000 documents).

So I looked at copying over the files using the sharepoint object model!  It turns out that this is speedy fast and works a treat!  There’s an MSDN article I used as my basis but I’ve made a few changes so it uploads a whole directory instead of just a single file.  Here’s how you do it:

public void UploadImages()
{
    this.CopyDirectory(@"\\some\server\images", "PublishingImages");
    this.CopyDirectory(@"C:\ImagesFolder\ImagesToUpload", "PublishingImages");
}

private void CopyDirectory(string frm, string to)
{
    var serveraddress = "http://server:80/";
    using (var web = new SPSite(serveraddress + to).OpenWeb())
    {
        if (!web.Exists)
        {
            throw new Exception("Web doesn't exist here");
        }

        var di = new DirectoryInfo(frm);
        var fileInfos = di.GetFiles("*.*", SearchOption.TopDirectoryOnly);
        foreach (var fileInfo in fileInfos)
        {
            this.UploadFile(fileInfo.FullName, web);
        }
    }
}

private void UploadFile(string srcUrl, SPWeb web)
{
    if (!File.Exists(srcUrl))
    {
        throw new ArgumentException(String.Format("{0} does not exist",
            srcUrl), "srcUrl");
    }

    byte[] contents;

    using (FileStream fStream = File.OpenRead(srcUrl))
    {
        contents = new byte[fStream.Length];
        fStream.Read(contents, 0, (int) fStream.Length);
        fStream.Close();
    }

    string filename = srcUrl.Substring(srcUrl.LastIndexOf("\\") + 1);

    if (!IsValidFileName(filename))
    {
        throw new Exception(filename + " is not a valid filename.  Please review and try again.")
    }

    var file = web.Files.Add(filename, contents)
    file.Update();
}

private static bool IsValidFileName(string filename)
{
    if (filename.Contains("..") || filename.EndsWith(".") || filename.StartsWith("."))
    {
        return false;
    }

    if (filename.IndexOfAny(new[] { '\"', '#', '%', '&', '*', ':', '<', '>', '?', '\\', '/', '{', '|', '}', '~' }) > -1)
    {
        return false;
    }

    if (filename.Length > 128)
    {
        return false;
    }

    return true;
}
 

In a recent project, I’ve begun to heavily use regular expressions to capture the data from a looong string.  This post will demonstrate how I used ExplicitCapture to make it really easy to use the captured data later on using the Match object.

The data is in the following format:

[Data I do not care about...]<textarea1><![CDATA[blahhhhhhh]]>
</textarea1> <textarea2 xmlns=""><![CDATA[bada bing bada boom]]>
</textarea2>[More data I do not care about]

I need to capture all the data inside those CDATA areas, and also the number of the textarea.  Even though the content of the CDATA may be HTML and therefore not a regular language, I am still using a regular expression here as the content outside of the textareas is regular.  If you need to extract data from HTML, I’d recommend using HTML Agility Pack.

Regex pattern = new Regex("<textarea(?<textareaid>\\d+)( xmlns=\"\"|)><!\\[CDATA\\[(?<content>.*?)\\]\\]></textarea\\d+>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.ExplicitCapture);

Here I’m storing my regular expression in to a variable called pattern.  The expression is a little more complex than expected due to me having to escape my backslashes when I do actually want them represented in the regex pattern.  The interesting parts are the RegexOptions in the second parameter of the Regex constructor.

Of course I’m using ignore case as there may be instances where the case is different.

I’m using single line as I don’t want to take in to account line breaks, nor am I using ^ or $ to indicate the start or end of lines respectively.  This option treats the string as one long unbroken line with line break characters and so enables a kind of dotall functionality.

The final option I’m using is explicit capture. This allows me to specify which capture groups I’m actually interested in and giving them a name.  In the above example, you can see I capture the textarea id number by writing (?<textareaid>\\d+).  This matches one or more digits and calls it “textareaid”. Awesome.

Now to use that later on I use the following code:

MatchCollection matches = pattern.Matches(content);
string convertedContent = String.Empty;
foreach (Match match in matches)
{
    convertedContent += string.Format("<div id=\"textarea{0}\">{1}</div>", match.Groups["textareaid"].Value, match.Groups["content"].Value);
}

The string convertedContent will now contain as many divs as there are textareas and will contain the content held within the CDATA.  Using match.Groups["whatever"] is a really easy way to get at the match values.

 

At work a lot of our forms use Windows Authentication instead of Forms Authentication as it provides a convenience for the user to not have to always log in to every online form.  Plus these forms are only accessible to computers in the WAN or VPN.

Some forms however should only be seen by specific personnel and so we have to get permissions set up on our actions so that regular users do not see any approval forms or reports etc.  Rather than coding up the checking of the permissions database for User.Identity.Name for every action, we’ll go ahead with the DRY (Don’t Repeat Yourself) principle and make an ActionFilter that we can decorate our actions with.

Continue reading »

© 2011 athe.la blog Suffusion theme by Sayontan Sinha