Named Arguments

This may seem trivial but I just recently came across this gem. Named Arguments allow you to specify which argument a value belongs to in a method call. One of its advantages is that it frees you from looking up the order of parameters in the call. Meh! That may be cool for some but I find myself around knowing that answer from intellisense while typing. But an application that is useful is if you have a slew of optional parameters and you only need to adjust one or more further down the line.

The following is a traditional way in which you would adjust a distant optional parameter. You would have to supply all the argument values that proceed it:

Now using named arguments you can call it as follows:

It simplifies the call and makes it easier to know the meaning of each argument at a glance. There have been times in the past where I have used Overloading to bridge the argument gap. Now with Named Arguments, I have another tool in my arsenal to supply arguments in a precise and intelligible way.

Read More

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

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

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:

Chad

Read More

Convert Razor Validation Summary into Bootstrap Alert

In MVC, if you use the Validation Summary method any validation errors for the model are presented back to the user in a bulleted list. If you have been using bootstrap throughout the site you may want to give this message the same look and feel to have consistent interfacing. This error summary can easily be converted into a bootstrap alert to show to the user. Simply expand upon that call with this logic:

By default, @Html.ValidationSummary() returns nothing if no errors. But since we are adding additional markup for the bootstrap alert we must check for errors ourselves. The result will be a closable, danger alert with a heading and bulleted, error list inside.

Next, you may want to clean up the classes added by the validation summary. This can ensure that you will not have any CSS rendering issues as well as expanding upon the bootstrap look. I simply added this javascript at the bottom of my view:
The first call cleans up the list itself. The second call will put a bootstrap danger highlight around your fields with the issues. If the red outline does not appear then make sure you are following bootstraps recommendation of wrapping form elements and their labels in a form-group class. For example:

Read More

WPF Label – Click and Focus on Element

WPF applications have labels and controls but, unfortunately, they don’t integrate together as easily as in HTML. In HTML you rely on the id and for attributes to bind them together. Then when the label is clicked the control gets focus. So in that environment labels serve to identify the control, as well as aid in accessing it. Sometimes it’s easier to click on a label then the form element itself, such as with checkboxes and radios.

I wanted to achieve the same effect in WPF. I accomplished this by creating and referencing my own customized label. The new label inherits all the features of a traditional label but also includes a few others.

To begin, we create the class. Out of the box a WPF label will stretch horizontally to fill the entire area it resides in. By setting the HorizontalAlignment it collapses it down to the width of its content. This can be overridden in the xaml. We then give the element focus based on a mousedown event.

I also have a bit of code just for textboxes. Once focused the cursor will be placed at the front of any text. You can use the code below to move the cursor to the end, or select the text.
Next, we need to reference the new label in the xaml. To do this we must declare a namespace in the Window object then reference it on each call to the control. The example shows EnvelopePrinting. Replace that with the name of your namespace. We also use Target attribute and Binding call to link the two elements together.

Read More