Is Duck Typing a Type System, or a Way of Thinking?

Posted on January 4 2014 10:43 AM by jatten in CodeProject, C#, Javascript   ||   Comments (4)

6114395629_e28c3d1c65Ok, so there is what might be my first-ever "link bait" title. Especially dangerous because I am about to jump into a discussion propagated by some well-known, highly-respected developers against whom my own self-taught, inexperienced knowledge pales. 

I lack the formal schooling or training to join this discussion at the academic level, I simply know what I think I know, and will attempt to toss my opinion out there and see what happens. Actually, that is another first for me . . . I normally recognize that I don't have sufficient "real-world" experience or education to express a strong opinion on such things. Must be early Saturday morning, and I might need more coffee.

Image by Federico Reiven | Some Rights Reserved

Eric Lippert recently posted a typically well-stated article on his blog, Fabulous Adventures in Coding (if you don't already subscribe, now would be a perfect time to do so. His stuff really is THAT GOOD), setting out his thoughts relating Duck Typing to what we in the statically-typed world might recognize as Late Binding. When I woke this morning, I found in my inbox from Phil Haack's blog feed a follow-up in which aptly uses the square filters/round holes issue from the ill-fated Apollo 13 mission as an analogy for Duck Typing.

Both Lippert and Phil Haack appear to be attempting to reconcile the concept of Duck Typing with static type systems, and statically typed programming practices.

Mr. Haack appropriately pulls out some python code, but in my humble opinion only brings the Duck Typing concept partway home, by looking at method overriding in dynamically-typed languages as an example of how Duck Typing might be effectively demonstrated. Most importantly, Phil Haack hits on what, to me, is the deciding gem of the quest to understand:

"I think some of the confusion lies in the fact that duck typing isn't so much a type system as it is a fuzzy approach to treating objects as if they are certain types (or close enough) based on their behavior rather than their declared type. This is a subtle distinction to late binding."

-Phil Haack

Unfortunately (for me, anyway) he then goes on to discuss Duck Typing from a perspective of method overloading. Obviously, Phil Haack knows of which he speaks, and I in no way disagree with what he is saying. However, for myself, the important way to look at Duck Typing is unnecessarily obscured from this perspective.

My question is, are we trying too hard to pigeonhole a simpler concept?

Developers Moving from Statically-Typed to Dynamically-Typed Languages Tend to Over-Complicate Things

As one who has spent most of my time coding in a statically-typed language, I have developed some very basic coding practices and ways of thinking which make the transition to a dynamic approach most challenging. The mushy, malleability of dynamic languages and typing creates a situation which forces us to re-examine what we think we know about type systems, method signatures, and such (at least, if we come from a statically-typed background).

I have spent a lot of time trying to reconcile the dynamic mushiness with my static-typed tendency to create code which, through the action of compile-time type checking, forces the client of my code to "do the right thing."

If we examine some simple, but common design strategies in C# code, we can understand this tendency.

Interfaces Mimic the Notion of Duck-Typing in Statically-Typed Languages

When working in C#, Java, or other statically-typed language paradigm, we become very accustomed to working within the type system, and not only allow it to dictate much of our program structure, but also to assist us in protecting clients of our program from doing the wrong thing.

void TheAnimalSpeaks(Animal animal)
{
    Console.WriteLine(animal.WhatISay);
}

 

Before the code above will even compile, there are three things, at a minimum, which must be satisfied:

  • There must be an Animal class defined, and available to our code
  • The argument passed in to the method TheAnimalSpeaks must be of class Animal
  • The Animal class must itself define a WhatISay Property which resolves to a string

Therefore, we would need, at a minimum, a class Animal, which includes a property WhatISay:

The Animal Class:
class Animal
{
    public string WhatISay { get { return "I Said Something"; } }
}

 

In the C# world, we now know that any client code which wished to call the method TheAnimalSpeaks will be providing an instance of Animal as an argument, and that instance will indeed make available a property named WhatISay. We know this because the client code will not even compile until it does these things.

Also in C#, if we wanted to define different sorts of animals which all share some common behaviors and properties, we could define an IAnimal Interface, which would need to include the property WhatISay, and then modify our method TheAnimalSpeaks to accept an instance of IAnimal as an argument:

The IAnimal Interface in C#:
interface IAnimal
{
    string WhatISay { get; }
}

 

We would then Implement the IAnimal interface on any class we wished to exhibit the property WhatISay:

Classes Implementing the lAnimal Interface in C#:
class Duck : IAnimal
{
    public string WhatISay { get { return "Quack"; } }
}
  
  
class Wolf : IAnimal
{
    public string WhatISay { get { return "Howl"; } }
}
  
  
class Toaster : IAnimal
{
    public string WhatISay { get { return "Hi, I'm not even an animal!"; } }
}

 

Now, we can pass any instance of IAnimal to our method TheAnimalSpeaks and it will work. The compiler will make certain for us that, before we can even run our program, any code which calls this method is passing an argument which implements IAnimal.

static void Main(string[] args)
{
    // We can explicitly declare an instance of IAnimal . . .
    IAnimal theBigBadWolf = new Wolf();
    TheAnimalSpeaks(theBigBadWolf);
  
    //  . . . OR we can explicitly declare an instance 
    // of any type which IMPLEMENTS IAnimal:
    var theFleeingDuck = new Duck();
    TheAnimalSpeaks(theFleeingDuck);
}
  
static void TheAnimalSpeaks(IAnimal animal)
{
    Console.WriteLine(animal.WhatISay);
}

 

In the code above, we can either explicitly declare an instance of type IAnimal, or we can simply instantiate a type which implements the IAnimal interface, and our code will compile and run. We can also see that, so long as a class implements the IAnimal interface, it matters not what the actual class represents (as we can see from the Toaster class, which presumable has little or nothing to do with animals, but can still be passed to the method TheAnimalSpeaks, even though it is not necessarily a good example of domain modelling!).

This is Interface Inheritance 101, Dude. WTF, and Why Do I Care?

As a developer with a lot of background in a statically-typed environment, I found the transition to the dynamic world of JavaScript most challenging. In statically-typed land, we learn to expect that our method signatures, and compiler type checking will protect consumers of our code from passing in the wrong arguments.

In other words, the compiler enforces the contracts established by the method signatures we devise, and we carefully create our domain models to work within these boundaries. We devise  base classes and interfaces to define type expectations at program boundaries, and sleep well at night knowing that client code can't even call into our methods until certain minimum conditions are met.

When we move into a dynamically-typed environment, all that goes out the window.

Dynamically-typed languages do not perform any compile-time type-checking, instead relying on a run-time type system as described by Eric Lippert so effectively. All of the Type definition and interface business we discussed previously has little meaning in such an environment, because none of the advantages afforded by interfaces and the contracts they provide for the compiler are realized.

Duck Typing in Dynamic Languages

In my under-educated understanding, it seems to me common dynamic languages utilize Duck Typing implicitly. If seems to me we go to great lengths to describe a concept which should be fairly simple at its core:

From the Wikipedia definition referred to by Lippert:

"duck typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface."

More Explicitly:

"In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. For example, in a non-duck-typed language, one can create a function that takes an object of type Duck and calls that object's walk and quack methods.

In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error. If the object does have the methods, then they are executed no matter the type of the object, evoking the quotation and hence the name of this form of typing."

I have little background in compiler design, and I accept as axiomatic that under the covers, behind the scenes, there is a whole lot going on under the hood in the implementation of both the C# compiler, and the JavaScript interpreter to make both type systems work properly.

Duck Typing in JavaScript

However, to understand Duck Typing at the useful level of abstraction required to write code, the above definition can be illustrated by contrasting the previous C# examples with some simple JavaScript:

Let's consider some similar code in JavaScript. Note that JS does not have any notion of "classes." I will, however, model up some similar constructs using the JavaScript Module pattern (I am using the Node.js runtime here, such that I can execute the code in the terminal).

First, let's look at a Duck module:

A Duck "Class" (Module) in JavaScript:
var Duck = function() {
  this.whatISay = "Quack";
};
  
module.exports = Duck;

 

Here, we have defined a module which returns a "duck" object. We can do the same for our Wolf "class":

A Wolf "Class" (Module) in Javascript:
var Wolf = function() {
  this.whatISay = "Howl";
};
  
module.exports = Wolf;

 

Now, let's write a method analogous to our C# method TheAnimalSpeaks, and execute it in the terminal using Node.js:

Running the Javascript Equivelent Code:
var Duck = require("./Duck");
var Wolf = require("./Wolf");
  
this.theAnimalSpeaks = function(animal) {
  console.log(animal.whatISay);
};
  
var myDuck = new Duck();
this.theAnimalSpeaks(myDuck);
  
var myWolf = new Wolf();
this.theAnimalSpeaks(myWolf);

 

When we run the code above, the output in the terminal is, predictably:

Terminal Output from theAnimalSpeaks method in JavaScript:
Quack
Howl

 

As we can see, the JavaScript method theAnimalSpeaks cares not one whit what kind of object we pass in to it. In fact, it doesn't really recognize the argument's type until runtime, and even then, only recognizes that it is to look for a property on the passed in argument named whatISay. If it finds such a property, it will attempt to use it. If not, it will return the value undefined. If, instead of a property we were attempting to access a method, the JS runtime would throw a runtime error indicating that no such function exists.

Not Duck Typing in Javascript

Let's make a JavaScript analog of our Toaster class, but let's give it some sort of "toaster-like" method, and not include the whatISay property:

The JavaScript Toaster "Class" (Module):
var Toaster = function() {
  this.startToast = function(minutes) {
    console.log("the toast will cook for " + minutes + " minutes");
  };
};
  
module.exports = Toaster;

 

Here, we have created a "class" with a single method - the startToast() function which accepts an argument specifying how long to cook the toast. If we modify our application code to call into the Toaster module, attempting to both access the whatISay property as well as call the startToast() method, we see in the terminal output that the attempt to access the non-existent property returns undefined, and the call to startToast() executes as expected.

ApplicationCode Consuming the Toaster "Class" (Module):
var Duck = require("./Duck");
var Wolf = require("./Wolf");
var Toaster = require("./Toaster");
  
this.theAnimalSpeaks = function(animal) {
  console.log(animal.whatISay);
  animal.startToast(4);
};
  
var myToaster = new Toaster();
this.theAnimalSpeaks(myToaster);  

 

The terminal output from the above is:

Terminal Output from Application Code Consuming the Toaster "Class" (Module):
undefined
the toast will cook for 4 minutes

 

Obviously, the above is NOT an example of effective Duck Typing, as we are mixing metaphors and domain objects here. In similar fashion, let's try to pass one of our animal objects into the code as it currently exists:

Passing a Duck object into the Modified Application Code:
var Duck = require("./Duck");
var Wolf = require("./Wolf");
var Toaster = require("./Toaster");
this.theAnimalSpeaks = function(animal) {
  console.log(animal.whatISay);
  animal.startToast(4);
};
  
var myDuck = new Duck();
this.theAnimalSpeaks(myDuck);

The code above throws an error informing us that the object has no method startToast().

If it Acts Like a Duck, and Quacks Like a Duck, we can Use it like a Duck

The contrived examples above partially illustrate the power and danger in the Duck Typing concept. We have taken a method which accepts an argument, animal, and attempts to access certain properties and/or methods that it expects to find. There is nothing in the method "signature" beyond the name of the argument to tell us what methods and properties are expected, and the compiler is not going to help us prior to runtime. But if that object presents the expected properties/methods called by the code, all is well.

This is in keeping with the Wikipedia definition:

"duck typing is a style of typing in which an object's methods and properties determine the valid semantics . . ."

Let's look at one more silly example of how Duck Typing might be of use (or danger, as the case may be).

Modifying an Object at Runtime to take a Duck Typed Approach

Returning to our application code, lets ditch the call to the startToast() method, which we used previously only to illustrate how calling a non-existent function throws an error. Let's instead return to the idea that the method theAnimalSpeaks() expects to receive an argument animal, and that it expects the animal to have a property named whatISay which returns a string:

The Original Application Code:
var Duck = require("./Duck");
var Wolf = require("./Wolf");
var Toaster = require("./Toaster");
  
this.theAnimalSpeaks = function(animal) {
  console.log(animal.whatISay);
};
  
var myDuck = new Duck();
this.theAnimalSpeaks(myDuck);
  
var myWolf = new Wolf();
this.theAnimalSpeaks(myWolf);

 

Now, let's take things one more step in the direction of the ridiculous. Let's modify our myToaster object instance at runtime, adding a property whatISay, and then passing it to the method TheAnimalSpeaks:

Modified Application Code using a Duck Typed Approach:
var Duck = require("./Duck");
var Wolf = require("./Wolf");
var Toaster = require("./Toaster");
  
this.theAnimalSpeaks = function(animal) {
  console.log(animal.whatISay);
};
  
var myDuck = new Duck();
this.theAnimalSpeaks(myDuck);
  
var myWolf = new Wolf();
this.theAnimalSpeaks(myWolf);
  
var myToaster = new Toaster();
myToaster.whatISay = "I'm not an animal, but I speak and make toast";
this.theAnimalSpeaks(myToaster);   

 

Terminal output from the example above is:

Terminal Output from Modified Application Code:
Quack
Howl
I'm not an animal, but I speak and ost

 

Here we have, for better or worse, seen the idea of Duck Typing in action. We passed three different objects to our method theAnimalSpeaks. In all three cases, the object looked and acted like what the code was expecting, and so the runtime was able to properly execute the method.

In the case of the toaster, we forced the object to "look and act" like an animal for the purposes of our method call.

As our Wikipedia definition says:

" [. . . a Duck Typed] function would take an object of any type and call that object's walk and quack methods . . . If the object does have the methods, then they are executed no matter the type of the object . . ."

Is Duck Typing a Type System, or a Way of Thinking?

To me, as I try to write better, more idiomatic JavaScript code (I have a long, long way to go here), I find for the moment that learning to "think duck typing" is more valuable than attempting to define it in terms I relate to static type systems.

I am not sure one can say that a Duck Typing represents a Typing System per se. One might instead subscribe to the notion that to varying degrees, certain dynamic languages afford us the ability to employ a Duck Typed approach.

One line in the Wikipedia Entry that is not given the attention I feel it deserves by mssr.'s Lippert or Haack is:

"Duck typing is aided by habitually not testing for the type of arguments in method and function bodies, relying on documentation, clear code and testing to ensure correct use."

This has been my experience when working with JavaScript so far. You want to call a method, you need to figure out what it expects as arguments, and make sure whatever you are passing in has the properties and/or methods expected by the method implementation. And THAT'S IT.

To my mind, JavaScript (as an example) allows us to design a method which accepts an argument of whateverTheHellIWant, and the code will run properly so long as the argument implements the properties and behaviors expected by the method code.

Obviously to me, we want to adhere to some pretty solid design and naming conventions here. Additionally, there is probably no more clear case for effectively documenting an API such that consumers can more easily understand what is expected when calling your code.

In Dynamic Languages, the Interface is Implicit

Another way to approach the idea is to return to our concept of the interface in statically-typed systems. In these cases, and in our C# examples at the beginning of this article, we can see that interfaces in a statically-typed scenario allow us to say "This object looks and acts like a duck" even if it is not.

In a dynamic language, the ceremony associated with compile-time type checking, interface declaration, and such is unneeded. There is no compiler to enforce the type system rules, or to make sure our object implements a particular interface. This affords us an exceptional degree of freedom in designing our application code, and also places on us, the developer, the responsibility for ensuring our code will function correctly.

Final Thoughts

The preceding was inspired by both my own quest to better understand the languages I am using, and by reading two articles by developers I admire, and who know better than me. If anyone thinks I am trying to argue the points they make, please understand I am not. I am merely trying to synthesize what those two luminaries wrote with my own understanding, at the level that works best for me. If it helps anyone else, so much the better.

I am new to the world of Dynamic Languages in general, and JavaScript specifically. I am not a compiler builder, nor do I have any sort of academic training in language design.

Additional Resources and Items of Interest

 

Posted on January 4 2014 10:43 AM by jatten     

Comments (4)

ASP.NET MVC: Show Busy Indicator on Form Submit using JQuery and Ajax

Posted on December 22 2013 05:57 PM by John Atten in CodeProject, C#, ASP.NET MVC, ASP.Net   ||   Comments (6)

ajaxAs we all know, users are impatient. We also know that if we don't tell them our application is "doing something" they tend to do silly things like click the mouse repeatedly, seeking some sign that the requested action is indeed being performed.

For this reason, it is a good idea to throw up some sort of "busy" indicator when a user-initiated action may invoke a long-running process which requires them to wait.

In this article we are going to demonstrate a very basic way to achieve this which will be effective in most cases.

If you are new to ASP.NET MVC, you may want to check out my previous posts on Routing Basics and Route Customization as well. While not critical to understanding what we discuss here, some background on the basics of MVC routing will certainly help in understanding what's going on in places.

Image by Martin Abegglen | Some Rights Reserved

The fully-functioning source code for the example used in this article is available from my Github Repo. You will need to use Nuget Package Restore to pull down all the package goodness so that the project will run. If you are unsure what that means, see Keep Nuget Packages Out of Source Control with Nuget Package Manager Restore.

What the Hell is Ajax?

Ajax is an acronym for Asynchronous JavaScript and XML. Ajax represents a broad range of technologies used to facilitate client-server communication without interfering with the current state of the page.

In the main, we most often use the term when we speak of making an Ajax Request to the server, usually in the context of posting or retrieving data, and updating only a portion of the page, as opposed to completely refreshing a page simply because a small sub-area needs to be updated.

Upon the introduction of the term circa 2005, XML represented what many believed would be the primary data interchange format for this type of client-server transaction. Since then, JavaScript Object Notation (JSON) has become more and more of a standard. While XML is not gone, you are as likely to send and receive JSON in the course of an Ajax request as you are XML.

At present, we often find Ajax used in conjunction with JQuery (more properly, one often uses JQuery to make an Ajax request) when we need to retain the current state of our page while a request is made to the server and then update the portion of the page affected by the information returned from the request.

Adding a Busy indicator to a Page with JQuery and Ajax

The common way to display a busy indicator on a page while we wait for a long-running request to return from the server is to throw up an animated Gif, to let users know something is in fact happening. Equally as often, we need to then remove or hide the animation when the process completes, and refresh the portion of the page affected by our new data.

There really is no good way to do this from the server side in an MVC application – we need to use Ajax. We do this with JavaScript. in this case, we are going to use the popular JQuery library, because it is ubiquitous, it ships with and in integrated into the core MVC project.

Let's take a look at a quick example.

Basic Example – The View

First we will look at a basic view. We've kept it simple here – we will display a couple of data entry fields, and a button to submit the data entered by the user. The essential cshtml code for this is as follows:

A Basic View:
@model JqueryBusyExample.Models.DemoViewModel
@{
    ViewBag.Title = "Home Page";
}
  
<h3>Enter Your Name and Submit:</h3>
  
@using (Html.BeginForm("LongRunningDemoProcess", 
    "Home", FormMethod.Post, 
    new { encType = "multipart/form-data", id="myform", name = "myform" }))
{
    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, 
            new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.LastName, 
            new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
    </div>
    
    <input type="submit" name="operation" id="process" value="process" />
}

 

As we can see, there is nothing unusual here. We use standard Razor syntax to create a form with a couple data entry fields for First and Last names, and a submit button. In the opening of the using statement, The form is wired to a method named LongRunningDemoProcess on our HomeController.

In the form declaration, the syntax is:

Html.BeginForm(<actionName>, <controllerName>, <Http Method Type>, <Html Attributes>)

 

The above basically determines what happens when the form is submitted, and specifies a specific method, and a specific controller as a target for the Http request. It also defines the request method type (GET, POST, PUT, DELETE).

In our example case, we want to send our model data in the POST body. On our controller, the LongRunningDemoProcess method will need to be decorated with the [HttpPost] attribute, and accept the POST body payload as an argument.

Now let's take a look at our Home controller.

Basic Example – The Controller

For our purpose here, I have simply added a method named LongRunningDemoProcess to the stock ASP.NET MVC Home Controller which is part of the default MVC 5 project template:

A Basic Controller with Long-Running Process:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public JsonResult LongRunningDemoProcess(DemoViewModel model)
    {
        Thread.Sleep(1000);
        return Json(model, "json");
    }
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return View();
    }
}

 

In the above, we use Thread.Sleep to mimic a long-running process on the server. You will need to add a reference to the System.Threading namespace in the using statement imports at the top of your file.

As we can see, LongRunningDemoProcess is the target of for our HTTP Post request from the Index view when form submission occurs. We want to use the Json data returned from the request to update our view, and let the user know their submit succeeded.

At the moment, though, things are not all they could be. We can load up our page, type some data into the form, and hit submit. What happens next, though, is that our page freezes up while the long-running process runs, and then our Json data is returned to a new tab in our browser (Chrome) or we are prompted to Save or Open (IE). 

What we WANT to happen is to display a busy indicator, and then somehow indicate to the user that their submission was successful (or something!).

Get a Busy Indicator GIF

One of the more useful little sites I've found recently is AjaxLoad.Info, which presents a handy library of various customizable animated GIFs. You can specify some basic parameters (Size, Type, Foreground Color, etc.) and then download, ready to use.

Go get one, add it to your project in a location which makes sense (I am using ASP.NET MVC 5 project in VS 2013, so I placed mine at the root level of the Content folder).

Next, let's modify our view, and add a div we can show and hide as needed, and which contains our gif:

The View, with Animated GIF and Placeholder for Submission Result

In the highlighted area below, we have added a div element to contain our Gif. While we're at it, we also added another div, to hold the result when our long-running process returns:

Modified View with Animated Gif and Placeholder Div:
@model JqueryBusyExample.Models.DemoViewModel
@{
    ViewBag.Title = "Home Page";
}
  
<h3>Enter Your Name and Submit:</h3>
  
@using (Html.BeginForm("LongRunningDemoProcess", "Home", FormMethod.Post, 
    new { encType = "multipart/form-data", id="myform", name = "myform" }))
{
    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, 
            new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.LastName, 
            new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
    </div>
    
    <input type="submit" name="operation" id="process" value="process" />
}
   
// We want to show this while the server process is running:
<div id="divProcessing">
    <p>Processing, please wait . . . <img src="../../Content/ajax-loader.gif"></p>
</div>
  
// We want to display the result from our submission in here:
<div id="divResult">
</div>

 

Now, in order to tie all this together, we need to add an Ajax request.

Adding the Ajax Request

The easiest way to achieve what we want is to use JavaScript on the client to show our animated gif, and then submit our data to the server. We also want to be able to respond when the Json is returned by the server by updating our page, without refreshing the whole thing.

For our example, I am going to add the JavaScript right on the view. This may or may not make sense in a production application, but we will do it here for simplicity.

I've added the JQuery code below our now-familiar view:

The View, with JQuery Added:
@model JqueryBusyExample.Models.DemoViewModel
@{
    ViewBag.Title = "Home Page";
}
  
<h3>Enter Your Name and Submit:</h3>
  
@using (Html.BeginForm("LongRunningDemoProcess", "Home", FormMethod.Post, 
    new { encType = "multipart/form-data", id="myform", name = "myform" }))
{
    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, 
            new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.LastName, 
            new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
    </div>
    
    <input type="submit" name="operation" id="process" value="process" />
}
    
// We want to show this while the server process is running:
<div id="divProcessing">
    <p>Processing, please wait . . . <img src="../../Content/ajax-loader.gif"></p>
</div>
    
// We want to display the result from our submission in here:
<div id="divResult">
  
</div>
  
@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
  
  <script type="text/javascript">
  
    $(document).ready(function () {
  
      // Hide the "busy" Gif at load:
      $("#divProcessing").hide();
  
      // Attach click handler to the submit button:
      $('#process').click(function () {
          $('#myform').submit();
      });
  
      // Handle the form submit event, and make the Ajax request:
      $("#myform").on("submit", function (event) {
        event.preventDefault();
  
        // Show the "busy" Gif:
        $("#divProcessing").show();
        var url = $(this).attr("action");
        var formData = $(this).serialize();
        $.ajax({
          url: url,
          type: "POST",
          data: formData,
          dataType: "json",
          success: function (resp) {
  
            // Hide the "busy" gif:
            $("#divProcessing").hide();
  
            // Do something useful with the data:
            $("<h3>" + resp.FirstName + " " + resp.LastName + "</h3>").appendTo("#divResult");
          }
        })
      });
    });
  </script>
}

 

In the above, we start with the standard JQuery document.ready function, and hide the div containing our animated Gif.

We then attach the form submit event to the click event of the submit button we defined in our View (Isn't it already attached, you ask? We'll get to why we do this in a moment), and then we handle the form submit event.

Handling the Form Submit Event with an Ajax Request

This is where things get interesting. There are a few things occurring inside this function, in a rather specific order. Let's walk through it. 

First, we want to prevent the default action using (wait for it . . .) the JQuery preventDefault() method when the form submit event occurs, otherwise, form submission will proceed automatically, as before, and any code we place in our handler will not work properly.

Next, we show our animated Gif. Once shown, it will do its thing, giving the user the impression that something  useful is happening.

Finally, we collect what we need from our form in order to submit our Ajax request. First, we grab the Url and stow it in a variable by accessing the form's action attribute using JQuery. The action attribute essentially pulls a Url which matches the route we specified in the form declaration (remember?  ActionMethod, ControllerName, HttpMethodType, etc?).

Next, we serialize the form data ( in this case, our model data) into another variable, again using JQuery.

Once we have collected these things, we can set up our Ajax request by making the property assignments shown. Note that we need to specify the data type as Json, so that when the request returns, JQuery will recognize it as valid Json. Then, we come to the all-important success property.

We have assigned a function here, which will execute when our long-running process returns a response. The resp argument will contain the Json returned from our controller method. In this very simple case, it is merely the data we already submitted. However, it could just as easily be the result of persisting some data in a database on the server. In any case, we know that when this function is called, our remote, long-running task has completed.

That being the case, the first thing we want to do is hide our animated Gif. Next, we push the returned data into the div we set up as a placeholder (after doing a little formatting, of course).

Fairly Simple, but Not Always Obvious

And there you have it. The example we have examined is pretty basic, but gives a good look at how to both display a busy indicator, and how to make Ajax requests from your ASP.NET MVC page.

There is a lot more to learn about Ajax, and it provides a foundation for much of the interactivity found in today's modern websites. I welcome comments and constructive criticism in the comments section below (especially if I got something wrong here . . .)!

You can clone or download the example project from my Github Repo. Note that you will need to use Nuget Package Restore to pull in all the package dependencies. If you don't know what that means, see Keep Nuget Packages Out of Source Control with Nuget Package Manager Restore.

Additional Resources and Items of Interest

 

Posted on December 22 2013 05:57 PM by John Atten     

Comments (6)

C# SMTP Configuration for Outlook.Com SMTP Host

Posted on December 20 2013 09:18 PM by jatten in C#, CodeProject   ||   Comments (0)

3306827131_eff5401a63If you want to send Email programmatically using your Outlook.com or Gmail account as the SMTP host, there are a few things to pay attention to in order to get it all working.

Using the basic System.Net.Mail library, sending email is generally fairly straightforward. However, if you want to send using your Outlook.Com or Gmail account as the SMTP host, you will most likely need to take a few extra steps, if you have two-stage authorization enabled (and you DO have two-stage auth enabled, RIGHT??!!).

Image by JASE Group LLC | Some Rights Reserved

 

SMTP Configuration Example for Outlook.Com SMTP Host

Here is a basic class with SMPT configuration for sending mail using Outlook.Com SMTP:

Basic Mail Configuration Settings for Outlook.Com SMTP:
using System;
  
// You will need to add a reference to this library:
using System.Net.Mail;
  
namespace SmtpMailConnections
{
    public class OutlookDotComMail
    {
        string _sender = "";
        string _password = "";
        public OutlookDotComMail(string sender, string password)
        {
            _sender = sender;
            _password = password;
        }
  
  
        public void SendMail(string recipient, string subject, string message)
        {
            SmtpClient client = new SmtpClient("smtp-mail.outlook.com");
  
            client.Port = 587;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            System.Net.NetworkCredential credentials = 
                new System.Net.NetworkCredential(_sender, _password);
            client.EnableSsl = true;
            client.Credentials = credentials;
  
            try
            {
                var mail = new MailMessage(_sender.Trim(), recipient.Trim());
                mail.Subject = subject;
                mail.Body = message;
                client.Send(mail);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }
    }
}

 

As you can see, we have kept this pretty minimal for the purpose of clarity. We initialize our simple class with a user name (in this case, out Outlook.Com email address) and a password.

Example Usage

We can call into this class to send mail like this (this example is a simple console application):

Sending Mail Using the Mail Sender Class
class Program
{
    static void Main(string[] args)
    {
        string mailUser = "YourAccount@outlook.com";
        string mailUserPwd = "YourPassword";
  
        var sender = new OutlookDotComMail(mailUser, mailUserPwd);
        sender.SendMail("recipient@example.com", "Test Mail", "Hello!");
    }
}

 

If you run the code above, using your own Outlook.Com Email address and password, all should work fine.

Unless you have enabled two-stage authorization on your Outlook.Com account. If you have, you will need to create an application specific password, or the code above will throw an exception when your credentials are refused by the Outlook.Com SMTP server.

Create an App-Specific Password if You Have 2-Stage Auth Enabled

To create an App-Specific Password, log in to your Outlook.com account, and go to Account Settings –> Security Info –> App Passwords:

outlook-com-app-passwords

Click on the Create a new app password link, and voila – you now have a new password for use within your application:

create-new-app-password

Use this as the password in your code, and all should be well:

Use the App Password Instead of Your Outlook.Com Account Password:
class Program
{
    static void Main(string[] args)
    {
        string mailUser = "YourAccount@outlook.com";
        string mailUserPwd = "bnppnnenfmpiixty";
  
        var sender = new OutlookDotComMail(mailUser, mailUserPwd);
        sender.SendMail("recipient@example.com", "Test Mail", "Hello!");
    }
}

 

You can find the Code Samples above at my Github repo.

Additional Resources and Items of Interest

 

Posted on December 20 2013 09:18 PM by jatten     

Comments (0)

About the author

My name is John Atten, and my username on many of my online accounts is xivSolutions. I am Fascinated by all things technology and software development. I work mostly with C#, Java, SQL Server 2012, learning ASP.NET MVC, html 5/CSS/Javascript. I am always looking for new information, and value your feedback (especially where I got something wrong!). You can email me at:

jatten@typecastexception.com

Web Hosting by