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);
        }

String Or Binary Data would be truncated, Linq to SQL Entity Framework

So if you use Linq to SQL or the entity framework, no doubt you have run into the "String or Binary Data would be truncated error" at one point or another.  What is happening is simple, you are trying to insert a value into a SQL column that is longer than the column can hold so instead of trying it just fails. 
Usually this isn't a big deal as most systems and tables make it easy to see what you're doing wrong simply looking at the object you're saving.  In large system applications, it gets to be a bit of a chore and not as easy.  You basically need to compare the values on your object to ever filed in SQL until you find the culprit.  This is very manual.  
After fighting with this for half an hour today with no luck, I decided that the software knows what is wrong, we just need to have it tell us, so I wrote the following routine that uses reflection to re curse the object I am saving and tell me what field isn't going to fit.  I simply called it right before my SubmitChanges and it told me exactly what the problem was, I wish I would have done this a while ago.

public static void FindLongStrings(object testObject)
        {
            foreach (System.Reflection.PropertyInfo propInfo in testObject.GetType().GetProperties())
            {
                foreach (System.Data.Linq.Mapping.ColumnAttribute attribute in propInfo.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), true))
                {
                    if (attribute.DbType.ToLower().Contains("varchar"))
                    {
                        string dbType = attribute.DbType.ToLower();
                        int numberStartIndex = dbType.IndexOf("varchar(") + 8;
                        int numberEndIndex = dbType.IndexOf(")", numberStartIndex);
                        string lengthString = dbType.Substring(numberStartIndex, (numberEndIndex - numberStartIndex));
                        int maxLength = 0;
                        int.TryParse(lengthString, out maxLength);

                        string currentValue = (string)propInfo.GetValue(testObject, null);

                        if (!string.IsNullOrEmpty(currentValue) && currentValue.Length > maxLength)
                            Console.WriteLine(testObject.GetType().Name + "." + propInfo.Name + " " + currentValue + " Max: " + maxLength);
                    }
                }
            }
        }