Category Archives: C#



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.



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.

CUIT: Getting Started with Data Driven Tests

Data Driven CUITs allow you to record a set number of steps and then use a data source as a list of parameters to change the values that are either chosen, entered, or have been asserted in a test. If numerous sets of parameters are supplied, the test will run itself multiple overs using the list of supplied parameters.

Since this is my first attempt at creating a Data Driven variation of CUIT, I created a simple CUIT which contains two methods. I used Windows Calculator as my test dummy in this. The first method adds 1 + 2 by clicking ‘1’  -> ‘+’ -> ‘2’ -> ‘=’. The second method asserts that 1 + 2 equates to 3.

The process can be summed up in about 3 (relatively) simple steps

  1. Create a data set
  2. Add the data set to a test method
  3. Map the test values from the Data Set

A using statement must be added when dealing with Data Driven tests

using Microsoft.VisualStudio.TestTools.UITesting.WinControls;

Creating the Data Set

In order to create the file to be  used, simply add a new text file to the solution by right clicking on it. The file will need a .csv extension (Yes, add a text file to the solution and during creation append .csv instead of .txt). Once the file has been created, a table of values can be created. For each parameter that you want to supply a new value for, add a new column for it. For each new repetition of the test, a new row of values to fill the columns is needed.

On my test there are three parameters that I want to give new values to. These values are: The first number pressed, the second number pressed, and the value asserted. This means that my data file will need to include columns for those parameters. If I want the test to run 3 times, then the file will need 3 rows of data.

This is what the contents of the file would look like:
Num1, Num2, Sum
2, 3, 5
3, 4, 7
4, 5, 9

Add the Data Set to a TestMethod

So far there’s only a file with the values we wish to use for the parameters. Technically, the file could be used for multiple Test Methods. In order to tell the test which method we wish to associate it with, a Data attribute must be appended to the Test method attribute.

[DataSource(“Microsoft.VisualStudio.TestTools.DataSource.CSV”, @”c:\users\phillipwolf\documents\visual studio 2013\Projects\CodedUITestProject1\CodedUITestProject1\data.csv”, “data#csv”, DataAccessMethod.Sequential), DeploymentItem(“data.csv”), TestMethod]

In the DataSource attribute, the first string determines the type of data source, the second is the file path (which requires an @ symbol due to the spaces), and I’m not entirely sure what the last one is yet aside from knowing to match it to the file’s name. I found the DataSourceAttribute class help page and those constructors don’t seem to match these.

If the test was ran at this moment, with only the Data Source have being added – The test would run through three times, but with the default values each time. This is because the test realizes that there are three rows of values in my data source but it doesn’t know what parameters to match to which column.

Map the Values from the Data Set

Before the methods run in the Test Method, the values on the UIMap that the methods in the test use need to be mapped to the correct columns in the data set.

Currently, my UIMap looks like this


So my three values to map where the first number button click, the second number button click, and the value asserted.

The First Value

According my UIMap, UIItem1Button is the object that selects the ‘1’ button (Under AddNumbers there’s the actions taken during recording. If you select one of those options, the code equivalent will highlight on the right side). Objects that interact with the GUI use the properties of the item on the screen in order to find them. This means that we need to change the search properties of UIItem1Button.

this.UIMap.UICalculatorWindow.UIItemWindow.UIItem1Button.SearchProperties[WinButton.PropertyNames.Name] = TestContext.DataRow[“Num1”].ToString();

The first part is pretty easy to figure out. UIMap.UICalculatorWindow.UIItemWindow.UIItem1Button is directly from the UIMap image above. SearchProperties[] is then a property of the button which the test uses to find the control on the application. The controls property is then placed within the brackets, in this case the name will be replaced. After the = contains the column reference via TestContext.DataRow[“NameOfTheColumn”].ToString(); This makes the Search Properties equal to the respective column .

The Second Value

The second number button would have it’s parameters set exactly the same way as the first number button

this.UIMap.UICalculatorWindow.UIItemWindow2.UIItem2Button.SearchProperties[WinButton.PropertyNames.Name] = TestContext.DataRow[“Num2”].ToString();

The Assertion

The assertion throws in a curveball and you don’t use the UICalculatorWindow on this one. Instead, assertions have a class created called assertionNameExpectedValues and then the name of the text control.

this.UIMap.ValidateSumExpectedValues.UIItem3TextDisplayText = TestContext.DataRow[“Sum”].ToString();

After the equals follows the same pattern as before for mapping the correct column’s values.

Running the test now will run it three times in a row, adding the first two column values from the data source and then asserting the third column.

The final product of the code looks like

[DataSource(“Microsoft.VisualStudio.TestTools.DataSource.CSV”, @”c:\users\phillipwolf\documents\visual studio 2013\Projects\CodedUITestProject1\CodedUITestProject1\data.csv”, “data#csv”, DataAccessMethod.Sequential), DeploymentItem(“data.csv”), TestMethod]

public void CodedUITestMethod1()


// To generate code for this test, select “Generate Code for Coded UI Test” from the shortcut menu and select one of the menu items.

this.UIMap.UICalculatorWindow.UIItemWindow.UIItem1Button.SearchProperties[WinButton.PropertyNames.Name] = TestContext.DataRow[“Num1”].ToString();

this.UIMap.UICalculatorWindow.UIItemWindow2.UIItem2Button.SearchProperties[WinButton.PropertyNames.Name] = TestContext.DataRow[“Num2”].ToString();

this.UIMap.ValidateSumExpectedValues.UIItem3TextDisplayText = TestContext.DataRow[“Sum”].ToString();




CUITs: Automating Web Page testing and the Ajax trickster.

(If you’re not interested in my short story and want to skip ahead to the issue being faced and the resolution  go to THE PROBLEM heading.)

So for the past few weeks I’ve been attempting to come up to speed on using CUITs to automate my every testing needs. One of the items on my testing palette is a web page. There are a couple different languages that can be utilized in order to craft a web page into a beautiful butterfree, such as HTML, CSS, and JavaScript. (Let it be known now that I am NOT  a professional web dev and my experience in web development has been summed up by High School classes and a college course)

As pretty much everyone who’s ever stepped onto the interwebz these days know (thanks to MySpace! :P), HTML is the staple language in creating a website. Anyone can put a few lines of HTML into a notepad document and BOOM a “website” appears (obviously not THAT simple, but you get the idea). A while after the birth of HTML came along this thing called CSS, Cascading Style Sheets. CSS allowed web devs to use HTML primarily for placing elements on the screen, not for making it look pretty. You could then create a single CSS document that would be linked to the HTML pages which then would then add the “makeup” to the web page giving it the polished look. Then, to make websites even more interactive and to further increase the coolness factor, JavaScript began to be implemented in the web pages as well. Now JavaScript does a bunch of cool stuff like running client-side scripts, controlling the browser, altering the pages content and asynchronous communications. This my friends, is where my issues began.

After weeks of being trumped on the same issue, someone smarter than I pointed out something in the websites code I was attempting to automate. The website uses JavaScript and implements a technology known as AJAX. AJAX stands for Asynchronous JavaScript And XML and can also be known as AJAJ, Asynchronous JavaScript And JSON.


Ajax (also AJAX; /ˈeɪdʒæks/; short for asynchronous JavaScript + XML)[1][2][3] is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required; JSON is often used instead (see AJAJ), and the requests do not need to be asynchronous.[4]

Ajax is not a single technology, but a group of technologies. HTML and CSS can be used in combination to mark up and style information. The DOM is accessed with JavaScript to dynamically display – and allow the user to interact with – the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

Upon Googling (This hasn’t been added to the dictionary yet? Whaatttt?)  Problems with CUITS and AJAX, we discovered that the version of AJAX we were using causes conflicts with the CUITs.

Enough Short Story.


The problem I’ve been exhibiting is that when I record a test through Visual Studio’s Test Recorder, the playback of the test would be incorrect. Events were not being executed upon clicking certain elements on the page and therefore the data wouldn’t be sent or retrieved correctly.


The website in question, uses AJAX calls when the button I was attempting to test is clicked.  The AJAX calls were responsible for correctly transporting the data to the DB and letting it know I was adding something to the page and then displaying the results on the page. CUITs don’t play nice with the version of JQuery on the web page (v2.0.3), thus concluding in unexpected test results.


The solution to the issue was simple.  One line of code resolved all my issues. Inside the list of local variables (empty by default) for your CUIT.cs file, a single app setting is required.


The line

ConfigurationManager.AppSettings["WebWaitForReadyLevel"] = "3";

Is what is required to make the CUIT play nice with AJAX calls to the server. With this single line of code, the doors to Web Page Automation shall be open and rainbows will emit unicorns that twirl sparklers throughout the sky. Seriously, it’s that awesome.


Hopefully someone will be able to make sense of my ramblings here and will prove useful!



How To: Create a CUIT(Coded UI Test)

It begins….

A BIG item on my list of items to get done for a while has been to learn how to test a GUI, automatically of course. I’ve done a bit of research to find out what would be the best method to go about trying to implement this. I’ve looked through various scripting languages like AutoIt, possibly using a module and .NET through PowerShell and also C#.

What I finally decided to devote time into and giving a REAL shot was via C# and CUITs (Coded User Interface Tests). Visual Studio features a pretty awesome ability to record the actions you take while testing your GUI and then generates the code necessary. Once the code is generated you are able to freely edit it to your needs, such as adding a loop to turn adding an item once into adding it 5, 10, 50+.

What’s Needed?

Visual Studio Ultimate or Premium.
An application or web page to test.
A wee bit of C# knowledge (I’ve only been at this for ~month).
A bit of time.

Let’s Dig in.

To start creating a CUIT, a CUIT project needs added to the application solution. To add a new project, Right-Click on the Solution in the Solution Explorer and click Add -> New Project.



After you click OK to create a project, you’ll be prompted to choose the way in which you wish to add the CUITs to the project. Especially for the first time (since there are no tests to import) we’ll want Record Actions, edit UI map or add assertions.


After clicking OK on this one, Visual Studio will minimize and this box will appear


This is the little guy that records the actions you make on the GUI. The application that I’m going to show this off with will be a very simple one. All it has is the current version # in a text box and a button that displays a message box upon being pressed.


(The message on the main window is just because it’s a ClickOnce application I was testing to verify that it’ll update on it’s own upon launching 😀 Which works 😀 )

So now we’ve got an application open and the CUIT builder. To begin testing, simply click the red circular button. The builder when begin to record any apps you open, the clicks you make and any strings entered into a form. For my app, I simply want to open it, click start, click the OK button on the message box that appears and then close it again.

Recording is as simple as it sounds.

Step 1. Click the Record Button
Step 2. Double Click the App
Step 3. Click Start
Step 4. Click OK
Step 5. Click Close on the app
Step 6. Click Generate Code on the CUIT Builder

Once you hit Generate Code, you’ll be prompted to name the method that’s about to be created and add a little description.


Finish up by clicking Add and Generate – VOILA!

Close the CUIT Builder and Visual Studio will now appear. You might notice that some code has been generated for you now.


To actually execute your test, you’ll need to Build the Solution  (In Solution Explorer, R-Click the Solution -> Build) and then open the TEST explorer (if you don’t see it, click the TEST tab up top from the menu hover over Windows -> TEST explorer). You should see a dropdown called CodedUITest1 with CodedUITestMethod1 under it.


R-Click ‘CodedUITestMethod1’ and choose ‘Run Test’ – BOOM! Auto-Mation at your finger tips!

—— 10/29/2014 UPDATE —–

Refer to on how to create Data Driven tests in order to have a test run multiple times with different values .

The code below does technically work, but it requires moving the code from UImap.uitest to UImap.cs  (which I didn’t outline because at the time I didn’t know). Doing so will greatly reduce the ease in editing these tests as it gets much more code intensive. If you don’t move the code over (by right clicking the method name on UIMap.uitest and choosing move code) then anything you do will be overwritten the next time a test is recorded.


Now, you may recall at the top saying that you need a little bit of C# knowledge. That part comes next.

What if I wanted to do that test more than once without having to click run over and over? Loops, duh!


But this didn’t work out exactly like I was expecting it too! The first time I ran it with no issues, and now, it’s throwing errors! (Unfortunately I can’t show the actual error because I fixed it and forgot to get the exception message and now I can’t reproduce the error >.<)

The application was failing to close so I took a look see at what the Generated Code came up with.


I noticed four lines of code that didn’t look right for what I wanted. The first being the top where the uIParagraphPane is defined as a HtmlDiv type. It has the name of my blog in it. I definitely didn’t mean to do that. The three highlighted parts of the image is what actually interacts with uIParagraphPane which means I don’t want that either. The Playback.PlaybackSettings.ContinueOnError obviously wasn’t doing it’s job too well on that attempt (though it most likely worked after I removed my fix seeing as it didn’t happen again). So, I removed those lines. No more error!

While we’re at it, why don’t we add another loop to click the START and OK buttons 4 times each time the app opens and closes as well?


All I had to do was find the line that clicks the start button and the line that clicks the OK button then encase them within a for loop!

This is what I’ve been able to master after only -2- days of working with this stuff and very minimal knowledge of C# and reading exceptions.

I’ll follow this post up with how to implement the same test on another PC that DOES NOT have Visual Studio Premium/Ultimate installed.

UPDATE 9/18/2014 — If you have any question regarding CUITs, FIRE AWAY! I’ve got a lot more experience with them now.