C# Referencing List Items with Both Indexes and Strings

Defining an indexer allows you to create classes that act like “virtual arrays.” Instances of that class can be accessed using the [] array access operator. Examples include Settings[0] or Settings["ComputerID"]. See the code below:

Another option is an extension method. Call it like Settings.GetByName("ComputerID"):

Read More

Use a Counter with a Foreach Loop in Razor

Using bootstrap I wanted to create a two column grid with the data provided to the model. To accomplish this I needed to surround every two divs of class col-sm-6 with a div of class row. To do this I implemented a counter. I then used modulus to determine if I should open the tag or close it.

Another thing to note is that razor shows syntax errors if you just include an opening tag without its closing tag. If you run the code you will likely get a broken page complaining about missing curly braces. To get around this prepend each tag in their respective if-statements with @:.

Read More

Overcoming Problems in the Unified API Upgrade

I recently upgraded my Xamarin.Mac application to the unified API. This allows for a single code base that works on 32 and 64 bit applications. But besides that its needed to put anything in the app store. As of Feb 1, 2015 Apple requires that all new submissions to the app store must be 64 bit applications. Since the classic API is limited to 32-bits only this is necessary to get your app in the reach of others.


Go to Project > Migrate to Xamarin.Mac Unified API

Afterward some of my packages had error flags by them. I chose to update my packages.

When I went to Run the project a dialog appeared saying, "The application has not been built". I finally overcame this issue by renaming my project. I had a project with a "." in the name. I switched to an underscore and it finally built.

Steps to Rename a Project

  1. For your project go to Options. Under General > Main Settings change the Name and Default Namespace. Under Build > Output change Assembly Name.
  2. Open a cs file. Select the namespace. Rename it with the Refractor option.
  3. Next, right-click (or ctrl-click) on the project and choose Open Folder Location. At this point be sure to fully exit Xamarin Studio. Rename the project folder. Open the sln file in a text editor and adjust the project’s file path to account for the change.
  4. Delete bin and obj folders
  5. Re-open the solution and build the project

I follow the same steps when I rename a project in Visual Studio too.


The next issue I came across concerned SignalR. It was no longer working. From a try/catch I received this error, "Could not load file or assembly 'System.Net.Http' or one of its dependencies." So I removed my SignalR Client Nuget. When I reinstalled it a few more dependencies were added. Now when I built my application I got 3 errors concerning assembly names that have already been imported. The message resembled, "An assembly with the same identity ‘System.Threading.Tasks, Version…" This problem seemed to come from the new Microsoft.BCL dependency package. The 3 DLLs in question were:

  • System.Threading.Tasks
  • System.IO
  • System.Runtime

Searching online people were suggesting altering the app.config file. I didn’t have any luck with that. I searched for other nugets that had been altered to work in this scenario. No such luck. Finally, I looked in the simplest of places. I went to References > Edit References. Under the .NET Assembly tab the 3 DLLs were listed. I unchecked them and tried again. It worked like a champ. SignalR connectivity was fully restored.

Read More

Cancel/Abort a Closing Window in Xamarin.Mac

Close Dialog

I began by researching the WillClose event to accomplish this. With it I could detect the window as it was closing but could not find a way to abort with the EventArgs provided. I achieved success with a delegate class that overrides the WindowShouldClose method .
Put this class in the window.cs below the partial class that was pregenerated:

Assign the delegate wherever you instantiate the window controller:

Read More

Comparing C# Objects

There are times when you need to compare objects. Microsoft includes a built-in Equals function. When it comes to comparing instantiated objects it will return False unless the two objects are the result of the same instantiation. If your definition of equality is the two objects of the same type with the same property values then you need to implement a different approach. I typically serialize the object then compare the string values.

The JsonConvert object is included with the Json.NET nuget.

Read More

Center a Window in Xamarin.Mac

To make my window appear front, centered and focused I have had success with the following:

This works exceptionally well when invoked from a NSStatusBarItem.

Read More

Add Code Behind to a Resource Dictionary

I recently used a Resource Dictionary and wanted to be able to tweak the xaml components on it behind the scenes. This can be accomplished fairly easily:

  1. In your project add a new class file. Give it the same name as the xaml.
  2. In the newly created file override the contents of the namespace with this code:
  3. Next, go to your <ResourceDictionary> tag in the xaml file. Add this property with the appropriate namespace and name: x:Class="namespace.classname"

Now the two should be linked up. In Visual Studio, however, they will not be nested like normal xaml files. This bugged me. I read online that the csproj file can be edited in notepad to accomplish this. I tried and for some reason I couldn’t get it to take. I did have success with VSCommands. It is an install that adds extra features to Visual Studio. Once installed select the xaml and cs with your mouse in the tree. Right-click and choose Group Items. Choose the xaml as the root item to be conventional. Now Solution Explorer should show them as paired.

Read More

Invert the Transparency in an Image with Gimp

You can easily invert the transparent parts of an image with Gimp. Gimp is an open source Photoshop alternative.

Follow these steps:
  1. Choose Colors -> Components -> Decompose from the menu and set Color model to RGBA.
  2. A new image is opened with all color channels (including alpha channel) decomposed as single layers.
  3. Select the layer alpha and choose Colors -> Invert from the menu.
  4. Choose Colors -> Components -> Compose from the menu, set Color model to RGBA and make sure the layers are correctly mapped to the channels (should default correctly if you did not reorder the layers)

It will open a few new Gimp tabs but it will, indeed, invert the transparent areas of the image. This worked well for me on an image of a single color with transparency.

Read More

How to Queue up Method Calls in C#

First you need to instantiate a List of type Action:

Next, we will add methods to the list. We do this through Lambda Expressions using a specific syntax: () => { TestFunc("data") };

With this technique local methods can be stored along with parameters for future execution. In the example below you can see two Console.WriteLine statements. But since the first method is housed in the expression it does not fire until executed later. However, the subsequent one will fire immediately and be listed first in the output tab of Visual Studio:

To fire off each method loop through and use function params to execute:


Read More

Perform Scheduled Table Maintenance in SQL Server

Have you ever had a need to do routine maintenance on your database tables? For instance, moving older records to history, fixing anomalies, removing bad/incomplete data, updating flags under certain conditions, etc. These types of recurrent tasks can be implemented easily within SQL Server Management Studio (SSMS). With an SSMS component known as SQL Server Agent you can execute T-SQL statements on a repetitive schedule.

SQL Server Agent can be found at the bottom of the Object Explorer pane. Right-click on it and select New > Job. A window pops up to specify the name of your job with some other defaults. Notice the options on the left-hand side. This tutorial touches on the Steps and Schedules options.

Click on Steps. In the window that appears click the New button. A dialog will appear as follows:

SQL Agent Steps New Dialog

In the dialog you can select your database and enter T-SQL statements to perform the job. For example:
or even a stored procedure:

I recently created a job to maintain several tables. Then for each step I provided the T-SQL needed to do my maintenance on each table. Steps can be deleted individually and re-ordered.

Next, you need to set the schedule. Click on Schedules and click the New button. There are many options here to customize the run time to your liking:

SQL Agent Schedule New Dialog

Finally, save the job to make it live. And that’s it. You have created a table in an environment that can perform further automation. There is obviously many more options to explore in SQL Agent. This is just a taste.

Read More