Category Archives: Coding



I thought I had CORS all figured out. Of course, like all things programming, the more you think you know the sooner something is going to blow your world wide open. As a guy who codes for the web a lot, these errors are get under my skin. They’re annoying when you know you put a line of code in your server to allow all origins. They’re even more so annoying when the browser (or framework you’re using) tells you that you CAN’T use a wildcard and just allow ALL origins.

Let me leave this link right here:

If you’re having CORS trouble on your server, it would behoove you to click that link there and finally be done with it. If you’re using ASP.NET chances are you’re using a Windows server and you’ll be able to use either the ASP.NET or IIS6/7 solutions.

My current favorite method for handling CORS with ASP.NET applications ( especially if you’re using SIGNALR and UseCors(CorsOptions.AllowAll) isn’t what you need, as browsers still puke with this in place )

             <add name="Access-Control-Allow-Origin" value="http://localhost:58547" />
             <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE, TOKEN" />
             <add name="Access-Control-Allow-Credentials" value="true"/>

This goes in your web.config with <configuration> as its parent element. You can use a wild card in place of the


You CANNOT add another origin to the Access-Control-Allow-Origin. Why? No idea. But if you try, you’ll get an error like this

The ‘Access-Control-Allow-Origin’ header contains multiple values ‘http://localhost:58547,;, but only one is allowed. Origin ‘; is therefore not allowed access.



AngularJS: Creating a factory and returning data in a SPA.

Providers (I’ve seen many people just refer to Providers as Services, Angular docs use Providers, so that’s what I’m using >.< ) in Angular provide a way to fetch and persist data inside your web application. There are a couple different variations of providers which from what I can tell, and the large number of equally confused individual on the web, they’re all pretty much the same. There are providers, factories, values, and services, the one that you use is pretty much up to you depending on your need. The reply by Jonathon Palumbo on StackOverflow does a pretty good representation of what all of them look like as well clarifications like that fact that factories and services actually use providers ‘under the hood’. Again, a little confusing. Whatever.

I’m going to go over creating a factory which will fetch some data for me and then return it so that I can use that data in a controller to display on my web page.

So say I want to retrieve a list of users and display them to my page. This is where the factory comes in, it will retrieve the data for us. Then, the controller will bind the data. Finally, a web page will display the data.

Creating a Factory

Creation of a basic factory is easy. First, create a module to contain the factory.


The module is named app and the ngRoute module is passed in (if you want more information on ngRoute, checkout my last blog post). Now that we have a module, we can create the factory with .factory(‘factoryName’, function(){});


The first parameter is the name of the factory, the second is a function which will return data. The name of this factory is userRepository and what I want to do with it is return a list of users. To do so, a function needs to be added to the return in order to retrieve the list of users.


The return statement now contains a function called getAllUsers which returns an array of static users. The factory is now complete and this data can be bound in a controller to a view. This can be done by creating a controller and passing in or injecting the userRepository factory which will then make use of the getAllusers function.

Passing the Factory to a Controller


The first param is the controllers name, userController and the second is function which takes in the $scope service and the userRepository factory so that we can use it. Then, inside the function, $scope.users gets defined as the return data from UserRepository.getAllUsers(); – and that’s all we need for the controller.

Now, the reason I put ‘in a SPA’ is just because of how i’m going to associate the controller to my web page, which happens to just be a partial page in a Single Page Application (SPA). Associating a controller to a page in a SPA is super easy because in the $routeProvider.when method, you can use the controller: param to pass in the controller name

Adding the controller to the (partial)web page


In red is the .when for the page that I’ll be using the controller with and in green is the actual use of the controller: parameter.

Displaying the factory’s data

The only thing left to do is to display the data in users.html, a simple  ng-repeat will display all entries in the array provided by the factory in getAllUsers().


The result

When the web app loads up and the users page is visited, it’ll look like this:


AngularJS: Single Page Applications with $route

Single Page Applications can easily be created and maintained when using AngularJS. Single page applications are achieved by injecting HTML into the main page (index.html) using the ng-view directive and some routing. The routes will point to partial HTML pages that will be injected into index.html.

Getting Started

Using routing with Angular requires having the angular-route.js or angular-route.min.js files and a reference to one of them inside index.html. They can easily be acquired via NuGet, the AngularJS package includes all the scripts you could ever possibly need for Angular. I’ve also included a reference to an app.js file which will contain the module and route configurations.


The Body

Setting up the body of index.html is extremely easy because it just acts as a skeleton to the partial pages that will be injected in to it.


The body element contains the ng-app directive which has a value that indicates the module name I will use in app.js will be “app”. Within the nav element is a list of links to the partial pages. The href properties’ values use the #/ syntax which refers to the /partials/ directory and is how angular identifies the routes. The #/ syntax is then followed by the name of the page (don’t put the .html extension). Inside the div container is the ng-view directive which tells the page that this is where you want the partials injected into.


The following is an example of a partial page that can be injected into index.html. The solution explorer on the right side contains all the partials listed from the nav element in index.html.


Creating the Routes

The syntax for creating routes in Angular is very simple. A module will need to be created and ‘ngRoute’ will be need be passed into the second parameter – which is an array that takes controllers, services, and factories that the module depends on. After creating the module, the module’s .config property needs to be configured with the routes. The first parameter .config takes $routeProvider and the second parameter takes a function which will also accept $routeProvider as a parameter. Inside the function contain a list of routes. The routes follow the syntax of

$routeProvider.when(‘/pageName(like the links on index.html w/o the #)’,{ templateUrl: ‘partals/pageName.html’});

There is also an option$routeProvider property .otherwhise which allows you to redirect the user to a certain page in the event of something like a link not yet implemented. The syntax is:

$routeProvider.otherwise({ redirectsTo: ‘/pageName’ });

Here is app.js in it’s entirety.


The final product of all of this will create singe web page which will be able to quickly inject in different partial HTML pages.

The Header and Nav bar remain static on the page, when a link is selected the $routeProvider identifies the correct partial page and the HTML gets injected into the div element that contained the ng-view directive.



A bit of AngularJS: Directives, Expressions, Modules, and Controllers

Angular is a JavaScript Framework (pretty popular too) for developing web-based applications. The Angular framework is useful in creating vibrant dynamic documents instead of just static pages.

Installing/Preparing Angular

In order to begin using Angular in your HTML, you must reference angular.js or angular.min.js. In order to reference the script, you must have the script in your site’s directory. If using an IDE such as Visual Studio, you can just download the AngularJS Nuget Package which will include a butt ton of Angular related scripts. If you don’t have the ability to download via NuGet, you can just download one of the angular scripts from Angular’s web page or wherever it may be acquired from and place it in your working dir. Once the script is available, reference it with the <script src=”path\to\angular.min.js”> element.

Directives & Expressions

Angular makes use of keywords called Directives that act as markers to tell the HTML that some JavaScript is about to be ran or referenced. The first directive that will be used on any web application is called ng-app. The reason that it’ll be the first is that this tells the page when to start making use of the Angular framework. The ng-app directive can be placed virtually anywhere in the HTML as long as it’s before the attempt to do anything else with Angular. Here’s an example of using ng-app, when the expression ( Identified by the double curly braces, expressions are how values are displayed onto the page) is before the directive it’s not evaluated. When the expression is after the ng-app directive then it’s evaluated correctly.



If I wanted to, I could have just put the ng-app directive into the beginning <body> or even the <html> elements.


Modules are where the application components live. They’re basically containers for different parts of the app such as controllers and filters.

In the HTML page, you have the ability to declare the module you want to use in the ng-app directive; However, without a module defined in a .js file, nothing will be accomplished as it won’t actually reference anything. Here’s what defining a module in a .js file would look like.


The name of the module is the first parameter provided, the second parameter, the array, is for more advanced module configurations. Now that the module has been created, the ng-app directive in the HTML page can have the module set as it’s value.


Now, if the page is loaded, the expression won’t be evaluated. This is because the .js file must be referenced in the HTML before the module is able to be found correctly. It uses the same script element as the reference to the angular.min.js file. Here’s a screenie of the script reference, the ng-app directive with the module included and the expression.


You’re probably going… “What the hell is the use of the module then?”. The module doesn’t really do anything at the moment. It’s just an empty container. In order to begin making use of the module, we need to add some content to it, such as a Controller.


Controllers are a way to handle data with values and methods which will define the apps behavior. A controller can be defined in a .js file along with a module. Here’s a controller added to the previously created module.


There’s a few alterations made to the JS file. First, it’s considered a good practice to encompass the entirety of a controller within a function. Line 1 and 14 display the containment function. Line 3 is the module created from before.  Lines 5-8 create a _person object which will contain my first and last name, this object will be used in the controller. Lines 10-12 actually create the controller by using the app variable that was defined as the module, this is because the controller is a method of modules in Angular. The first parameter of the controller is it’s name, the second is a function which defines what the controller actually does. All this controller currently does is instantiates another person object equal to _person, doing so allows the object to be used in the HTML.

Now that the controller has been established, it can be used by the HTML via expressions. But first, a new directive must be used, ng-controller. ng-controller tells the HTML what the name of the controller is to be used on the page.


Line 11 shows the use of the ng-controller directive, the value provided let’s the directive know that a controller named indexController is what needs to be referenced and will be utilized in the HTML as simply controller. Line 12 and 13 show expressions utilizing the indexController… as… controller (see how that works? :P). The expressions reference the person object in the controller and each property that the object holds and displays them on-screen. Here’s the final results.


I intend to continue a line of Angular posts for the stuff that I’ve been learning and they should all build upon the previous post. Stick around if you’re interested and drop any comments if you’ve got any questions.

C#: NLogging to the local File System and to LogEntries

>inb4 title spellcheck
Yes, the N is supposed to prefix “logging” in the title.
Because Nlog.
Nlog? you ask.
Yes. Nlog.

Nlog is an open source logging platform for .NET, Silverlight and Windows phones. Installation via NuGet, insanely easy to implement and packed with all the features you’d want in a logger, it’s an ideal logging solution.

In order to install Nlog, just open the NuGet Package Manager and search for Nlog. There’s two packages that are needed – NLog and NLog configuration. NLog is the actual library and NLog configuration is the NLog’s config file for determining the log levels and locations.


Once both of the packages are installed, the configuration file requires a tiny bit of tweaking. When I say tiny bit of tweaking, I mean, MICROSCOPIC tweaking. Two lines and we’re done. The examples given in the NLog.config are perfect for understanding how to get started.


Once the config file looks pretty and setup as needed, it’s time to invoke NLog in the application. This is as simple as creating a using statement for NLog and then creating a logger with a given name. You can create a log with a name by calling LogManager.GetLogger(“name”);. NLog’s documentation indicates that in most cases you’ll have one logger per class – which if you create a logger inside of a class you can just use LogManager.GetCurrentClassLogger().

In my testing I decided to replace the exception logging I had put in place in a previous post where I had created my own logging class. NLog provides multiple methods for different levels of logging. The config file lets you choose the minimum level in which gets written to the log.

  • Trace
  • Debug
  • Info
  • Warn
  • Error
  • Fatal

Since I’m replacing an exception logger and the exception is a wee one, I’ll use the Error() method.  (Don’t make fun of my code >.< it’s my first home-baked app)


Then when I run the application and null out one of the fields


Now, this is pretty cool and what not, but writing logs to LogEntries would be even cooler, right? Well guess what, it’s freakin EASY to implement as well. LogEntries provides a copy/paste template that goes into your applications app.config for web.config – the only value you have to change is the token to your logger.

Visit to copy the entries.

You can create a free account on LogEntries and try out their service for 30 days. When you create an account you’re prompted to create a new host which will contain a set of logs. Once the host is created you can create your first log. Once the log is created, you’re given a token which will be placed in your app.config. This all happens right after each other when you create the account – few seconds and done.

Here’s the app.config once it’s all said and done


I Could just run the app now and it would write the logs to LogEntries, but I want to implement the log on an actual class and use the GetCurrentClassLogger() method.

private static Logger logger = LogManager.GetCurrentClassLogger();

then called the logger’s info method to tell me when the my Person’s data changed


And when running my application and hitting submit


C#: Try to catch and log that exception!

-Uses the app in the previous post, “XAML/C#: Creating a button and an event”-

I noticed that on my recent WPF application that when I clicked my save button without entering any information in my little form that it would crash with a NullRef Exception on the combo box.


Figured it would be a good time to revisit the Try Catch statement and handle myself an exception.

I removed the MessageBox portion of the SaveButton event because I wasn’t too fond of it and encased the StringBuilder in a Try block. Since I know the exception that I’m getting is a NullRef, a NullReferenceException is placed in the Catch statement.


My application will no longer fail should an item not be chosen from the ComboBox, but I have two problems now.
Num1: Since I chopped the MessageBox my save button doesn’t really do anything again except build a string anyways.
Num2: If the save button did do something, and instead of the application crashing we keep it up to make it more user friendly, what information do we have now on why it wasn’t performing its task?

Solutions – Create a log that’ll save the information when the controls are filled out correctly and keep a separate log that’ll report the errors when they occur. This way our button will have a purpose and we’ll have information as to why the button may have not worked for whatever reason.


Then to just put the Logger in action.


And then to test out the application…


I’d say it was a success 😛

XAML/C#: Creating a button and an event

Creating a button for a WPF application and associating an event to it is exquisitely simple. A button can be created in the XAML with the <button> element which shares a lot of the common properties for positioning and alignment. The content property sets the text that displays on the button and the name property actually associates a name to the button.

Here’s a sample application that has a <button> element in it


This application is a simple grid layout with a couple controls that will collect information from the user. At the bottom of the application is a save button. The XAML behind the button currently looks like this:


If save button is pressed the way that it is currently set up, it won’t do anything. It’s literally just a button on the page that does a whole lot of nothing! A lot of good that does us right? This is where the wonderful world of events comes into play. The dictionary definition for an event is “enable a class or object to notify other classes or objects when something of interest occurs”… or “When something happens, do the thing(not all the things this time)”.

We can cure our button of it’s lack of events but adding the click property to it. When you add the Click=”” property, intellisense will pop up and give you the option of creating a new event handler, which so far is my preferred method.

Just to clear anything up in the picture:
The /> is the closing of the Button element and wasn’t
supposed to be that close to the property in the picture >.<

If you associated a name property with the button, then the new event handler will be ButtonName_Click. A new method will also be generated on the code behind page which will allow you to dictate what happens when the button is clicked.


Code Behind Page (MainWindow.xaml.cs)


The next step was to insert something relatively simple into the SaveButton_Click method to show that something happens when that button is clicked. Using a StringBuilder and then presenting the result, via a MessagBox, is a pretty simple solution.


This string builder allows us to append pieces of strings into one grand daddy and include the correct controls with simple bool queries. Once the string has finished being assembled, a MessageBox is able to display the result via the MessageBox.Show() method with StringBuilder.ToString() as a passed parameter.

Now when the save button is hit, the following will appear


It’s not pretty, but it does show that the event does indeed work.