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

Creating AutoComplete Drop Down List using MVC Razor and Jquery

So I decided to get fancy with an old app today and put in some auto complete text boxes.  As usual I am using MVC and C# to do this along with JQuery.  The general idea is your view (html) is going to have a text box your value goes in.  Using Jquery.UI, you can call the autocomplete function on the textbox which does the magic for you.  Of course you need to create a server side json service to feed the autocomplete function's ajax request, but that's easy in MVC, lets take a look.
There are only really 3 parts of this functionality other than the includes of JQuery and JQuery.UI.  

The first is the textbox you want populated.  In this case I was making a vendor auto-complete drop down list and I wanted my form to be bound to it so I can take advantage of all the MVC goodness and not have to search for values later.  What I did was bind my SearchVendorId to a hidden field so when the page posts back later, I will get it.  The second line is the text box itself.  Nothing to fancy yet.
@Html.HiddenFor(model => model.SearchVendorId)
<input type="text" id="vendorsearch" placeholder="Search For Vendor" />
Next, I create the JQuery function that will turn that ordinary textbox into an awesome autocomplete box.  I actually split this in two pieces, the first is function that runs on the change event of the text box so I can clear the stored hidden value to 0 if the user changes it after the select and I change how the text box looks to let the user know it is a valid vendor or not using CSS.  The actual autocomplete function on the textbox first takes in the ajax call to make, and the success piece stores the results of label and value for the autocomplete function's inner implementation to render to the user.  Simple really.  All we have to do now is create that service.

$("#vendorsearch").change(function () {
            $('#SearchVendorId').val(0);
            if ($('#vendorsearch').val() != "") {
                $('#vendorsearch').addClass("errorTextBox");
                $('#vendorsearch').removeClass("successTextBox");
            }
            else {
                $('#vendorsearch').removeClass("successTextBox");
                $('#vendorsearch').removeClass("errorTextBox");
            }
        });
       $('#vendorsearch').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("GetVendors")',
                data: { term: request.term },
                dataType: 'json',
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataFilter: function(data) { return data; },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.label,
                            value: item.id
                        }
                    }));
                },
            })
        }
Finally, I create the JSON service that my JQuery calls.  Its a simple JsonResult function on my controller that takes in a term and does a quick query using Linq to SQL to get my vendor and returns a new object that matches the id, label, value model the autocomplete function looks for.  Slam that back with the Json function and your good to go.  Enjoy!
[HttpGet]
        public JsonResult GetVendors(string term = "")
        {
            var ctx = new PPMRK_VendiscDataDataContext();
            var returner = (from a in ctx.Vendor
                   where a.Name.ToUpper().Contains(term.ToUpper().Trim())
                   select new { id = a.VendorNumber, label = a.Name.Trim(), value = a.Name.Trim() })
                   .Take(20);
            return Json(returner, JsonRequestBehavior.AllowGet);
        }