Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, July 9, 2015

C# Anonymous Functions

Intro

Anonymous Functions: Things that activist hacker group does when they go into the potty room. Darn, I keep forgetting this is a programming blog! OK in this case an Anonymous Function is an "inline statement or expression that can be used wherever a delegate type is expected." (1). In layman's terms, rather than supplying a fully-defined function to a delegate, you can create an anonymous function within your normal code and use that. It's hard to explain, so let's see it in action.



Code Samples in VS2013, .Net 4.5.

Simple Use Case



using System;

namespace BlogAnonymousFunction
{
    public class Thingy
    {
        public string DoAThing(int val1, int val2, Func preProcessor = null)
        {
            int val3 = -1;
            if (preProcessor != null)
                val3 = preProcessor(val1, val2);
            return String.Format("val1:{0}, val2:{1}, val3: {2}", val1, val2, val3);
        }
    }
}


using System;

namespace BlogAnonymousFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            var thingy = new Thingy();
            var result = thingy.DoAThing(24, 42, null);
            Console.WriteLine(result);
            result = thingy.DoAThing(24, 42, new Func((val1, val2) => val1 + val2));
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}



A simple example to be certain. Our class Thingy has a single method DoAThing that accepts a function as a parameter. If the user passes in a value for this nullable function we will call it and set it to our 3rd value.

In the Main method we call DoAThing twice. First we call it once passing in a null function parameter. In the second call we pass in an anonymous function that adds the first and 2nd parameter, returning the result. You can see the results of our two function calls in the output window screenshot below.


Cool huh? Simple too, but it does take a few repetitions to get used to the odd syntax. Enjoy!

What's Next?

You can also do generic methods (no return type), you can create variables that reference a generic function/method, and more! Search on teh webs, you'll find plenty.

Resources

(1) Anonymous Functions
The Generic Func Delegates

Thursday, June 4, 2015

AutoMapper with C#

Intro

Our world is a cold, cruel place where mapping the properties of one type to the properties of another type is a tedious chore, best left to bleary, dreary late night work while buzzed on enough caffeine to bug-eye a rhino. But wait, what light yon winder breaks? or something...


AutoMapper! If you guessed that AutoMapper is a new way to create your own maps from within a car, you'd be wrong! AutoMapper is a NuGet package that you can use in .Net to map the properties of one type to the properties of another type. If for example you have a middle-tier Person class that needs to map to a backend database class called PersonDb, AutoMapper can take most of the tedium away from you. No more setting Person1.FirstName = Person2.FirstName, yadda yadda. All you have to do is make a single call to initialize the configuration, make another call to map object 1 to object 2, and you're golden! Let's see it in action.

Note: Sample Project is in VS2013 Community Edition.

Samples

OK let's get movin. Create yourself a console application. You'll then need to install the NuGet package named AutoMapper. I'll show you a different way than I've used in the past, maybe you'll find this easier or maybe not. Anyways...


then in the Package Manager Console, type "Install-Package AutoMapper"...


OK now we've got AutoMapper installed in our console app. Add yourself a couple classes to the project, named Type1 and Type2. Here is the code for each: 


using System;

namespace BlogAutoMapper
{
    public class Type1
    {
        public string FirstName { get; set; }
        public int Age { get; set; }
        public DateTime DateBoughtFirstCar { get; set; }
    }
}


using System;

namespace BlogAutoMapper
{
    public class Type2
    {
        public string FirstName { get; set; }
        public int Age { get; set; }
        public DateTime DateBoughtFirstCar { get; set; }
    }
} 

Pretty simple stuff here.Now let's use AutoMapper. First open up your Program.cs file and add a "using AutoMapper;" statement up in the using statements. Now plug the following code into your Main method:

using System;
using AutoMapper;

namespace BlogAutoMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            var type1 = new Type1() { Age = 44, DateBoughtFirstCar = DateTime.Parse("01/01/2000"), FirstName = "Perriwinkle" };
            Mapper.CreateMap<Type1, Type2>();
            var type2 = Mapper.Map<Type2>(type1);
            Console.WriteLine("type2.DateBoughtFirstCar: " + type2.DateBoughtFirstCar.ToShortDateString() + "...type2.Age: " + type2.Age + "...type2.FirstName: " + type2.FirstName);
            Console.ReadKey();
        }
    }
}

That's it! If you had 10, 20, or even 50 properties, it would map them for you. Pretty handy huh? Here's what the output loooks like, just to prove it does what it says it does:



What's Next?

AutoMapper has a ton more features. I've shown you only the very basics. It can handle copying lists of objects, it can hit up sub-objects, you can customize the value copying (note how right now the source and destination properties have to be the same name), you can make it look at private member fields, and so much more. Play around with AutoMapper and see what it can do for you. I wonder if it could be used as a poor man's object cloning, hmm...

Resources

AutoMapper
Keith Durham: Thanks for pointing out this gem to me sir!

Thursday, May 28, 2015

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)

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

Thursday, April 23, 2015

Reflection in C#, Part 1

Intro

Reflection is a technology whereby you can view and modify the structure and behavior of a program at runtime. This general definition always seemed a bit vague to me, so picture this: You have a class, and for whatever reason you want the user to be able to select a property of your object from a dropdown, and type in a new value for the property in a textbox. You could manually populate your dropdown with the property names and have a big switch statement to set the value, but reflection would make this much easier by allowing you to, at runtime, discover the names of the properties and set their values. Nifty! I've personally used reflection for custom serialization (If you've heard of and used the TurboTags 2.0 format then you've used my reflection), and I've used it for a custom storage system that works a lot like Entity Framework. Well, now that I've tooted my own reflection horn let's get down to shiny and highly reflective brass tacks.


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

 

What can Reflection Do?

  • List Classes in Assembly - You can get a listing of the classes within an assembly.
  • Create Instance of Classes - You can create an instance of one of them thar classes that you found.
  • List Properties - Need a listing of the properties of the class? Reflection has you covered.
  • Get and set property value - Ooh, and you can modify those properties too!
  • List Methods - Once you've listed the properties of a class, it's easy to list the methods.
  • Execute Methods - Executing the methods with reflection is simple once you've found them.
  • And More! - Yay more! You can get attributes and other things too.
Let's dig into some specifics. I doubt we'll cover all of them this week, but let's give it the ol' college try.

List Classes in Assembly

I've created a Windows Forms app for demonstration purposes. Let's start by listing all the classes in an assembly. The first thing we need to do, after creating the solution of course, is add a reference to the System.Reflection assembly. This is where we get all the reflection junk. Now we're going to, in the Form_Load event handler, populate a dropdownlist with the classes of our current assembly:

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


Getting a reference to the current assembly is easy with reflection. We accomplish the task above by calling Assembly.GetExecutingAssembly. The next line shows how to get all the classes contained within the assembly. In our case we come up with 4 distinct classes: BlogReflection.MainForm, BlogReflection.Program, BlogReflection.Properties.Resources, and BlogReflection.Properties.Settings. This is a nice, small, manageable list. Yay!

Create An Instance of a Class

Now that we have a list of classes within our assembly, let's create an instance of the selected class when the user selects a Type from the DropDownList:

        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[] { });
            }
        }


Another pretty simple method. The key part here is the call to GetConstructor and then the call to Invoke. GetConstructor, in this form, will find the constructor that accepts parameters as specified by the Type[] type array parameter. In our case we passed in an  empty array of type Type, so we want a parameterless constructor. The next line, Invoke, calls the constructor method passing in another empty array of parameters. So in essence we first find the parameterless constructor of the selected type, and we then invoke the parameterless constructor of the type. Neato! Tip: This method bombs horribly if the type you select, with the DropDownList, doesn't have a parameterless constructor. Oh well, nothing's perfect. Figure out how to get around that on your own :)

We're Done!

Hey Pete, you didn't talk about all the other cool stuff Reflection can do! You're right, what can I say; I'm lazy. We'll cover some more parts of reflection next week.

What's Next?

Figure out how you can call a constructor that has parameters. If you'd like to, you can also skip ahead to next week's topic by figuring out how to find and execute methods as well as find and get/set property values.


Resources

C# Reflection

Thursday, April 16, 2015

Web API Global Exception Handling Made Easy

Intro

Exception handling can be a bit of a chore. It always ends up looking the same; the familiar try...catch pattern, maybe you log the exception, maybe you rethrow it, yadda yadda. In a Web API you might even throw back a server error 500 response when you encounter an exception.

I know you're all sitting there chanting impatiently, willing me to tell you I can make it better...easier even! You're probably sitting at your desk or staring at your phone, thinking "Peeticus, please save us from the doldrums of routine! Help us!!". Well OK, just this once.Only because I can see the tears of joy brimming in your eyes.

Example

So I've made a simple Web API. It has a single GET method that throws an exception. Here's the code:

using System;
using System.Web.Http;

namespace BlogWebApiExceptionHandling.Controllers
{
    public class HandlingController : ApiController
    {
        public IHttpActionResult Get()
        {
            throw new ApplicationException("hey, an error!");
        }
    }
}

Run this thing and send a request to it with Fiddler. Here's what you get:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNccGVldGljdXNcZG9jdW1lbnRzXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xCbG9nV2ViQXBpRXhjZXB0aW9uSGFuZGxpbmdcQmxvZ1dlYkFwaUV4Y2VwdGlvbkhhbmRsaW5nXGFwaVxoYW5kbGluZ1w=?=
X-Powered-By: ASP.NET
Date: Fri, 17 Apr 2015 01:20:24 GMT
Content-Length: 2176

{"Message":"An error has occurred.","ExceptionMessage":"hey, an error!"...}

Server error 500 with a message. That's not too bad I guess, though the exception is unhandled. What if we want to log it, or send a notification email to somebody? you can put a try...catch around it sure. What if you have 5 methods? 50? all that try...catch becomes a pain in the arse. So, let's do this the easy way.

Now I add a new class to my Web API. This new class will be named GlobalExceptionLogger, but you can name yours whatever you want. Because this is only a demonstration of exception handling, I won't do anything complicated in here. I'm just setting a local variable to the Message property of the exception. Here it be:

using System.Web.Http.ExceptionHandling;

namespace BlogWebApiExceptionHandling
{
    public class GlobalExceptionLogger : ExceptionLogger
    {
        public override void Log(ExceptionLoggerContext context)
        {
            var stuff = context.Exception.Message;
        }
    }
}

There's one more line of code necessary to make this work. This new line of code goes in your WebApiConfig.cs file, within the Register method:

config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());

If you now set a breakpoint back in the Log method of GlobalExceptionLogger and fire up the Web API using Fiddler, you'll see that the Log method is called for the unhandled exception. Hey, now it's globally handled! Any further Web API controllers and methods will use this thing, which is exceptionally cool. Like me! :)

Resources

What's New in ASP.Net Web API 2.1

OpenGL in C#

Preface


Have you ever want to do some graphics programming but think to yourself: Hey, do I have other options than DirectX/Flash/Silverlight?  Fear not, OpenGL (Open Graphics Library) is an option you've had since the 90's.  Based on research I'd done in regards to generating the world famous glutTeapot via Delphi in the late 90s (don't laugh too hard) it seemed to be a great idea to port over some old school code into C#.

The install


As it's an open source product there are quite a few options to pull from.  For this blog I'm using OpenTK as it was the least hassle install/code conversion over than the other options out there.  This one's a pretty easy install compared to some of the topics I've blogged about in the past.  Click the install below and include the 3 dlls in your project (OpenTK.dll, OpenTK.GLControl, and OpenTK.Compatibility.dll) after you've extracted them from the downloaded file.

Some coding (well, quite a bit)


The glut (GL Users Toolkit) isn't quite available for our purposes, but as luck would have it I found a project out there that used OpenTK and mapped out the necessary vertices to fake the teapot quite well.  The original code within the Teapot class was written by Mark J. Kilgard in 1994.  Below I've created a console application to make use of some gaming capability we have able to us via Visual Studio, plus it looked pretty good in the window :).  Rather than giving a detailed explanation outside of the source code it'll most likely be easier to follow the line by line documentation I did within my project below.



using System;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;

namespace OpenGLConsoleApp
{
  class MyApplication
  {
    public static class Teapot
    {
      // Rim, body, lid, and bottom data must be reflected in x and
      // y; handle and spout data across the y axis only.
      public static int[,] patchdata = new int[,]
    {
      // rim
      {102, 103, 104, 105, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
      // body
      {12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27},
      {24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40},
      // lid
      {96, 96, 96, 96, 97, 98, 99, 100, 101, 101, 101, 101, 0, 1, 2, 3,},
      {0, 1, 2, 3, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117},
      // bottom 
      {118, 118, 118, 118, 124, 122, 119, 121, 123, 126, 125, 120, 40, 39, 38, 37},
      // handle
      {41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56},
      {53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 28, 65, 66, 67},
      // spout
      {68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83},
      {80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95}
    };

      public static float[,] cpdata =
    {
        {0.2f, 0, 2.7f}, {0.2f, -0.112f, 2.7f}, {0.112f, -0.2f, 2.7f}, {0,
        -0.2f, 2.7f}, {1.3375f, 0, 2.53125f}, {1.3375f, -0.749f, 2.53125f},
        {0.749f, -1.3375f, 2.53125f}, {0, -1.3375f, 2.53125f}, {1.4375f,
        0, 2.53125f}, {1.4375f, -0.805f, 2.53125f}, {0.805f, -1.4375f,
        2.53125f}, {0, -1.4375f, 2.53125f}, {1.5f, 0, 2.4f}, {1.5f, -0.84f,
        2.4f}, {0.84f, -1.5f, 2.4f}, {0, -1.5f, 2.4f}, {1.75f, 0, 1.875f},
        {1.75f, -0.98f, 1.875f}, {0.98f, -1.75f, 1.875f}, {0, -1.75f,
        1.875f}, {2, 0, 1.35f}, {2, -1.12f, 1.35f}, {1.12f, -2, 1.35f},
        {0, -2, 1.35f}, {2, 0, 0.9f}, {2, -1.12f, 0.9f}, {1.12f, -2,
        0.9f}, {0, -2, 0.9f}, {-2, 0, 0.9f}, {2, 0, 0.45f}, {2, -1.12f,
        0.45f}, {1.12f, -2, 0.45f}, {0, -2, 0.45f}, {1.5f, 0, 0.225f},
        {1.5f, -0.84f, 0.225f}, {0.84f, -1.5f, 0.225f}, {0, -1.5f, 0.225f},
        {1.5f, 0, 0.15f}, {1.5f, -0.84f, 0.15f}, {0.84f, -1.5f, 0.15f}, {0,
        -1.5f, 0.15f}, {-1.6f, 0, 2.025f}, {-1.6f, -0.3f, 2.025f}, {-1.5f,
        -0.3f, 2.25f}, {-1.5f, 0, 2.25f}, {-2.3f, 0, 2.025f}, {-2.3f, -0.3f,
        2.025f}, {-2.5f, -0.3f, 2.25f}, {-2.5f, 0, 2.25f}, {-2.7f, 0,
        2.025f}, {-2.7f, -0.3f, 2.025f}, {-3, -0.3f, 2.25f}, {-3, 0,
        2.25f}, {-2.7f, 0, 1.8f}, {-2.7f, -0.3f, 1.8f}, {-3, -0.3f, 1.8f},
        {-3, 0, 1.8f}, {-2.7f, 0, 1.575f}, {-2.7f, -0.3f, 1.575f}, {-3,
        -0.3f, 1.35f}, {-3, 0, 1.35f}, {-2.5f, 0, 1.125f}, {-2.5f, -0.3f,
        1.125f}, {-2.65f, -0.3f, 0.9375f}, {-2.65f, 0, 0.9375f}, {-2,
        -0.3f, 0.9f}, {-1.9f, -0.3f, 0.6f}, {-1.9f, 0, 0.6f}, {1.7f, 0,
        1.425f}, {1.7f, -0.66f, 1.425f}, {1.7f, -0.66f, 0.6f}, {1.7f, 0,
        0.6f}, {2.6f, 0, 1.425f}, {2.6f, -0.66f, 1.425f}, {3.1f, -0.66f,
        0.825f}, {3.1f, 0, 0.825f}, {2.3f, 0, 2.1f}, {2.3f, -0.25f, 2.1f},
        {2.4f, -0.25f, 2.025f}, {2.4f, 0, 2.025f}, {2.7f, 0, 2.4f}, {2.7f,
        -0.25f, 2.4f}, {3.3f, -0.25f, 2.4f}, {3.3f, 0, 2.4f}, {2.8f, 0,
        2.475f}, {2.8f, -0.25f, 2.475f}, {3.525f, -0.25f, 2.49375f},
        {3.525f, 0, 2.49375f}, {2.9f, 0, 2.475f}, {2.9f, -0.15f, 2.475f},
        {3.45f, -0.15f, 2.5125f}, {3.45f, 0, 2.5125f}, {2.8f, 0, 2.4f},
        {2.8f, -0.15f, 2.4f}, {3.2f, -0.15f, 2.4f}, {3.2f, 0, 2.4f}, {0, 0,
        3.15f}, {0.8f, 0, 3.15f}, {0.8f, -0.45f, 3.15f}, {0.45f, -0.8f,
        3.15f}, {0, -0.8f, 3.15f}, {0, 0, 2.85f}, {1.4f, 0, 2.4f}, {1.4f,
        -0.784f, 2.4f}, {0.784f, -1.4f, 2.4f}, {0, -1.4f, 2.4f}, {0.4f, 0,
        2.55f}, {0.4f, -0.224f, 2.55f}, {0.224f, -0.4f, 2.55f}, {0, -0.4f,
        2.55f}, {1.3f, 0, 2.55f}, {1.3f, -0.728f, 2.55f}, {0.728f, -1.3f,
        2.55f}, {0, -1.3f, 2.55f}, {1.3f, 0, 2.4f}, {1.3f, -0.728f, 2.4f},
        {0.728f, -1.3f, 2.4f}, {0, -1.3f, 2.4f}, {0, 0, 0}, {1.425f,
        -0.798f, 0}, {1.5f, 0, 0.075f}, {1.425f, 0, 0}, {0.798f, -1.425f,
        0}, {0, -1.5f, 0.075f}, {0, -1.425f, 0}, {1.5f, -0.84f, 0.075f},
        {0.84f, -1.5f, 0.075f}
    };

      public static float[] tex =
    {
      0, 0,
      1, 0,
      0, 1,
      1, 1
    };

      private static void DrawTeapot(int grid, float scale, MeshMode2 type)
      {
        float[] p = new float[48], q = new float[48], r = new float[48], s = new float[48];
        int i, j, k, l;

        GL.PushAttrib(AttribMask.EnableBit | AttribMask.EvalBit);
        GL.Enable(EnableCap.AutoNormal);
        GL.Enable(EnableCap.Normalize);
        GL.Enable(EnableCap.Map2Vertex3);
        GL.Enable(EnableCap.Map2TextureCoord2);

        // time for the math portion: remember augmented matrices?  here's where you use them!
        // prep the matrix for the data to be loaded
        GL.PushMatrix();
        // rotate the view
        GL.Rotate(270.0f, 1.0f, 0.0f, 0.0f);
        // set the size of the data
        GL.Scale(0.5f * scale, 0.5f * scale, 0.5f * scale);
        // move the data via X/Y/Z coordinates
        GL.Translate(0.0f, 0.0f, -1.5f);
        for (i = 0; i < 10; i++)
        {
          for (j = 0; j < 4; j++)
          {
            for (k = 0; k < 4; k++)
            {
              for (l = 0; l < 3; l++)
              {
                p[j * 12 + k * 3 + l] = cpdata[patchdata[i, j * 4 + k], l];
                q[j * 12 + k * 3 + l] = cpdata[patchdata[i, j * 4 + (3 - k)], l];
                if (l == 1)
                  q[j * 12 + k * 3 + l] *= -1.0f;
                if (i < 6)
                {
                  r[j * 12 + k * 3 + l] = cpdata[patchdata[i, j * 4 + (3 - k)], l];
                  if (l == 0)
                    r[j * 12 + k * 3 + l] *= -1.0f;
                  s[j * 12 + k * 3 + l] = cpdata[patchdata[i, j * 4 + k], l];
                  if (l == 0)
                    s[j * 12 + k * 3 + l] *= -1.0f;
                  if (l == 1)
                    s[j * 12 + k * 3 + l] *= -1.0f;
                }
              }
            }
          }

          // high level math for the texture coordinates
          GL.Map2(MapTarget.Map2TextureCoord2, 0f, 1f, 2, 2, 0f, 1f, 4, 2, tex);
          // high level math for the vertices
          GL.Map2(MapTarget.Map2Vertex3, 0f, 1f, 3, 4, 0f, 1f, 12, 4, p);
          // high level math for a 2 dimensional map
          GL.MapGrid2(grid, 0.0, 1.0, grid, 0.0, 1.0);
          // high level math to do the evaluation of the grids
          GL.EvalMesh2(type, 0, grid, 0, grid);
          // high level math for the vertices
          GL.Map2(MapTarget.Map2Vertex3, 0, 1, 3, 4, 0, 1, 12, 4, q);
          // high level math to do the evaluation of the grids
          GL.EvalMesh2(type, 0, grid, 0, grid);
          if (i < 6)
          {
            // high level math for the vertices
            GL.Map2(MapTarget.Map2Vertex3, 0, 1, 3, 4, 0, 1, 12, 4, r);
            // high level math to do the evaluation of the grids
            GL.EvalMesh2(type, 0, grid, 0, grid);
            // high level math for the vertices
            GL.Map2(MapTarget.Map2Vertex3, 0, 1, 3, 4, 0, 1, 12, 4, s);
            // high level math to do the evaluation of the grids
            GL.EvalMesh2(type, 0, grid, 0, grid);
          }
        }

        // release the manipulated data from the matrix
        GL.PopMatrix();
        // release the manipulated data from the matrix attributes
        GL.PopAttrib();
      }

      public static void DrawSolidTeapot(float scale)
      {
        DrawTeapot(14, scale, MeshMode2.Fill);
      }

      public static void DrawWireTeapot(float scale)
      {
        DrawTeapot(10, scale, MeshMode2.Line);
      }

      public static void DrawPointTeapot(float scale)
      {
        DrawTeapot(10, scale, MeshMode2.Point);
      }

    }

    private static int teapotList;

    [STAThread]
    public static void Main()
    {
      using (var game = new GameWindow())
      {
        game.Load += (sender, e) =>
        {
          // setup settings, load textures, sounds
          game.VSync = VSyncMode.On;

          // easier to create float arrays in advance
          float[] ambient = { 0.0f, 0.0f, 0.0f, 1.0f };
          float[] diffuse = { 1.0f, 1.0f, 1.0f, 1.0f };
          float[] specular = { 1.0f, 1.0f, 1.0f, 1.0f };
          float[] position = { 0.0f, 3.0f, 3.0f, 0.0f };
          float[] lmodel_ambient = { 0.2f, 0.2f, 0.2f, 1.0f };
          float[] local_view = { 0.0f };

          // setup your light source(s)
          GL.Light(LightName.Light0, LightParameter.Ambient, ambient);
          GL.Light(LightName.Light0, LightParameter.Diffuse, diffuse);
          GL.Light(LightName.Light0, LightParameter.Position, position);
          GL.LightModel(LightModelParameter.LightModelAmbient, lmodel_ambient);
          GL.LightModel(LightModelParameter.LightModelLocalViewer, local_view);

          GL.FrontFace(FrontFaceDirection.Cw);
          GL.Enable(EnableCap.Lighting);
          GL.Enable(EnableCap.Light0);
          GL.Enable(EnableCap.AutoNormal);
          GL.Enable(EnableCap.Normalize);
          GL.Enable(EnableCap.DepthTest);

          GL.NewList(GL.GenLists(1), ListMode.Compile);

          // teapot time
          Teapot.DrawSolidTeapot(1.0f);
          GL.EndList();
        };

        game.Resize += (sender, e) =>
        {
          // setup the viewer for your image(s)
          GL.Viewport(0, 0, game.Width, game.Height);
        };

        game.UpdateFrame += (sender, e) =>
        {
          // add game logic, input handling
          if (game.Keyboard[Key.Escape])
          {
            game.Exit();
          }
        };

        game.RenderFrame += (sender, e) =>
        {
          // step 1: clear the buffer
          GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

          // step 2: render the teapot as you see fit
          // press S for a solid teapot
          if (game.Keyboard[Key.S])
            Teapot.DrawSolidTeapot(0.5f);
          // press W for a wire frame teapot
          else if (game.Keyboard[Key.W])
            Teapot.DrawWireTeapot(0.5f);
          // press P for a point frame teapot
          else if (game.Keyboard[Key.P])
            Teapot.DrawPointTeapot(0.5f);

          // step 3: force the execution of your GL code
          GL.Flush();

          // step 4: swap the buffers to display your code
          game.SwapBuffers();
        };

        // Run the game at 60 updates per second
        game.Run(60.0);
      }
    }
  }
}

There's decent documentation within the above source code, the output below:

Solid:

Wire:

Pixel:
















Now for some real fun: code some buttons so when you hit certain keys you change the viewing angle so you can rotate the teapot!  Heck, figure out how to change the colors of the teapot on the fly so it looks like a magical teapot.  Enjoy!

Source(s):

Thursday, April 2, 2015

Web Api Request Validation Made Easy

Intro

Validating inputs into your system can be quite a chore. Field X might be a required field, Field Y might need to be email format, Field Z might need to be a number between 1-100. Coding such requirements isn't very difficult, just tedious. Wouldn't it be great if there was something that would lessen the monotony? Yeah, you know where I'm headed...there is such a beast, and we can bask in its magnificence!

Note: I'll be using Visual Studio 2013 Community Edition and Fiddler to do my work.


Sample

For starters, create a new Web Api application. I've created such a solution and named it BlogWebApiValidation. Add a new controller to it named ValidationController.


 Now add a new class to your Models folder named ValidationSampleRequest. It'll have just three properties, so it'll be pretty simple. Here it is:

using System.ComponentModel.DataAnnotations;

namespace BlogWebApiValidation.Models
{
    public class ValidationSampleRequest
    {
        [Required]
        public string RequiredString { get; set; }

        [EmailAddress]
        public string SomeEmail { get; set; }

        [Range(1, 100)]
        public byte SomeNum1To100 { get; set; }
    }
}

Now go back to your ValidationController class. It doesn't need to do much, it just needs a single method named Post that accepts an object of type ValidationSampleRequest. Here's what yours might look like:

using System.Web.Http;
using BlogWebApiValidation.Models;

namespace BlogWebApiValidation.Controllers
{
    public class ValidationController : ApiController
    {
        public IHttpActionResult Post(ValidationSampleRequest request)
        {
            if (ModelState.IsValid)
                return Ok();
            else
                return BadRequest(ModelState);
        }
    }
}


This Post method is pretty bare-bones, as we're just demonstrating model validation. All it does is check the validity of the ModelState (the request), and returns a 200 OK HTTP result if good, and a 400 Bad Request HTTP result if bad. Simple! Go ahead and run the project. You'll get a 403 Forbidden error in your browser but that's OK. Our testing involves something a little more complex than just firing up a browser window. But hey, leave the browser window open :)

Fire up Fiddler and let's play with this sucker. I'll skip some of the explanations and just show you real quick how to use Fiddler to test your Web APIs. There's a lot more to it than what I'll cover, I just want to demonstrate the API for now. Anyways, launch Fiddler. You can install it from the link below if you don't already have it.

First, click on the "File" menu, and click on the "Capture Traffic" menu item. This will tell Fiddler not to capture everything you're doing on the internet. That's too much noise for us to sift through.

Now click on the Composer tab. This brings you to a window where you can create your own requests. Select "POST" as the verb, and type in the URL of your web api controller. You can see mine below, though yours (especially the port) may be slightly different. In the headers field right below the URL you can just copy what I have. In the Request Body field, you can also copy what I have below.

Headers:
User-Agent: Fiddler
Accept: application/json
Content-Type: application/json

Request Body:
{
"RequiredString": null,
"SomeEmail": "not an email",
"SomeNum1To100": 101
}


Now hit the big Execute button. You'll see you now have a single request shown in the left-hand side of the window, and it should have a 400 result. Double-click this response record, then on the right-hand side of the window click on the "Raw" button. If you look down there in the response section it now shows you the raw HTTP response.

2 key points here:
  1. You received 400 Bad Request response. Poifect!
  2. The body of the response contains a JSON object which has details on what precisely went wrong. What good is model validation if the client doesn't know what they did wrong? If you keep scrolling to the right you can see that all 3 fields failed validation.


What's Next?

Validation has a lot more options like regular expressions, you can use nullable types like bool? to make a normally non-nullable field required, it will validate sub-objects in complex requests, credit cards, comparison of 2 properties, you can even create your own custom class validation methods, custom error messages, and much much more.

Fiddler also has a lot more options than what I breezed on through. Play around with it, it's great for testing Web API's.

Resources

Fiddler 
DataAnnotations (more validation options)

Thursday, March 19, 2015

.Net OData Services

Intro

I've talked about Web API in previous articles, and I think my overall opinion is pretty clear: I really like the direction MS has taken with internet-based services. I find Web API to be a big improvement over SOAP services and WCF. They're simpler and more flexible, and I find them to be just plain fun. However there is a more powerful alternative out there that is still quite simple: OData. OData is an "open protocol to allow the creation and consumption of queryable and interoperable RESTful APIs in a simple and standard way." For .Net, OData is supported in Web APIs with just a few minor tweaks to your code. So in essence you get queryable RESTful APIs with very little effort on your part. OK everybody, time to show me your OData face and let's get crackin!




Howdie Doodie

Time to talk specifics. Pretend you have a list of animals. You want a RESTful service that allows the client to query your list of animals by name. OK cool, sounds easy enough. You might create a Web API that has a GET method with a single parameter, name. The user hits your api, maybe with the url /api/animals/timmy, and this would return Timmy the lion (we'll just assume all your animals have unique names). Now what if the client wants to retrieve a list of mammals? You could always create a new GET method in your API that has a single parameter for class and the client would hit /api/animals/mammal, but now you've got 2 conflicting API methods and they each need their own special path. Plus you're making some duplicated code here, as in essence you're still just querying your list of animals for specific animal(s). OData gives you an easier out. Let's create an OData service that allows querying as per the previous desires.

First, fire up Visual Studio. I'm using VS 2013 here. Create a new empty Web API project.


Now add a class to your Models folder. Name the class Animal.

Make your class look like this:

using System.ComponentModel.DataAnnotations;
namespace BlogOData.Models
{
    public class Animal
    {
        [Key]
        public string Name { get; set; }
        public string Type { get; set; }
        public string Class { get; set; }
        public int Height { get; set; }
        public int Weight { get; set; }
    }
}

Note: The Key attribute is merely used to identify which is the unique property of our class that identifies individual instances of an animal. In the real world names aren't unique, but this is a blog not the real world.

Now it's time for our OData controller. Go ahead and add one named Animals to your Controllers directory as per the following screenshots:



You've now got a rather large file named AnimalsController.cs in your Controllers folder. It has a lot of extra actions that we don't need since all we care about is retrieving an animal or list of animals based on criteria specified by the client. Replace the code of your new controller with the following:

using System.Collections.Generic;
using System.Linq;
using System.Web.Http.OData;
using BlogOData.Models;

namespace BlogOData.Controllers
{
    public class AnimalsController : ODataController
    {
        public List<Animal> Animals;

        public AnimalsController()
        {
            Animals = new List<Animal>();
            Animals.Add(new Animal() { Class = "mammal", Type = "lion", Name = "timmy", Height = 64, Weight = 495 });
            Animals.Add(new Animal() { Class = "reptile", Type = "box turtle", Name = "billy", Height = 4, Weight = 2 });
            Animals.Add(new Animal() { Class = "reptile", Type = "leopard gecko", Name = "marzipan", Height = 1, Weight = 1 });
            Animals.Add(new Animal() { Class = "invertebrate", Type = "worm", Name = "willy", Height = 1, Weight = 1 });
            Animals.Add(new Animal() { Class = "mammal", Type = "house cat", Name = "sushi", Height = 1, Weight = 12 });
        }

        [EnableQuery]
        public IQueryable<Animal> Get()
        {
            return Animals.AsQueryable();
        }
    }
}

The first thing that is noteworthy is your class declaration for AnimalsController. We're descending from ODataController. Next in line, our constructor. It's not really all that special, but you can see we're populating a list of animals. Lastly the method Get. This has a few interesting bits:
  1. The EnableQuery attribute. This tells the runtime that we are returning a result from this method that is queryable using OData. 
  2. The return type is IQueryable<Animal>. This lets the result set be queried automatically via the OData backend.
  3. Lastly, we return our list of Animals as a queryable object. 
With this incredibly small amount of code, we've now created an OData controller that lets clients tell the server to return only specific results.

And now is where I tell you there's one more piece left. As things stand at the moment, there is no route to your OData controller, which means clients can't actually call it. Open up your WebApiConfig.cs file in the App_Start folder. Looking at the below code sample, you'll need to add the 3 lines of code underneath the comment "//OData Routes":

using System.Web.Http;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using BlogOData.Models;

namespace BlogOData
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //OData Routes
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Animal>("animals");
            config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

        }
    }
}


These 3 lines tell the runtime that we wish people to access our OData controller via the url /odata/animals (case-sensitive). That's it. Run this little sucker! When your browser first comes up, you'll probably see a 403 forbidden error like the following:


Not to worry though; that's not really the url you want. If you're debugging in IE, go ahead and open up a firefox window. It's easier to demo Web API and OData functionality with than IE. Leave the IE debugging window open though. Navigate to your localhost url plus "/odata/animals". You should now see this:


Cool! This is the JSON response from our OData controller showing the full list of animals. I hope you're now thinking "Geez Peeticus, that's cool! But hey, didn't you say the client could tell the server, via a query of some sort, which animals to return?". Well yes I did, and yes we can. OData has it's own special syntax that we can use for filtering, delivered via the $filter querystring parameter. Let's go ahead and use a basic query now...add this on to the url you already have in FireFox: "?$filter=Name eq 'timmy'" (note these filters are also case-sensitive, as are string values contained therein). Here's what your result looks like:

Try a few more queries. Maybe we want to see all the mammals with "?$filter=Class eq 'mammal'".

Holy poo this is cool! We didn't have to write a bunch of switch statements with dynamic querying, LINQ statements, or anything of the sort. All this filtering is handled automagically!


What's Next?

You have a lot more query options with OData than what I've shown you here today. Play around, see what all else you can do, and check out the OData website for more information. It's powerful stuff. You might also try creating a C# client to consume your OData service. Info on how to do that can be found here.

Resources

OData Home
Create an OData v4 Endpoint Using ASP.Net Web API 2.2

Ninject

Purpose:


Ever read about dependency injection and wonder: Hey, how can I implement that easily into my .Net project yet still not pay a fortune to do it?  Open Source is your friend in this instance.


Download + the install:


It's as simple as going to the source link below and clicking their download icon.  They offer framework dependencies for 3.5 and newer, i'll go with 4.0 for my purposes.  Adding the reference to your program is fairly straight forward like any other reference you've added in the past.

Code:


Lets write some dependency injection code, for my purposes I'll use Bugs and Elmer.  Bugs and Elmer have interesting interactions, lets c#ify a conversation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject;
using Ninject.Modules;

namespace NinjectTutor
{
  interface IVegetable
  {
    void Chomp(string target);
  }

  class Carrot : IVegetable
  {
    public void Chomp(string target)
    {
      Console.WriteLine("{0} What's up doc?", target);
    }
  }

  interface IWeapon
  {
    void Hit(string target);
  }

  class Shotgun : IWeapon
  {
    public void Hit(string target)
    {
      Console.WriteLine("{0} huh huh huh huh", target);
    }
  }

  class Fudd
  {
    readonly IWeapon weapon;
    public Fudd(IWeapon weapon)
    {
      this.weapon = weapon;
    }

    public void Attack(string target)
    {
      this.weapon.Hit(target);
    }
  }

  class Wabbit
  {
    readonly IVegetable veggie;
    public Wabbit(IVegetable veggie)
    {
      this.veggie = veggie;
    }

    public void Harass(string target)
    {
      this.veggie.Chomp(target);
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      Ninject.IKernel kernel = new StandardKernel();
      
      kernel.Bind<IVegetable>().To<Carrot>();
      var bugs = kernel.Get<Wabbit>();
      bugs.Harass("Eh");

      kernel.Bind<IWeapon>().To<Shotgun>();
      var elmer = kernel.Get<Fudd>();
      elmer.Attack("kill da wabbit! kill da wabbit!");

      Console.WriteLine("\nPress Any Key to Exit.");
      Console.ReadKey();
    }

  }

}


and the result:
















Source(s):


I easily burnt an hour trying to do the download through NuGet to do the install of Ninject into VS2013 express.  If anyone can solve it please post below to help others.  My best current guess is user rights related.

Thursday, March 12, 2015

.Net Web API Compression

Intro

Web API projects are great. But hopefully I've already convinced you of that in past blogs :)  What could make them better? Optimization of course! As you can guess by the title, I'm specifically going to talk about compression. Compression has a dual-purpose: it can optimize bandwidth, and as a result on many devices it optimizes speed as well from the user's point of view. Out of the box, your Web API's don't accept compressed requests and won't send back compressed responses. Lazy API! But we've got an easy way to make this happen, so read on fellow optimizers!


Example

First, let's create a Web API project in C#. We'll go without web optimization for now just so you can see the difference. Fire up Visual Studio and create a new project. Make it a c# web project.



Make it a empty project and give it Web API and Web Forms capabilities:

 Now give your site a new web API controller. Name it TestController. 






Your Web API doesn't need much in it, just set your code to this:

using System.Net.Http;
using System.Web.Http;

namespace BlogWebApiCompress.Controllers
{
    public class TestController : ApiController
    {
        public HttpResponseMessage Get(string id)
        {
            var result = new List();
            for (int i = 0; i < 10; i++)
                result.Add(id);
            return Request.CreateResponse(result);
        }
    }
}


If you run your web api by hitting your base url plus "/api/test/hi", the web api will return back the list of strings string containing "hi" (10 times) to you. Not much to that. Now let's pretend you sent up a 100 page pamphlet worth of text. You'd have not only a large request, you'd have a very large response as well. Compression can lessen the burden on your systems.

How do we get compression? It turns out there's already a NuGet package for that. NuGet kind of reminds me when iPhones were still pretty new and people kept saying "there's an app for that". Well with Visual Studio and NuGet, "there's a package for that". The one we want is named Microsoft.AspNet.WebApi.MessageHandlers.Compression. Good luck memorizing that. I'll assume you have some familiarity with NuGet by now, but if not drop me a line in the comments below. Fire up the package manager and install the above package.

Now open up the file App_Start/WebApiConfig.cs. At the end of your Register() method, copy in this line of code:

GlobalConfiguration.Configuration.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));

You may also have to add "using"s for these:

using Microsoft.AspNet.WebApi.MessageHandlers.Compression;
using Microsoft.AspNet.WebApi.MessageHandlers.Compression.Compressors;


Believe it or not, that's all you have to do on the server! Let's do another test of our Web Api using FireFox to see the compression in action. This time I'll put a much longer string into the request:



Notice how FireFox sent up the request header "Accept-Encoding: gzip, deflate" and the server sent back down gzip-encoded content? Sweet! That's all there is to it.



What's Next?

  • Go to the website of the NuGet package and see how to:
    • Only compress requests and responses that are above a certain size threshold, and
    • Write client-side code that tells the server you can accept a compressed response (hint, most browsers do this for you already if you are using JavaScript, but for C# clients you have a small amount of extra coding to do).


Resources

 Microsoft.AspNet.WebApi.MessageHandlers.Compression

Wednesday, February 18, 2015

Dictionary

Intro:

So you like hashsets and want to see some other cool datatypes out there that can manipulate data in cool and efficient ways?  Have no fear, another option is the Dictionary type!  With this data type you get Key/Value pairing storage along quick searching and data manipulation.  Think HashTable but more generically typed so you can pass an Object type versus having to pass a defined type (int/string/etc...).

But enough about defining the Dictionary type, lets write some code!

Coding:

For this adventure I'm going to borrow some data from Bobby's Removing Duplicate Data post (go read it if you haven't already, great stuff).  Adding data is similar to what you'd do for a List (yes i used one in this sample).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionarySample
{
  class Program
  {
    static void Main(string[] args)
    {
      //step 1: create!
      Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
      myDictionary.Add("Daniel",new List<string> { "Slingblade","1001101111","Troll" });
      myDictionary.Add("Bob", new List<string> { "UpandDown","4242424242","Troll" });
      myDictionary.Add("Dan", new List<string> { "TheMan", "ffffffffff", "Troll" });
      myDictionary.Add("Peter", new List<string> { "PumpkinEater", "0110010000", "Lesser-Diety" });
      //step 2: test
      Console.WriteLine("does myDictionary.ContainsKey(chode)? : " + myDictionary.ContainsKey("chode").ToString() + " ");
      Console.WriteLine("does myDictionary.ContainsKey(Peter)? : " + myDictionary.ContainsKey("Peter").ToString() + " ");
      Console.WriteLine("does myDictionary.ContainsKey(peter)? : " + myDictionary.ContainsKey("peter").ToString() + " ");
      //step 3: write out the data
      foreach (var pair in myDictionary)
      {
        Console.Write(pair.Key + " ");
        foreach (string value in pair.Value)
          Console.Write(value + " ");
        Console.WriteLine();
      }
      Console.WriteLine("\nPress Any Key to Exit.");
      Console.ReadKey();
    }
  }
}

And the output:














Step 1 is a fairly easy concept, go create a new Dictionary with whatever datatypes you wish to use.  As they are Key/Value pairs you'll have to have two data types passed in, this is where Bobby's blog data comes into play.  Step 2 I'm doing a little bit of testing to see if Keys exist within my Dictionary, Notice the case sensitivity involved with the Peter/peter test results.  Step 3 is just displaying the data from the Key/Pair values in the Dictionary.

Source:

Microsoft: Dictionary

Thursday, December 11, 2014

Data.Gov: Public Government Data API's


Intro

Believe it or not, there are actually a few free things out there. Freedom may cost you $1.05, but there are tons of freely available public APIs. Some are corporate APIs for retrieving information on weather, traffic and other useful things. You can probably find plenty such APIs with a small amount of Google-fu. Some free public APIs are made available by our government. You can retrieve data on economics, oceanography, demographics,utility rates, and more.


The API I Want to Use

We have to start somewhere, and I've picked an API that gives information on alternative fuel stations. Go ahead and dig around on this site for a minute then come back. This API includes information on fueling stations that use alternative fuels such as hydrogen, natural gas, ethanol and more. I don't have such a vehicle, but hey it's an interesting topic and I want to play with this API. Feel free to start somewhere else with your own code if you like.

The method I'm most interested in right now is the one that lists all locations which match specified query parameters. I could picture this information being useful for a person who wants to find the alternative fuel stations near their home or work so they can plan their daily commute.

This method has a large number of request parameters that you can supply on the querystring. It also allows you to specify whether you wish to receive the results as xml or json. Either way, the request is a simple HTTP GET with a specific URL and chosen querystring parameters, and you parse out the response with code. For example, let's say I want to retrieve a list of the first 5 alternative fuel stations in zip code 75006 that have E85 ethanol gasoline or electric refueling. For this API I would use the url: http://developer.nrel.gov/api/alt-fuel-stations/v1.json?api_key=DEMO_KEY&fuel_type=E85,ELEC&zip=75006&limit=5. The first part, "http://developer.nrel.gov/api/alt-fuel-stations/v1", is the base url of the service. the next part, ".json" tells the service that I want my results in JSON format. other possible values are ".xml" and ".csv" for this API. Next up, "api_key=DEMO_KEY". This is how we authenticate with the API. In our case we're just going to use their demo key rather than creating an API key on the website. Now we get to the first filter of our querystring, "fuel_type=E85,ELEC". This tells the API that we want to return a list of stations that are E85 Ethanol or electric refuel/recharge capable. Next up is the zip code, and the last querystring chunk, "limit=5", tells the API we want only the first 5 results. Paste this sucker into your browser and see what you GET (ha, internet pun!). You should see something like this, except mine's formatted nicer:

{
   "station_locator_url":"http://www.afdc.energy.gov/afdc/locator/stations/",
   "total_results":2,
   "station_counts":{
      "total":8,
      "fuels":{
         "E85":{
            "total":0
         },
         "ELEC":{
            "total":8,
            "stations":{
               "total":2
            }
         },
         "HY":{
            "total":0
         },
         "LNG":{
            "total":0
         },
         "BD":{
            "total":0
         },
         "CNG":{
            "total":0
         },
         "LPG":{
            "total":0
         }
      }
   },
   "fuel_stations":[
      {
         "access_days_time":"MON: 24 hours | TUE: 24 hours | WED: 24 hours | THU: 24 hours | FRI: 24 hours | SAT: 24 hours | SUN: 24 hours",
         "cards_accepted":null,
         "date_last_confirmed":"2014-12-11",
         "expected_date":null,
         "fuel_type_code":"ELEC",
         "id":45129,
         "groups_with_access_code":"Private",
         "open_date":null,
         "owner_type_code":null,
         "status_code":"E",
         "station_name":"Carrier Enterprise HQ",
         "station_phone":"888-998-2546",
         "updated_at":"2014-12-11T08:09:02Z",
         "geocode_status":"GPS",
         "latitude":32.933474,
         "longitude":-96.92574,
         "city":"Carrollton",
         "intersection_directions":null,
         "plus4":null,
         "state":"TX",
         "street_address":"2000 Luna Rd",
         "zip":"75006",
         "bd_blends":null,
         "e85_blender_pump":null,
         "ev_connector_types":[
            "J1772"
         ],
         "ev_dc_fast_num":null,
         "ev_level1_evse_num":null,
         "ev_level2_evse_num":4,
         "ev_network":"Blink Network",
         "ev_network_web":"http://www.blinknetwork.com/",
         "ev_other_evse":null,
         "hy_status_link":null,
         "lpg_primary":null,
         "ng_fill_type_code":null,
         "ng_psi":null,
         "ng_vehicle_class":null,
         "ev_network_ids":{
            "station":[
               "51671"
            ],
            "posts":[
               "20199",
               "19577",
               "11721",
               "9055"
            ]
         }
      },
      {
         "access_days_time":null,
         "cards_accepted":null,
         "date_last_confirmed":"2014-04-04",
         "expected_date":null,
         "fuel_type_code":"ELEC",
         "id":46370,
         "groups_with_access_code":"Private",
         "open_date":"2011-08-13",
         "owner_type_code":"P",
         "status_code":"E",
         "station_name":"General Electric - Dallas Office",
         "station_phone":null,
         "updated_at":"2014-04-04T19:00:52Z",
         "geocode_status":"GPS",
         "latitude":32.9838,
         "longitude":-96.845317,
         "city":"Carrollton",
         "intersection_directions":null,
         "plus4":null,
         "state":"TX",
         "street_address":"2508 Highlander Way",
         "zip":"75006",
         "bd_blends":null,
         "e85_blender_pump":null,
         "ev_connector_types":[
            "J1772"
         ],
         "ev_dc_fast_num":null,
         "ev_level1_evse_num":null,
         "ev_level2_evse_num":4,
         "ev_network":null,
         "ev_network_web":null,
         "ev_other_evse":null,
         "hy_status_link":null,
         "lpg_primary":null,
         "ng_fill_type_code":null,
         "ng_psi":null,
         "ng_vehicle_class":null
      }
   ]
}


I'll just summarize the results rather than detailing all of it: we found 2 stations that match our criteria, both of which are electric recharging stations. We also got their address, which is kinda nifty and we'll use that in a few minutes.


Code it Like It's Hot

This wouldn't be a very good coder's blog if I didn't code something, so let's call the API. Create yourself a new web project in Visual Studio. I chose an empty WebForms project, and it will be easier for you to follow along if you do the same. Now add a default page to your site, named "Default". Drop a button on there and give it the same properties as the button you see in my code below:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BlogPublicApi.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Public API Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnExecuteApi" runat="server" Text="Execute API" OnClick="btnExecuteApi_Click" />
    </div>
    </form>
</body>
</html>



Now go to the code behind of your page. The first thing you'll want to do is install the Microsoft Web API Client Libraries. It's a NuGet package. You can find it by searching for "Microsoft.AspNet.WebApi.Client" within the NuGet package manager. After you've added that to your solution/site, copy the code from my button click event into your own:

using System;
using System.Net.Http;


namespace BlogPublicApi
{
    public partial class Default : System.Web.UI.Page
    {
        protected void btnExecuteApi_Click(object sender, EventArgs e)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://developer.nrel.gov/");
                var response = client.GetAsync("api/alt-fuel-stations/v1.json?api_key=DEMO_KEY&fuel_type=E85,ELEC&zip=75006&limit=5").Result;
                if (response.IsSuccessStatusCode)
                {
                    dynamic stationResponseData = response.Content.ReadAsAsync<Object>().Result;
                    Response.Write("Total Results: " + stationResponseData.total_results + "<br />");
                    foreach (dynamic station in stationResponseData.fuel_stations)
                    {
                        Response.Write(String.Format("<a target='_blank' href='https://www.google.com/maps/place/{0},+{1},+{2}+{3}'>{4}</a>", 
                            station.street_address, station.city, station.state, station.zip, station.station_name));
                        Response.Write("<br />");
                    }
                    Response.Write("Raw Result Object: <div>" + stationResponseData + "</div>");
                }
            }

        }
    }
}


The magic starts with the using statement within btnExecuteApi_Click. This is where we create our http client object. The next line of code we set the base address, and then after that we get our response. Assuming the request was successful, we then pull out the json from the response as a dynamic object so that we can access its properties. We write out the total # of results, then loop through the individual fuel stations to create a link. Then for a little extra fun, we link to the station on Google maps. Try plugging in your own zip code and give the code a whirl! It's pretty neat to see the results on a map.

Here's a screenshot of the results so you can visualize what we've done:



What's Next?

There are lots of other free, public APIs out there. Look around, and see what you can make with all the free data. Maybe you'll end up with a great idea for an app for your phone.


References

APIs | Data.gov
Alternative Fuel Stations API
All Stations API | Alternative Fuel Stations
JSON Formatter & Validator 
Calling a Web API From a .Net Client