FakeModel V0.0.7

Introducing FakeModel v0.0.7

It’s been a while since I’ve been able to commit some time to improving FakeModel, but I’m now proud to announce the release of FakeModel v0.0.7, bringing some essential fixes to the nature of FakeModel.

What’s New

FakeModel v0.0.7 brings the following updates;

  • Limited Characters in String Generation

Continue Reading →

26. July 2014 by Adam Riddick
Categories: FakeModel | Leave a comment

Insight: AuthorizeAttribute Lifecycle

I’ve learned a valuable lesson about the AuthorizeAttribute Lifecycle recently, one which I feel should be shared with the world. Hopefully, someone will gain something from this, hopefully I can fix the issue I faced for others.

The Story

The situation is a simple one, I required that access to certain controllers and actions was subjected to the approval of an authorisation process. In MVC, we are provided with the AuthorizeAttribute to help us along our way. Not wanting to re-invent the wheel in any way, I implemented the AuthorizeAttribute filter, as I have many times before without ever fully understanding the AuthorizeAttribute Lifecycle, and went on my way, assuming the filter was doing it’s job because the tests passed and I could authorise against the attribute.

Continue Reading →

22. July 2014 by Adam Riddick
Categories: ASP.Net, C# | Leave a comment

Software Overengineering

Software Overengineering

How do you know when you are over thinking the architecture of a solution? Should we forget about the future and build for now, or should we focus our efforts on building for the future? Are we all Software Overengineering?

First, I want to define Software Overengineering. It may be natural towards thinking this means putting too much effort into a solution that requires less. Whilst it follows the same mold, it is not entirely the same.

By Software Overengineering, I refer to putting too many constraints on the architecture or design of a solution, constraints that we feel are required though never actually will be, we can build for the future without building the future. It’s an easy trap to fall in to, it’s among many people’s traits to over think a situation, and many developers over complicate solutions, a lot simply because they feel it makes them appear smarter and better at what they do.

Continue Reading →

15. July 2014 by Adam Riddick
Categories: Achitecture | Leave a comment

Backup All Databases SQL

Data is precious and for many companies data means money, directly or indirectly. More and more countries are taking up laws on the ownership storage and historical persistence of data, meaning companies need to pay attention to backups for multiple reasons. But whatever the reason for a backup, you should be able to backup all databases without it giving you a headache.

Of course we could use Sql Server Management Studio (SSMS) to create a maintenance plan, and that’s fine and easy when we have a handful of databases, or less, but what if there are dozens or hundreds of databases that require attention? Do we really want to maintain that may maintenance plans?

We can backup all databases in an Sql server using a T-Sql script, which will cycle our databases and create a dated backup at the  location of our choice. This script can be scheduled through a SQL Job to automatically backup all databases to a set schedule.

Backup All Databases Script


DECLARE @name VARCHAR(50) -- database name
 DECLARE @path VARCHAR(256) -- path for backup files
 DECLARE @fileName VARCHAR(256) -- filename for backup
 DECLARE @fileDate VARCHAR(20) -- used in file name
 SET @path = 'C:\backups\' --path to the backup folder

 SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
 DECLARE db_cursor CURSOR FOR
 SELECT name
 FROM master.dbo.sysdatabases
 WHERE name NOT IN ('tempdb')
 OPEN db_cursor
 FETCH NEXT FROM db_cursor INTO @name
 WHILE @@FETCH_STATUS = 0
 BEGIN
 SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
 BACKUP DATABASE @name TO DISK = @fileName
 FETCH NEXT FROM db_cursor INTO @name
 END
 CLOSE db_cursor
 DEALLOCATE db_cursor

The power of T-SQL allows us to be flexible enough to include of exclude certain databases, in case they are archived already, their backups are handled by an existing maintenance plan or they are temporary databases. This can be achieved through a standard WHERE clause. The full power of T-SQL is at our disposal for handling backups, which allows us to be very dynamic in what we create backups of.

05. July 2014 by Adam Riddick
Categories: SQL | Leave a comment

MVC External Controllers

In my current role I am architecting and implementing an application platform that is flexible and dynamic enough to allow a full set of application features be loaded into the application without any outward dependencies from the central application block. This requires that each Service being loaded into the application is dependent only on the central applications functionality, using a separated data access layer to handle any data persistence. It also requires that a single MVC presentation layer handles the loading and routing of External Controllers. These External Controllers are to be located within the services, separate from the base presentation layer.

Effectively, this application is operating with an N-Tier architecture, in which N is only definable within a given deployment.

Each of the services that will be created for this application needs to be in a position to declare and handle it’s own Controllers, Views and Routes, three essential components of the MVC engine.

Handling External Controllers from a single presentation application has perhaps been the most complex part of the project to date.

The most obvious point approaching the problem of External Controllers was that the Routing table would need to be aware of the routes in order to pass a request to the controller in question. This was achieved by mapping all of the routes into the routing table on application startup. Using an interface implemented within each service, derivatives of the interface can be loaded on application start and there register method called to map the routes.

But it doesn’t stop there. Each of the routes mapped must set the Namespace parameter to declare the full namespace in which the controller can be found, otherwise the routing engine will stop after checking the default namespaces.

For example;

context.MapRoute<"MyRoute","My/External/Route",
new { controller = "ExternalExample", action = "Index"},
new string[] { "MvcApplication.Controllers" });

The next step is to make sure every resource that will be rendered is set a an Embedded Resource and each of the External Controllers must return a view by the entire namespace name, I.E “MvcApplication1.Views.Home.Index”.

Next, there is a need to implement a custom VirtualPathProvider to tell the MVC engine where to find our resources, which is registered on application start. There are a lot of examples of this on the internet (Try Ian Mariano’s), it’s normally just a case of tweaking the path locations depending on the setup of your external controllers assemblies.

In order to handle media files (.css, .js, .png, .jpg …. etc), they must also be set as Embedded Resource’s, and can be called through the following method, within the Presentation layers controller;


public FileStreamResult Content(string id)
{
string resourceName = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList().FirstOrDefault(f => f.EndsWith(id));
return new FileStreamResult(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName), GetMIMEType(id));
}

Finally, we must ensure that the separate services are locatable by the app domain. In order to do so, we have to use a PreApplicationStartupMethod (See This) in which we load a shadow copy of the assemblies into the app domain.

In order to do so, we must set the Probing PrivatePath property to the location we will shadow copy the assemblies to. This is done in the web.config <runtime><assemblyBinding> section;


<Probing PrivatePath="/ShadowCopies" />

Once we load the shadow copied folder into the private path, which is done using a standard file.copy from a dynamic directory search, the shadow copied assembly must be registered with the Build Manager, so MVC knows to reference this DLL as part of the application domain. This is done using;


BuildManager.AddReferencedAssembly(myShadowCopiedAssembly);

The build manager requires that this is done in a PreApplicationStartupMethod. So we use our PreApplicationStartupMethod to make shadow copies of the DLL’s we are working with and registered the appropriate ones with the Build Manager.

And from there, the External Controllers can be accessed through the base application, without the application needing a reference to the external controllers assembly. This allows us to swap and change Services in a plugin fashion and the only requirement is that we restart the applications domain, which is a very straightforward operation, just have a controller action call the following;


AppDomain.Unload()

The next steps will include allowing a Plugin architecture to be handled for the Modular services, so they themselves and have their functionality expanded without the need for updates. Unfortunately, this would require that the plugin dll’s are also loaded into the BuildManager pre-startup.

I plan on experimenting with holding an additional app-domain to hold plugins in a separate environment to the main application, one that would be started when the plugins are requested by the service itself, holding only the required lifecycle and not being present for the entire application lifecycle when they may not be used.

If I have much success, I may plan to implement this into the services, however it depends how nicely MVC plays with controllers in separate app domains, considering the setup required for External Controllers.

26. June 2014 by Adam Riddick
Categories: Achitecture, C# | Leave a comment

C# ?? Operator

Those of you who have used C# for a while will probably be familiar with the ?? operator, known as the null coalescing operator. The ?? Operator is used to check if a value is null, and will return the left hand operand if it isn’t, and the right hand if it is.

For example;


string myString = null;

string result = myString ?? "Empty String"; //Result is set to "Empty String"

myString = "A String";

result = myString ?? "Empty String"; //Result is set to "A String"

The reason for this post wasn’t to introduce anyone to the ?? Operator, which most of you will have seen at least in passing before. But it was because I discovered something new about the ?? Operator today, it can be chained.

The ?? Operator can be used multiple times in the same operation to determine if multiple operands are null.

An example usage;


string valueOne = null;

string valueTwo = null;

string valueThree = "Hello";

string result = valueOne ?? valueTwo ?? valueThree ?? "No Value"; //Result is set to "Hello"

valueOne = "Changed";

result = valueOne ?? valueTwo ?? valueThree ?? "No Value"; //Result is set to "Changed"

Sometimes it’s the simplest things that make our lives more concise!

Credit where credit is due, Rick Stahl.

16. June 2014 by Adam Riddick
Categories: Uncategorized | Leave a comment

c# Type Alias

C# comes with the using directive, which allows us to import namespaces in order to allow access to the members of namespace, but it can also be used to create a namespace or type alias.

When used as an Type Alias, the using statement allows us to simplify access to long-named namespaces, or to simplify access to types by creating an Alias of that type.

For example, we can setup a type alias using the following code;


using NestedDict = Dictionary<string, Dictionary<string, Dictionary<string, IEnumerable<int>>>>;

Setting the above code with the rest of the files Using statements allows us to use NestedDict instead of our large definition of a nested dictionary, so we can simply do the following;


NestedDict myDict = new NestedDict();

Calls to myDict are not calls to a NestedDict type, but to the complicated nested structure we defined with the Type Alias.

Using is not only able to make Type Aliases, but also to make Namespace Aliases.

This can be done in the same way, for example;

using space = myNamespace.anotherNamespaceWithAReallyLongName;

We can then access the members of the namespace by using the space alias, saving us repeating potentially long namespace names, especially if they become complicated and nested.

 

12. June 2014 by Adam Riddick
Categories: Bits & Bobs, C#, Tips | Leave a comment

c# Convert String To Enum

There are multiple techniques that can be employed for conversion of a String to Enum value, But which one should we be using? In the past, I’ve always done it the simple way and created a method “ToEnum” and used Enum.TryParse to gather the value. However, as I am currently leading a project in which performance at every stage is crucial, I thought I would explore this a little bit deeper.

Disclaimer: I am not prematurely optimising. It just happens I looked at my enum extensions and was curios if there was a faster way, knowing the method I was using in turn used reflection for resolution.

Enums are a great solution for holding information in a lightweight container. An enumeration can be used to hold the possible options to be passed into a method, such as a factory, or to be used to hold the possible states of a piece of information, such as the results of an Authentication attempt;


enum AuthResult

{

Accepted,

Rejected

}

Continue Reading →

08. June 2014 by Adam Riddick
Categories: C#, Tips | Leave a comment

C# Initialize methods before app start

There often comes a time in development when some form of initialization is needed in an application, so we begin to implement Initialize methods. These are very handy, allowing developers to complete any pre-cursor work the application requires before it is run, setting up caches or loading external assemblies into the app domain.

But where do we set these Initialize methods?

No doubt you will have seen Initialize methods called in the Application_Startup path of a Global.asax file. If you haven’t, it’s almost a guarantee that you soon will.

I’m not criticising the approach. It’s what it is there for, it’s called very early in the pipeline and does allow for initialize methods to be called to setup the environment for the application to run. But it isn’t always available for use, though we have an alternative route.

Continue Reading →

01. June 2014 by Adam Riddick
Categories: ASP.Net, Bits & Bobs, C# | Leave a comment

The Parallel.Invoke Method

In the .Net Framework we can use Parallel.Invoke to call multiple methods in parallel, meaning they will begin to run at the same time across multiple threads. This can be useful when we have multiple long-running methods that don’t need to be called in a linear process.

For example, if we are running one method which takes 3 seconds, and then a second that takes 4 seconds in tandem, we are going to be waiting 7 seconds for the final output, but if we run these parallel to each other, the output will be faster.

The Options

Parallel.Invoke isn’t the only way to achieve parallelism of methods using the .Net framework. Here, we will explore the effects of running the methods linear, using Thread to manage the threads ourselves, and using Parallel.Invoke, the code will look something like the following;

For the linear process;


FirstMethod();

SecondMethod();

Continue Reading →

20. May 2014 by Adam Riddick
Categories: ASP.Net, C#, Tips | Leave a comment

← Older posts