C# calling REST API's using complext types (objects)

So we have been rolling out Web API's to expose functions to other systems.  This is great, but it isn't like SOAP where you have a WSDL, import it and you can code against it.  You have to do more work than that.  We don't want to be completely blind and just pass xml / json around and let each side figure out what the type looks like, so we should compile our main types to classes and share them between assemblies.  Then when we request or post a product, we can easily just have it as its native type.  Here is how.

If I wanted to post a product to a function, I would do it like this.

var client = new RestClient(Config.GetString("QASpecWebClient", true));
                var request = new RestRequest(Config.GetString("QASpecWebFunction", true), Method.POST);
                request.RequestFormat = DataFormat.Json;
                request.AddBody(product);
                var resp = client.Execute(request);

Notice how we just AddBody the product.  It is a complex type that the service in question uses as well.  Luckily RestSharp takes care of converting it to json to get it there.

If we want to request a product from a function, I would do it like this.

var client = new RestClient("http://localhost:62991/");
var request = new RestRequest("api/productapi/"+id.ToString());
request.RequestFormat = DataFormat.Json;
var resp = client.Execute(request);
var returner = JsonConvert.DeserializeObject<IProduct>(resp.Content);
return returner;

Notice how we just do the same client request setup, don't add a body, and then use the deserialze function template to our type and boom, we have a complex type with no messy parsing.  Enjoy!

 

Oh, don't forget to include Newtonsoft.Json and RestSharp! 

Serialize Object Data to an XML File C#

Saving and loading objects to and from files is one of the first things they teach you when learning to program.  The text file was the original format of choice and it is still used widely today.  Xml was created to be easy to read like text and yet structured to allow relationships to exist in storage.  Occasionally today you still run across the need to store data to something other than a database.  But writing out files from classes means writing functions on your object to read and write it from some sort of file format you must establish. 
While this isn't necessarily hard, it is time consuming and a point of failure and complexity.  I had written a few code generators that could generate a simple reader and writer to xml files given any class, but that was also cumbersome.  What I found out is you can do this inherently with the System.XML library using the XmlSerializer which is very easy to use and saves a lot of time.  You just need to dress your classes.
Here is an example, I have relatively simple set of objects that represent a set of customer statements.
[Serializable]
        public class Statement
        {
            public string AccountNumber { get; set; }
            public int Sort { get; set; }
            public string SubSort { get; set; }
            public decimal SackNumber { get; set; }
            public decimal PackNumber { get; set; }
            public decimal Key { get; set; }
            public string RateLevel { get; set; }
            public string Endorsement { get; set; }
            public string Payload { get; set; }
            public string Stuffer { get; set; }
            public string CustomerNumber { get; set; }
            public string Company { get; set; }
            public string Plan { get; set; }
            public decimal Balance { get; set; }
            public decimal MinimumPayment { get; set; }
            public decimal PastDueAmt { get; set; }
            public string Name { get; set; }
            public string Address1 { get; set; }
            public string Address2 { get; set; }
            public string Address3 { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public string Carrier { get; set; }
            public string Zip { get; set; }
            public DateTime FinalDate { get; set; }
            public string Prefix { get; set; }
            public string Zip2 { get; set; }
            public bool PastDue { get; set; }
            [XmlArray("MessageList"), XmlArrayItem(typeof(Message), ElementName = "Message")]
            public List<Message> Messages { get; set; }
            [XmlArray("DetailList"), XmlArrayItem(typeof(Detail), ElementName = "Detail")]
            public List<Detail> Details { get; set; }
            public Statement()
            {
                Details = new List<Detail>();
                Messages = new List<Message>();
            }
        }
        [Serializable]
        public class Message
        {
            public Message()
            { }
            public decimal LateCharge { get; set; }
            public decimal MinPayMonths { get; set; }
            public decimal MinPayTotal { get; set; }
            public decimal ThreeYearPayment { get; set; }
            public decimal ThreeYearPayTotal { get; set; }
            public decimal YTDFees { get; set; }
            public decimal TYDInterest { get; set; }
            public string MessageString { get; set; }
            public string Last4 { get; set; }
            public decimal EndRate { get; set; }
            public decimal EndFinCharge { get; set; }
            public decimal EndAmtFinanced { get; set; }
            public decimal EndTotalPayout { get; set; }
        }
        [Serializable]
        public class Detail
        {
            public Detail() { }
            public DateTime TransactionDate { get; set; }
            public string TransNumber { get; set; }
            public string TransDescription { get; set; }
            public decimal TransAmount { get; set; }
            public char TransDisputeFlag{ get; set; }
            public string SubPlan { get; set; }

            public string Filler { get; set; }
        }
As you can see I dressed child objects with a xmlroot and serializable.  I also had to make sure all types used in classes and the classes themselves have default constructors that are public and take in to parameters.  And then simply call the save method and boom, you have saved your object to an xml file and can read it with the load method later.  Enjoy!

Enabling CORS on a MVC 5 Application

I recently created a application using Apache Cordova which uses HTML and Javascript / JQuery to create apps that can be built and deployed to many platforms like Android, IOS, and Windows Phone to name a few.  In doing, this, I adopted the model of selecting data from a REST API I exposed via MVC Web API 2.0 from my webserver.  The problem is, you need CORS exposed on the webserver or the Javascript won't except the response from the request for data to prevent cross site scripting.  I could have set up a proxy, but instead I enabled CORS and it wasn't that hard.  It appears there are several ways to do this including many new libraries like System.Web.Html.Cors and System.Web.Cors that are in the nightly builds from Microsoft but not in the deployed visual studios dev environment yet.  I used nuGet to get a few of them and din't have the best luck as my version of System.Web.Http got confused.  
After some more looking I found you could simply put this in your web.config under system.webserver, and it solved the problem, though less gracefully than in code.

<httpProtocol>
  <customHeaders>
	<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
  </customHeaders>
</httpProtocol>
That was it. On my web host, I had to grant full access in the System.Configuration tag as well.

Creating a empty HTML 5 Mobile App with Cordova on Windows 7

I have had the hankering to build an HTML5 mobile application for quite some time and decided today was the day to start. For the extent of this post I just want a blank application building in 2 environments, and I wanted to document the steps I went through to get here.  Here is what I did.

1. Install Node.js.  I used this video to guide me through it.  It had me install git first (I'm using Windows).  After that, I actually installed Node.js by going to their site and downloading the Windows installer.
2. Next I installed Cordova.  by running "C:\>npm install -g cordova" in the Git Bash window.
3. Next, in GitBash, I navigated to my project directory and created a new project running "$ cordova create hello com.example.hello HelloWorld".  
4.  Next, I installed the platforms I wanted to develop on.  You have to go into the hello directory you just created to do this.  At this point I wanted to make an app on Android and Windows for testing it out so I installed the Windows by running "cordova platform add windows" and then "cordova platform add android" which failed because I had to set ANDROID_HOME.  This means I don't have the Andoird SDK Installed (face palm) so I installed it and then the command worked. (note I also had to have java installed and set my JAVA_HOME and JDK_HOME followed by using the Android SDK Manager to install Android 19).
5. So now my projects are generated, so I initiate a build using "cordova build".  Of course boom, I need to install ant.  (set up ant_home and add bin to Path).  Then the build works! (Almost, Windows 7 can't build windows 8 apps :( , but android is happy)
6. Fire this bad boy up in 

Furthermore, if you want to run the application on your device, you must set it up as well.
1. Put your device in debug mode (android) though the developer options menu which is sometimes hidden.  To un-hide it you must click the version number 7 times in the about window.
2. Next you must install the drivers for said device for your OS.  Samsung S5 has different ones. 

Applying tilt shift to a picture.

Tilt–shift photography is the use of camera movements on small- and medium-format cameras, and sometimes specifically refers to the use of tilt for selective focus, often for simulating a miniature scene. Sometimes the term is used when the large depth of field is simulated with digital post-processing; the name may derive from the tilt–shift lens normally required when the effect is produced optically. http://en.wikipedia.org/wiki/Tilt%E2%80%93shift_photography 
I have always liked the effect for several uses.  My favorite might be a large scenery photograph centered on one point to make it look like a small scale.  I also like it in pictures of a subject to make the subject clear with everything else out of focus.  What I found is there are some wonderful filters online to do this.  
http://tiltshiftmaker.com/ is my favorite.  You upload your picture, play with the settings and download it out, for free.  Rather awesome really.  Here is a before and after of my daughter, it was a good picture to begin with (IMO) but I like the result as well.

Before
After