Post to MVC Controller using Ajax


A common requirement is to post data from a MVC view using Ajax rather than the built in Html.BeginForm method. If you place a break point in the CreateEmployee function below you will find that the data has been posted as JSON.

View Model

    1 using System;

    2 using System.ComponentModel.DataAnnotations;

    3

    4 namespace PostViaAjaxApp.Models

    5 {

    6     public class EmployeeViewModel

    7     {

    8         public int Id { get; set; }

    9

   10         [Display(Name = “First Name”)]

   11         [Required(ErrorMessage = “First name is required”)]

   12         public string FirstName { get; set; }

   13

   14         [Display(Name = “Surname”)]

   15         [Required(ErrorMessage = “Surname is required”)]

   16         public string Surname { get; set; }

   17

   18         [Display(Name = “Email address”)]

   19         [Required(ErrorMessage = “Email address is required”)]

   20         [EmailAddress(ErrorMessage = “Invalid email address”)]

   21         public string EmailAddress { get; set; }

   22

   23         [Display(Name = “Is Enabled”)]

   24         public bool IsEnabled { get; set; }

   25

   26         [Display(Name = “Date Created”)]

   27         public DateTime Created { get; set; }

   28

   29         [Required]

   30         [Display(Name = “Date Modified”)]

   31         public DateTime Modified { get; set; }

   32

   33     }

   34 }

Controller

    1 using System.Web.Mvc;

    2 using PostViaAjaxApp.Models;

    3

    4 namespace PostViaAjaxApp.Controllers

    5 {

    6     public class HomeController : Controller

    7     {

    8         public ActionResult Index()

    9         {

   10             var model = new EmployeeViewModel();

   11             model.Id = 1;

   12             model.IsEnabled = true;

   13

   14             return View(model);

   15         }

   16

   17         [AllowAnonymous]

   18         [HttpPost]

   19         public ActionResult CreateEmployee(string id, string firstName, string surname, string email, bool isEnabled)

   20         {

   21             return new EmptyResult();

   22         }

   23     }

   24 }

View

    1 @{

    2     ViewBag.Title = “Index”;

    3 }

    4 @using System.Web.Mvc.Html

    5 @model PostViaAjaxApp.Models.EmployeeViewModel

    6 <h2>Index</h2>

    7

    8 @Styles.Render(“~/Content/css”)

    9 @Scripts.Render(“~/bundles/modernizr”)

   10

   11 <script src=”http://code.jquery.com/jquery-1.11.3.js”></script>

   12

   13 <script type=”text/javascript”>

   14

   15     $(function () {

   16         $(“#PostEmployee”).click(function () {

   17

   18             var id = $(“#Id”).val();

   19             var firstName = $(“#FirstName”).val();

   20             var surname = $(“#Surname”).val();

   21             var isEnabled = $(“#IsEnabled”).val();

   22             var email = $(“#EmailAddress”).val();

   23

   24             $.ajax({

   25                 type: “POST”,

   26                 url: @Url.Action(“CreateEmployee”, “Home”),

   27                 timeout: 5000,

   28                 data: {

   29                     id: id,

   30                     firstName: firstName,

   31                     surname: surname,

   32                     email: email,

   33                     isEnabled: isEnabled

   34                 },

   35                 success: function (data) {

   36                 },

   37                 error: function (xhr, ajaxOptions, thrownError) {

   38                 }

   39             });

   40         });

   41     });

   42

   43 </script>

   44

   45 @*@using (Html.BeginForm((string)ViewBag.FormAction, “Home”))

   46 {*@

   47     @Html.ValidationSummary(true, “Create employee was unsuccessful. Please correct errors and try again.”)

   48

   49     @Html.HiddenFor(model => model.Id)<fieldset>

   50         <legend>New Employee</legend>

   51         <div class=”employeeRow”>

   52             @Html.LabelFor(m => m.FirstName)

   53             @Html.TextBoxFor(m => m.FirstName)

   54         </div>

   55         <div class=”employeeRow”>

   56             @Html.LabelFor(m => m.Surname)

   57             @Html.TextBoxFor(m => m.Surname)

   58         </div>

   59         <div class=”employeeRow”>

   60             @Html.LabelFor(m => m.EmailAddress)

   61             @Html.TextBoxFor(m => m.EmailAddress)

   62         </div>

   63         <div class=”employeeRow”>

   64             @Html.LabelFor(m => m.IsEnabled)

   65             @Html.CheckBoxFor(m => m.IsEnabled)

   66         </div>

   67         <div class=”employeeRow”>

   68             <input type=”submit” value=”Save” id=”PostEmployee” />

   69         </div>

   70     </fieldset>@*

   71 }*@

   72

   73 @Scripts.Render(“~/bundles/jquery”)

   74

   75

   76

   

No matter how far you have gone on the wrong road, turn back!


I worked with a brilliant team of developers on a project some time ago, with a typically geeky calendar that had sayings by notable computer scientists like Edsger W. Dijkstra that was the subject of discussion in our daily stand-ups from time to time.

I was aware of the proverb, but had never really considered it in a software development context. Sometimes one encounters projects large or small that are failing or have indeed failed, or difficulty in trying to solve a technical  or programming obstacle.

“No matter how far you have gone on the wrong road, turn back – Turkish Proverb”

Managing Complexity with a Trilemma


Managing software projects is not an easy task, unfortunately, due to the pervasiveness of software in the modern world, a common mistake is to think of software engineering as easy. As a consultant for some of the largest companies and high street names in the UK, one sometimes encounters projects that have failed or are failing due to complexity, unrealistic expectations and optimistic budgets.

All too often in board or team meetings, developers and their management guesstimate a task will take two weeks and it ends up taking twice as long because project owners and financiers are never furnished with a trilemma.

455px-Project-triangle_svg

This is one of the most important questions people that manage successful projects ask “fast, cheap and good: choose two?”

The modern car is very complex, and features in the expensive range of the modern utilities we are likely to use, consequently, provides an excellent way to compare how commercially successful businesses manage their complexity on a day to day basis. With this complexity in the car, comes a higher probability that problems will arise, because modern cars are complex, failure to maintain components can lead to exorbitant costs down the line, so car manufacturers have service and maintenance plans for the lifetime of a vehicle. There is an important lesson software development teams and IT managers can learn from car dealerships service departments about managing their own projects, and that is if you choose to drive into your dealership without notice, and request that they address a problem on your vehicle immediately, they will happily do this, but it will cost you substantially more money (twice or even more) – companies all to often have software products that they have paid hundreds of thousands, or millions of pounds for, but are seldom prepared to afford any time to pay for the maintenance of the software, this is a fault, especially when it comes to paying back technical debt.

MINI-Downtown-facility-image-01

If one would like to not incur these charges, then the recommended approach is to phone the car dealerships service department and book your car in well in advance, note that they will check their diary and advise you when they have a slot available, not you specifying when you would like your car in to be looked at.

Fast + Cheap = Work will be shoddy and of a very poor standard
Fast + Good = Expensive
Cheap + Good = When we have the time

All too often people choose fast and cheap, which is one of the biggest mistakes you can make if you are developing software for customers (though it sounds attractive in the boardroom or when making the sale), the reality is that when you give them a “quick and dirty” software product, it will contain bugs and deficiencies, work poorly and crash often, so the customer will complain, it is now far too late to start deliberating about the trilemma, their expectation will always be a high quality product as no-one likes to pay for software with bugs, if you are agreeing to anything else, you are likely to fail.

IT managers also need to take heed when dealing with users of varying organisational and strategic importance that request that their problem gets addressed immediately. If you are the managing director of a company and take your car for a service (you usually can afford to pay for them to collect the car), if you don’t want to pay for this premium service, then you join the queue the same as everyone else (judgement call).

This is the root cause of bottlenecks and reactive (not proactive) problem solving in a lot of companies, if you want an effective IT department, treat all your users the same, your Managing Director or Chief Executive will come to thank you for it in the end, when their business thrives.

Windows Ten Free Upgrade Offer


Windows 8 has come on in leaps and bounds since the 8.1 release, making Windows 8 significantly easier to use. When Windows 8 was released, word was everyone was going to ditch their PC and just use a tablet, so the User Interface (UI) in Windows 8 promoted touch based input. Microsoft appears to have corrected the issue in Windows 10.

Why No Windows 9?

It turns out that there is a lot of code out there that relies on some sloppy coding in the Windows 95-98 timeframe, where instead of checking for the whole year e.g. 95 in 1995 or 98 in 1998, the code checks for the first character StartsWith(“9″) instead of Equals(“1995″), you can find an article here that explains the issue.

Windows Ten

The first thing you will notice is that the start bar in the bottom left hand corner looks a little bit more familiar. They have completely done away with the Windows Modern UI Start Screen in Windows 8

Back

Windows Ten Free Upgrade Offer

If you would like to move to Windows 10 for free, have a look at this post

Great news! We will offer a free upgrade to Windows 10 for qualified new or existing Windows 7, Windows 8.1 and Windows Phone 8.1 devices that upgrade in the first year!  And even better: once a qualified Windows device is upgraded to Windows 10, we will continue to keep it up to date for the supported lifetime of the device, keeping it more secure, and introducing new features and functionality over time – for no additional charge. Sign up with your email today, and we will send you more information about Windows 10 and the upgrade offer in the coming months.      

Website

Link available here.

Microsoft Visual Studio Installer Projects


I was forced to remain using Visual Studio 2010 and not upgrade to Visual Studio 2012 or Visual Studio 2013, because my company has dozens of internally used utility apps that use visual studio installer/setup projects. It just is not worth the effort to migrate to another installer technology.

Surprising, last year Microsoft reversed the decision to remove set-up projects, as politically the focus was on getting developers making Windows Store applications where the end product is submitted to Microsoft to host and manage. I write this post as I still come across developers that are unaware that this functionality has been returned.

You can download the extension package from here that updates Visual Studio 2013 only (not Visual Studio 2012)

Setup

After installing the extension you will see the project template available in Visual Studio 2013 shown below

Installer/Setup project

I am currently evaluating Visual Studio 2015 preview, so one naturally assumed that you would be able to create a new set-up project as the functionality had been returned in the previous version, albeit via an add-in extension, I assumed I could see the project template shown in the image above, but it was not there.

It turns out that Microsoft have changed their mind again, and decided not to include installer/setup project in Visual Studio 2015, article available here.

We’d like to thank you all for your comments on this UserVoice entry. We have been discussing the comments on InstallShield Limited Edition (ISLE) raised here with Flexera and we are currently working with them to address the top issues. At this stage we have no plans to include the former Visual Studio Setup Projects in future product versions but we will continue to work with Flexera and the community to ensure Visual Studio customers’ setup needs will be met with no-cost tooling that supports a broad range of scenarios.

Tony Goodhew, Program Manager, VS Pro.

 This is a very frustrating development, a decision based on political and not technical issues. it just means a whole class of Visual Studio developer simply won’t upgrade.

Gangnam Style music video ‘broke’ YouTube view limit


I read an article on the Gangnam Style music video on the BBC website earlier this week and felt it failed to explain any of the numbers mentioned in any meaningful way.

The article asks,

How do you say 9,223,372,036,854,775,808?

Nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight.

When one starts to learn programming, understanding data types is of fundamental importance, irrespective whether you are using Native Languages like C or C++, Managed Languages like Java or C#, Functional Languages like Haskell or F# or Dynamic Languages like JavaScript, PHP or Python. A variable essentially is what a computer uses to store items usually when it is running. Text (like the one you are reading right now in this article) is usually stored in a String variable, whole numbers tend to be stored in an Int variable (integer).

There is no magic!

I program in C# (pronounced “see sharp”) a lot nowadays and can instantly recognise 2,147,483,647 as Int32.MaxValue. It is this limit that the Gangnam style video reached. Programming wise, Youtube is written in a lot of C, so a quick Wikipedia search for C data types shows that all that’s really changed is that they’ve changed their long signed integer type (At least in the −2147483647, +2147483647 range thus at least 32 bits in size) to a long long signed integer type (At least in the −9223372036854775807, +9223372036854775807 range thus at least 64 bits in size. Specified since the C99 version of the standard). In C#, this is Int64.MaxValue.

The remote server returned an error: (407) Proxy Authentication


Periodically, I find myself writing an N-Tier, SaaS app written in Winforms or WPF for a Bank or Energy firm, that uses proxies.

400px-Proxy_concept_en_svg

In fact, as security becomes a better understood component, providing a standardised environment in the enterprise, the more companies typically use proxy servers.

Every once in a while I come across the dreaded message The remote server returned an error: (407) Proxy Authentication Required. 

There is an article here that explains the issue. Make sure you add this to your app.config between the configuration nodes.

<system.net>

<defaultProxy enabled=true useDefaultCredentials=true>

<proxy autoDetect=True usesystemdefault=True/>

</defaultProxy>

</system.net>

<defaultProxy> Element (Network Settings)

enabled  Specifies whether a web proxy is used. The default value is true.

useDefaultCredentials  Specifies whether the default credentials for this host are used to access the web proxy. The default value is false.

 <proxy> Element (Network Settings)

autoDetect Specifies whether the proxy is automatically detected. The default value is unspecified.

usesystemdefault Specifies whether to use Internet Explorer proxy settings. If set to true, subsequent attributes will override Internet Explorer proxy settings. The default value is unspecified.