Thursday, May 28, 2015

Visual Studio Plug-In: Developer Assistant

Visual Studio Developer Assistant Plug-In

This will be a quick blog folks, I'm just covering a nifty plug-in for Visual Studio called the Developer Assistant. It's a free plug-in from the folks at Microsoft. What's it do? It helps find code samples (github, Bing search, and even your own local code repositories) with a search feature, it enhances the built-in intellisense feature of Visual Studio, there is a compiler error search assistant feature, and there's probably more but that's all I've run across so far.

You can find out more here: Visual Studio Developer Assistant Plug-In

Note: I've only used it in VS 2013 Community Edition. It may be usable in other versions of Visual Studio.

C# Extension Methods

Introduction


Ever want to add some new methodology to your code but don't feel the urge to create a brand new type to do it?  Extension methods are your friend!  In this blog I'll create a sample extension method and call it through some test case scenarios displayed to the user.

Let's code!


I'll start out by making a sample class called MyExtensionMethodSample.  Within it I'll create a string called YourMom which takes a parameter of string.  I'll let you read the following source code, bonus points if you get the funny being made :) :

namespace ExtensionMethodsBlogSource
{
  public static class MyExtensionMethodSample
  {

    public static string YourMom(this String str)
    {
      if (str == null)
        return "Your Mom should never be null!";
      return "It is known";
    }

  }
}

Now it's time to use our new extension method.  Check out the following code snippet:

using ExtensionMethodsBlogSource;

namespace ExtensionMethodsBlogSource
{
  class Program
  {
    static void Main(string[] args)
    {
      string yourMom = null;
      Console.WriteLine("1: " + yourMom);
      Console.WriteLine("2: " + yourMom.YourMom());
      yourMom = "YourMom isn't null";
      Console.WriteLine("3: " + yourMom);
      Console.WriteLine("4: " + yourMom.YourMom());

      // do the rest
      Console.WriteLine("\nPress Any Key to Exit.");
      Console.ReadKey();
    }
  }
}

We're starting out with the new string yourMom being null.  Writing out some data, it's null so you won't see anything.  Calling yourMom.YourMom() should return "Your Mom should never be null!".  Setting yourMom to "YourMom isn't null" will display that for the 3rd line.  Testing against yourMom.YourMom at this point should give us "It is known".

Output


And our results:













Huzzah, it works as expected.  For a real challenge go implement some of this with Pete's named arguments blog from last week and create some coding magic.

Source:

Extension Methods

Thursday, May 21, 2015

C# Named Arguments

Intro

Whose turn is it to take out the trash? What's the answer to everything? Is Bieber better or is One Direction? Team Jacob or the pasty one? These are some great examples of named arguments.

Wait, what's that? Oh, that's not the kind of named arguments you care to read about? Ok fine. For the record, it's clearly 42, but we'll move on to C# named arguments.



The code sample is in VS 2013 .Net 4.5. Named arguments have been around since VS2010 though so you can follow along with older versions.

Que?

I'm sure you've all seen optional parameters in C# by now. Just in case you haven't, here's an example:

namespace NamedArgumentsBlog
{
    public class Class1
    {
        public void OptionalParams(int param1, int? param2 = null, string param3 = "")
        {
            //do stuff here
        }

        public void CallMethods()
        {
            //call with all params
            OptionalParams(1, 33, "fred");
            //Call with the required and 1 optional param
            OptionalParams(-12, 0);
        }
    }
}


The method OptionalParams has 3 parameters. The first one is required because it has no default value. 2nd and 3rd parameters are optional; if a caller doesn't specify a value for a parameter, it gets the default value. But hey you already knew this stuff, so let's see what we can do with named arguments.

Here's another sample. This uses the same class and the same 2 methods, but with a slight twist. Starting at line 17, we call the OptionalParams method a couple times, specifying which argument we are populating based on the name of the param rather than using ordering to implicitly specify params. Neat!

namespace NamedArgumentsBlog
{
    public class Class1
    {
        public void OptionalParams(int param1, int? param2 = null, string param3 = "")
        {
            //do stuff here
        }

        public void CallMethods()
        {
            //call with all params
            OptionalParams(1, 33, "fred");
            //Call with the required and 1 optional param
            OptionalParams(-12, 0);
            //call with named params in order
            OptionalParams(param1: 44, param2: 21);
            //call with named params out of order
            OptionalParams(param3: "blah", param1: 42);
        }
    }
}


Simple eh? You just specify the name of the parameter and the value of the parameter, separated by a colon. I must admit I don't use this trick very much, but it's another tool in yer shed. Use wisely.

Resources

Named and Optional Arguments (C# Programming Guide)

css3 advanced, now with flair

Introduction


So now you've seen a box change colors and move in a particular pattern.  For this lesson's sample I borrowed heavily from Roman Cortes's pure CSS coke can sample

Onto some coding!


Quite a bit to implement (code/graphics/etc...), I'll let you download and run via VS Express 2013 for Web:  code to download

I will discuss one small section of code in particular:  overriding the internal div tag along w/ overriding the p tag.

        div div {
            background-image: url(scroll.png);
            background-repeat: no-repeat;
            background-position: 0 0;
            padding-left: 300px;
            width: 660px;
        }

        p {
            margin: 0;
            padding: 0;
            float: left;
            height: 336px;
            background-image: url(SamAdamsSummerAle.png);
            background-attachment: fixed;
            background-repeat: repeat-x;
            width: 1px;
        }

Without the background-repeat within the div div tag scroll.png shows up multiple times in your browser.  Removing background-repeat within the p tag has the same effect for SamAdamsSummerAle.png.  Removing background-attachment: fixed from the p tag doesn't give the cool scroll effect we're looking for, keeping it in the tag lets the graphic of choice achieve movement with the scrollbar.

When you run it you should see something like the following:















Scroll that slider and watch the magic happen.  Try some more advanced coding on your own: give the option to switch between bottles and cans, or even better another option to switch brands of the beverage of your choice.

Source Reference(s):


Roman Cortes Pure CSS Coke Can

Thursday, May 14, 2015

A Partial Object Update Trick in C#

Intro

At least one time in my life someone has asked me a question that goes like this:

"I have a class with a bunch of properties. I want to update some or all of them, in any combination. How can I do this?"

Well you could just set the values of course, you could call a method that has an optional parameter for each property of the class, and you could of course pay a badger to write some clever new trick for you. We'll go with the badger option! The rest of the blog details what the badger would write.

Note: Sample code is in VS 2013.




Details

Within the class that you wish to update, create a SetAll or SetMany or whatever method where you pass in another instance of your class (source). Check each property and if it's non-null, you set the destination object's property value to the source object's property value. Note that this tactic will depend on nullable types, and assumes you can ignore null values passed into a new setter method. Here's an illustration:

using System;

namespace BlogPartialUpdateTrick
{
    public class SomeClass
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int? HeightInches { get; set; }
        public DateTime? Dob { get; set; }

        public void SetAll(SomeClass source)
        {
            this.FirstName = source.FirstName ?? this.FirstName;
            this.LastName = source.LastName ?? this.LastName;
            this.HeightInches = source.HeightInches ?? this.HeightInches;
            this.Dob = source.Dob ?? this.Dob;
        }

        public override string ToString()
        {
            return String.Format("fn: {0}, ln: {1}, height: {2}, DOB: {3}", FirstName ?? String.Empty, LastName ?? String.Empty, 
                HeightInches.HasValue ? HeightInches.Value.ToString() : "null", Dob.HasValue ? Dob.Value.ToShortDateString() : "null" );
        }
    }
}


In this first code sample, We have my spiffy class SomeClass. It's got 4 properties, all of which are nullable. The noteworthy part of this class is the SetAllMethod where I can pass in a source object which is also of type SomeClass. It sets this instance's property values to the values passed in the source parameter, but only if they're non-null. Here's a 2nd code blurb where I'm using this stuff:

using System;
using System.Windows.Forms;

namespace BlogPartialUpdateTrick
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var destination = new SomeClass() { FirstName = "Freddy", LastName = "Fingers", Dob = DateTime.Parse("01/01/1970"), HeightInches = 72 };
            var source = new SomeClass() { FirstName = null, LastName="Flippers", Dob = null, HeightInches = 80 };
            destination.SetAll(source);
            MessageBox.Show(destination.ToString());
        }
    }
}


Create a destination object, a source object, call the new method, voila! output is this:

"fn: Freddy, ln: Flippers, height: 80, DOB: 1/1/1970"

Thursday, May 7, 2015

Simple Lambda Expressions in C#

Intro

I'm not going to go too in-depth regarding Lambda expressions or how to use them in .Net. Rather, I will just show you a short sample to whet your appetite. If you've already used lambda expressions or LINQ then this post might not teach you much, but it's a short post so suffer through it if you can :)



Code samples are in VS2013, .Net 4.5. Other environments might work just fine too.

Example


using System;
using System.Collections.Generic;
using System.Linq;

namespace BlogLambda
{
    public class SomeClass
    {
        public int ANum;
        public string AString;

        public override string ToString()
        {
            return "(" + AString + ":" + ANum + ")";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var things = new List<SomeClass>();
            things.Add(new SomeClass() { ANum = 2, AString = "cheese" });
            things.Add(new SomeClass() { ANum = 1, AString = "bacon" });
            things.Add(new SomeClass() { ANum = 7, AString = "tires" });
            things.Add(new SomeClass() { ANum = 4, AString = "apples" });
            var orderedThings1 = things.OrderBy(t => t.ANum);
            orderedThings1.ToList().ForEach(thing => Console.Write(thing));
            Console.WriteLine("---");
            var orderedThings2 = things.OrderBy(t => t.AString);
            orderedThings2.ToList().ForEach(thing => Console.Write(thing));
            Console.WriteLine("---");
            Console.ReadKey();
        }
    }
}


As promised, a pretty small sample. First we declare a new class called SomeClass. It's got 2 fields, and int and a string. It's got a single ToString method that we'll use just to illustrate what's going on.

The real meat here is within the Main() method (as you may have guessed, this is a console application). We first create a new list of objects of type SomeClass and initialize it with 4 new instances. Things get interesting on line 27, where we have our first lambda expression. The OrderBy method lets us sort the things object by whatever we tell it to sort. In this case we're sorting on the ANum property. If you haven't seen lambdas before the syntax might look a little weird. To me it helps if i think of "things.OrderBy(t => t.ANum)" meaning "sort things by t such that t.ANum". Basically I pretend that " => " means "such that". It's not always a great way to conceptualize, but it's helped me.

Moving on, you can see that we then output the list (notice the cool use of the ForEach extension method which allows us to spit out the whole list to the console, with a single line of code). We then sort the list a 2nd time on the AString field and send the output to the console once again. Here's the output:

(bacon:1)(cheese:2)(apples:4)(tires:7)---
(apples:4)(bacon:1)(cheese:2)(tires:7)---

That's all there is to it! First list sorted by ANum, second list sorted by AString.

What's Next?

Lambda expressions can get way more useful and way more complicated. I've barely even slightly rubbed the surface, much less scratched it. Read up on them! If you haven't tried LINQ yet, jump into that too. It can be a great time saver for us coder types.

Resources

dotnetperls Lambda

Documentation

One day in your coding career (preferably early) you'll reach the point of:  I wrote this weird thing  and for the life of me can't recall what I was attempting to accomplish.  Where'd I go wrong?  What could I have done back then that would've saved me countless hours in the future?  Document your code!

Techniques:


Chances are if you went to college to learn to write software they may have emphasized self-documenting code (aka naming your for loop variable i or x when looping through a list of table rows you could've named the variable rowIndex or something more definitive).  If not, it's a great idea to try to implement self-documenting coding techniques.  Your present and future colleagues will appreciate you more for that one.

Another option is to put in the occasional comment or two.  Generally speaking if I can't rationalize what an obscure block of code is doing (happens quite a bit out in the wild) I throw in at least some documentation on what that block of code is attempting to do.  That way future me and present me can be on the same page quicker than not so future me can determine what action to do next to it more efficiently than if it the coding block wasn't documented.

The last option is putting your pseudo-code into comments near your obscure block(s) of code.  If nothing else future you (or your colleagues) can try to see what present you was attempting to do in the source code.  This form of documentation is one I've been trying to implement in the past six months or so, so far I've used it a few times when the self-documenting code as well as the comments for each block might now give future me (or a colleague) an idea of what present me was attempting to create.

Conclusions


Documenting your code might seem like a bit of a hassle but in the long term it'll save future you (and potentially your colleagues) time to debug/determine what your present code is doing.

Shout outs:


I have to give credit to Peter Hyde and Bobby Russell for blogging along for quite some time now, keep up the great work guys!

Sunday, May 3, 2015

Reflection in C#, Part 2

Intro

This here posting is part 2 of 2 in our series on Reflection in C#. Review Part 1 first to see what we started with. All done? OK cool. You wouldn't lie to me about that would you? Nah of course not, I trust you. On with the blog! We saw in the last post how we can list the classes in an assembly and how to create an instance of a class through reflection. Useful stuff. We have more work to go though so let's get it on! Or something.


Note: Samples are VS2013 Community edition, .Net 4.5. Here is the sample project if you want to play along.

What Else Can Reflection Do?

Other than listing the classes in an assembly and creating an instance of a class, what else can we do with reflection? We can list and modify property values, and we can list and execute methods. There's a little more too, but those 4 things are what I want to cover right now. So, let's see some of it in action!

First we have here a class that doesn't do much. It's got a single string property that we're going to play with, and a constructor that sets a default value for said property.

namespace BlogReflection
{
    public class DummyClass
    {
        public string AValue { get; set; }

        public DummyClass()
        {
            AValue = "timmeh!";
        }
    }
}


This class by itself doesn't illustrate anything other than I can type the word Dummy. So, have a look-see at this second class:

using System;
using System.Reflection;
using System.Windows.Forms;

namespace BlogReflection
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            var a = Assembly.GetExecutingAssembly();
            ListClassesEntry.Items.AddRange(a.GetTypes());
        }

        private void ListClassesEntry_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(ListClassesEntry.SelectedItem.ToString()))
            {
                var assembly = Assembly.GetExecutingAssembly();
                var formType = assembly.GetType(ListClassesEntry.SelectedItem.ToString());
                var constructor = formType.GetConstructor(new Type[] { });
                var instance = constructor.Invoke(new Object[] { });
                var methods = formType.GetMethods();
                string methodNames = "METHOD NAMES: ";
                foreach (var method in methods)
                    methodNames += method.Name + ",";
                MessageBox.Show(methodNames);
                var toStringMethod = formType.GetMethod("ToString");
                MessageBox.Show("ToString() : " + (string)toStringMethod.Invoke(instance, new Object[] { }));
                var properties = formType.GetProperties();
                string propertyNames = "PROPERTY NAMES: ";
                foreach (var property in properties)
                    propertyNames += property.Name + ",";
                MessageBox.Show(propertyNames);
                var selectedProperty = formType.GetProperty("AValue");
                MessageBox.Show("AValue: " + selectedProperty.GetValue(instance).ToString());
                selectedProperty.SetValue(instance, "some silly value");
                MessageBox.Show("AValue: " + selectedProperty.GetValue(instance).ToString());
            }
        }
    }
}


This class does 4 important things that illustrate the functionality of reflection:
  1. Find all methods of a class: Line 28, where we call GetMethods(), returns an array of methods in the class DummyClass.
  2. Execute a method: Line 34 uses Invoke, passing it a reference to the ToString method to call it. 
  3. Find all properties of a class: Line 35 calls GetProperties, which returns an array of all the properties of our class DummyClass.
  4. Get and set a property value: Lines 41 and 43 retrieve the value of the property AValue, while line 42 sets the value of the property AValue.

Not really all that complicated is it? Reflection sounds mean and nasty, but once you get into it it's as easy as theoretical physics. Or pie. Mmmm, pie.


Resources

C# Reflection