Thursday, July 30, 2015

.hasOwnProperty in JavaScript

...does what you'd expect. The following example returns two alerts, the first saying "true" and the second saying "false"

var burningMan = {
   wickerColossusOnFire : "burn baby burn"
};
alert(burningMan.hasOwnProperty("wickerColossusOnFire"));
alert(burningMan.hasOwnProperty("wickerColossusAfterFire"));

 
 

This is another something I learned from Kyle Simpson's book "this & OBJECT PROTOTYPES"

Could not load file or assembly 'Whatever' or one of its dependencies. An attempt was made to load a program with an incorrect format.

This error raised its head for me when I attempted to make a new unit test project and have it test an existing C# class library project in Visual Studio 2015. As it turns out, if you right-click on a project and then go to the "Build" tab there is a place where you may explictly set the project to be x64 in lieu of x86 and the project I was testing had this setting and I had to give it to my unit test project to get around this error. Then when I attempted to test with MSTest by going to: Test > Run > All Tests ...my initial test just would not run. To get it to run I went to: Test > Test Settings > Default Processor Architecture ...and then picked x64.

Deserialize any randomly-shaped JSON object to a dynamic type in C# with JavaScriptSerializer and then pull properties off of it.

JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<dynamic>(reader.ReadToEnd());
bool isVerified = jsonObject["success"];

 
 

This is an example directly from here which is some mostly working code for interfacing with Google reCAPTCHA (reCAPTCHA is a spiffier version of CAPTCHA that is harder for bots to beat and there is a C# library for it). If you want to use this code please note that the line for making a new WebRequest is crafted wrong and there is a better example of how to do so here. The whole thing should look like:

  1. String recaptcha = Request.Form["g-recaptcha-response"];
    string x = "secret=" +
    YOURKEY + "&response=" + recaptcha;
    WebRequest webRequest = WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?" + x);
    webRequest.Method = "GET";
    WebResponse webResponse = webRequest.GetResponse();
    Stream stream = webResponse.GetResponseStream();
    StreamReader reader = new StreamReader(stream);

    The YOURKEY above variable is either a public or private key that one gets from Google, and one will get both. I was only exposed to this in helping a friend with code last night and I only see some of what's going on here.
  2. Next comes the three lines of code at the top of the blog posting. The thing you really want is the isVerified true/false value which will be false if the reCAPTCHA isn't undertaken successfully and true if the user is not a robot.
  3. The next three lines of code do a .Close(); on reader, stream, and webResponse. I guess I would have used a using statement if I wrote this, but of course, I didn't. I had to steal code from someone else who was competent. :P

Wednesday, July 29, 2015

"Rename" is TortoiseSVN for Subversion

If you right-click on a file in the Repository Browser you will see this option in the menu that appears. It does what you might think, retaining commit history.

European Union (EU) laws require you to give EU visitors information about cookies used on your blog. In many cases, these laws also require you to obtain consent.

Really? I just got this notice when I logged into my Blogger account! Supposedly some gunk has been automatically added to my blog to accommodate this. Aren't cookies scary?

Copy a file in Subversion without dropping the history.

With TortoiseSVN installed, right-click on a file under source control and pick "Repo-browser" out of the "TortoiseSVN" menu to bring up the Repository Browser. Right-click in the Repository Browser on a file (the one you want to copy) and pick "Copy to..." next. You will need to give a path to where the file should be copied to in source control. You may want to open another repo-browser and copy the path to the destination folder out of the URL line so you don't fat-finger it. The copied file will have all of the commit history as the file copied from! I suppose one could "move" a file by undertaking these same steps and then deleting the old file.

Use safe navigation operator in C# 6.0 to check to see if something is null in advance of calling a method.

Here we check to see if foo is null before calling .GetBarList() and if it's null we just return a new empty list of Bar as suggested by the null coalescing operator.

return foo?.GetBarList() ?? new List<Bar>();

BAI2 is a flat file format for communicating financial transactions and SAP uses these.

This suggests that the acronym stands for Bank Administration Institute. Each line starts with a single digit number. 1 denotes header/configuration. The lines between line 5 (open) and line 8 (close) are the various records and they will be broken into 6,4 pairs wherein 6 is the invoice and 4 is the payment. You can also have a 6,4,4 thing going on too wherein an invoice is paid down with two payments, etc. If there are enough records, the file has to be broken up into batches. All money is represented as one hundred times its corresponding currency's value in integers as a goofy way to sidestep having decimals. (They'd be commas in Española?) Thirteen dollars and forty-two cents is thus represented by 1342 and 67 yen (the Japanese currency is a zero-decimal currency) would be given as 6700.

Tuesday, July 28, 2015

address line caching in Microsoft Outlook 2010

Well, it's gone when you set up a new profile to a new locale for the Exchange server. You can't just type in the address line to auto-find someone. You have to go fishing in that stuff that "To..." button leads to, right? Wrong! You may just type a name and then click the "Check Names" button at the "Message" tab at the ribbon to find them.

yellow and red screen of death reads "Server Error in '/whatever' Application." followed by "Failed to map the path '/whatever'."

...wherein "whatever" is the name of your IIS application. Just restart IIS to get around this.

mail.office365.com

...is the web mail portal for Office 365. Duh. Lead it with http:// to go there is a browser. Duh.

You have to reinstall DevExpress 15.1.4 overtop of itself to get the legit license information in for a trail you let expire.

When you rerun the installer, pick "Modify" not "Repair" ...and yet, even after I register, I still see my app displaying the error reading: "Your evaluation version EXPIRED - To purchase a license, please visit us online at: www.devexpress.com/purchase.If you've purchased DevExpress Products and need to register your license, please review: www.devexpress.com/Support/Center/KB/p/K18106.aspx." Rats! I even uninstalled DevExpress and reinstalled it. No dice. If you pick "Your Licenses Information" from the "DevExpress" menu in Visual Studio and then click that two-arrows-going-in-a-circle-pointing-at-each-other's-tails refresh icon at the dialog which appears, you may just enter your credentials and skip this painful step if you have not yet let a trial expire.

Monday, July 27, 2015

What's the distinction between CREATE NONCLUSTERED INDEX and CREATE INDEX in T-SQL?

This suggests there is not one. Unless a clustered index is specified, the default for "CREATE INDEX" is to create a nonclustered index. In either of this cases if the word CREATE is immediately followed by UNIQUE then no two keys may be the same.

IBM Rational ClearQuest is CRM/bug tracking tool.

It's as complicated as TFS and you need a fleet of peeps to configure it.

"Web Compiler" and "Bundler & Minifier" are other Visual Studio extensions which do some of the sorts of things Web Essentials does.

Some of the things recently pulled out of Web Essentials such as LESS support and JS minification are in the other two items. Just downloading the .vsix, double-clicking it, and running it successfully installed all three of these for me in Visual Studio 2015.

Values from Web.template.config may be transposed to Web.config upon a build.

This may fill in details such as connection strings. In this paradigm, a Web.Debug.config will have instructions to make this happen upon debugging, and a Web.Release.config will put things back to defaults for the release builds. I don't understand how this stuff works yet.

Addendum 7/28/2015: I had it wrong. Values from Web.Debug.config get married into the template to make the Web.config file. You should not ever edit the template unless you are expanding functionality as opposed to changing canned settings.

Visual Studio 2015 seems to debug in IIS Express by default now instead of Cassini.

You may change the setting for a project to make IIS itself the default. Right-click on a project and pick "Properties" to bring up that funny grey screen full of tabs of settings for the project and then go to the "Web" tab.

Saturday, July 25, 2015

Emacs and vi

Are editors and a lot of Python people use these. I went to a family reunion today and a cousin told me that when he's not programming in R, a statistically programming language, the other language he uses is Python and he prefers to use Emacs to vi whereas vi is the editor I've most heard associated with Python. Emacs is short for editing macros, but some also see the e as sort of standing for extensible, sort of. Both editors date back to the 1970s when remoting into another computer was slow and "expensive" and are optimized to do things with as few keystrokes as possible, hence they are hotkey happy.

Friday, July 24, 2015

some tools to "pretty up" JavaScript alerts

(jAlert is not jConfirm)

Use the JavaScriptSerializer in C# to serialize anonymous types.

This test passes:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
namespace Atty.Core.Tests
{
   [TestClass]
   public class SerializationTest
   {
      [TestMethod]
      public void serialization_works()
      {
         var anonymous = new
         {
            Foo = "Bar",
            Baz = 13,
         };
         JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
         string serialization = javaScriptSerializer.Serialize(anonymous);
         Assert.AreEqual(serialization, "{\"Foo\":\"Bar\",\"Baz\":13}");
      }
   }
}

 
 

I had to reference in the System.Web.Extensions assembly to get the System.Web.Script.Serialization using declaration to work. I really only have used the JavaScriptSerializer to deserialize, but I was curious to see what serialization back the other way would look like so here it is.

 
 

Addendum 1/8/2016: System.Web.Extensions may be found at:

  • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5
  • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0

Thursday, July 23, 2015

Just install Visual Studio 2015 over the release candidate for Visual Studio 2015.

You won't end up with two separate things installed. Problem solved!

Object.defineProperty

Yet another goodie revealed to me by Kyle Simpson's book "this & OBJECT PROTOTYPES" is Object.defineProperty. You may use it to set the writable, configurable, and enumerable settings on a property like so:

var thingy = {};
Object.defineProperty(thingy, "whatever", {
   value: 13,
   writable: true,
   configurable: true,
   enumerable: true
});
alert(thingy.whatever);

 
 

Setting them all to true however gets you nothing in verbosely using the Object.defineProperty as these are all the default states anyways for these settings. writable as false blocks reassignment while enumerable as false is going to hinder you from looping through the property's guts. configurable of false keeps you from changing these settings a second time with the exception of yet being able to flip writable from true to false, that one, one-way change is still accessible for some reason. If writable and configurable are both false the thing at hand is effectively a constant.

to draft, perchance to dream

My first job out of college (1997) was at an architecture firm in Dallas and in theory I was there to provide 3D graphics, but really I mostly just played print boy. Anyways, they were an AutoCAD (CAD being computer-aided drafting) shop and I brought the old DOS version of 3D Studio as a skill with me and learned 3D Studio Max while I was there. (Shapes may be pushed from AutoCAD to either of these and there is incentive to build in AutoCAD first as the mathematical precision of measurements doesn't exist in the other tools.) There was another guy there, an architect fresh out of Texas Tech, who brought MicroStation with him and did some 3D graphics in MicroStation. I have coworker in modern times who used to draft and he said that, yes, MicroStation was first with the 3D, and came with a lot of things like 3D (and also scheduling) backed into its framework (not unlike TFS being an ALM not merely source control) where as you had to drag that in from other places to get AutoCAD to do that stuff as it didn't do it standalone. And yet, MicroStation otherwise has nothing to recommended it per my coworker. It's Mickey Mouse ghetto yo. Revit is apparently now the way to do 3D with AutoCAD. You may build in 3D now and render out both elevations and floorplans from the models minimizing duplicate work, but there is no way to take the old 2D plans from earlier versions of AutoCAD and get them on 3D. Also 3D elevations often have to have variations from the tight tying to floorplans photoshopped into them per my colleague if your shop wants such a thing. Rule of thumb: For every four stories on a building, one guy died during the construction of it.

Tuesday, July 21, 2015

There are no diacritics or other Unicode characters in cardholder names.

This explains that they have to only be comprised of uppercase ASCII characters only and no more than 26 of them.

Sunday, July 19, 2015

aurelia ABCs

I saw Rob Eisenberg speak on his creation, aurelia, on Wednesday night at the Rockstar Developers meetup.com meeting, and, no, that's not Rob Eisenberg pictured, it's Eric McVicker introducing him. Rob was elsewhere and his voice was piped into the room. We looked at his code on the TV pictured and another one just like it. Mr. Eisenberg was part of the team rewriting Angular to make it better and he suggests it needed it given that it uses dirty checking to manage its two-way binding allowing the performance hit that one takes to use two-way binding to balloon horribly as an application scales in size. He didn't like how things went in the rewrite (they're just gonna give up on two-way binding) and thus he just rolled his own solution which has a means of two-binding that doesn't suck. Beyond this benefit there will be support for aurelia. One cannot get a techie from Google on the phone to field questions about AngularJS, but aurelia will be supported by his Durandal team. Rob commented on how comic it was that "million dollar" software is architected around some of the goofy modern-day JS freebie frameworks for which there is no support whatsoever. react.js, like the new Angular to be, will perform fast because it also just doesn't use databinding, but who says databinding is an unsolvable problem. If you want to stick with it aurelia is now the way to go. Alright, we were told that aurelia is easy to install and while I know firsthand that's not true, we were also told that it is going to get easier in a couple of months. I will be patient because after seeing how awesome aurelia is I do want to work with it (instead of learning Angular) and I hope I get the chance. The markup here represents the equivalent of how you might slap an np-app tag on an html element in AngularJS to define the Angular mechanics as to be restrained within the tag. As with Angular, you don't necessarily have to decorate the body tag to make the framework take over everything in your markup, but instead the whole application may just bubble up inside of a div tag too.

<body aurelia-app>
   <script src="jspm_packages/system.js"></script>
   <script src="config.js"></script>
   <script>
      System.import('aurelia-bootstrapper');
   </script>
</body>

 
 

The Script.import line of JavaScript above is of an ES6 module loader API. aurelia is modular, and, like Angular, not AMD modular. It has this other approach for wiring stuff up. A template is going to be brought up into the tag slapped with aurelia-app (an html template enclosed in template tags) and every .html template has a sister .js file which is sort of its code behind to draw an ASP.NET web forms parallel. We are gonna find app.js and app.html by default. The first app.js the audience was shown looked like this:

export class Welcome {
   heading = 'Welcome to the Aurelia Navigation App!';
   firstName = 'John';
   lastName = 'Doe';
   
   get fullName(){
      return '${this.firstName} ${this.lastName}';
   }
   
   submit(){
      alert('Welcome, ${this.fullName}!');
   }
}

 
 

In our first component/app-level component setup we are defining some variables and, yes, we are going to surface these in our template. Just enclosing the variable name in curly braces and placing a dollar sign to the left of the left curly braces does this in the aurelia markup.

<template>
   <section>
      <h2>${heading}</h2>
      
      <form role="form" submit.trigger="submit()">
         <div class="form-group">
            <label for="fn">First Name</label>
            <input type="text" value.bind="firstName" class="form-control" id="fn"...
         </div>
         <div class="form-group">
            <label for="ln">Last Name</label>
            <input type="text" value.bind="lastName" class="form-control" id="ln"...
         </div>
         <div class="form-group">
            <label>Full Name</label>
            <p class="help-block">${fullName}</p>
         </div>
         <button type="submit" class="btn btn-default">Submit</button>
      </form>
   </section>
</template>

 
 

The curly braces thing is an example of one-way data binding. value.bind will sometimes give you two-way data binding. It depends on the situation. If used in an a tag for giving a link, well, there really is no reason for that circumstance to demand two-way binding so one-way binding only is afforded. In an input tag however, value.bind provides two-way data binding allowing you to affect the object slated back in the .js file. In contrast, value.two-way may be alternatively used to always have two-way binding without ambiguity and value.one-way is its dumber brother while the runt of the litter is value.one-time which will not refresh itself even if something changes the .js object hydrating the content. One-way binding will refresh what the user sees if other forces such as two-way data binding acts happening elsewhere change up the underlying data, not so with value.one-way though. An event may be wired up to the DOM and submit.trigger above is an example. It will call the submit function in app.js. If we want app.js to instead be a router allowing us to bring in other modules in lieu of having a one module app, we may do so like this:

export class App {
   configureRouter(config, router){
      config.title = 'Aurelia';
      config.map([
         { route: ['','welcome'], moduleId: './welcome', nav: true, title: 'Welcome' }
      ]);
      
      this.router = router;
   }
}

 
 

Our originally app.js and app.html become "Welcome" instead of "App" to become the first in a series of navigable pages. Above where the app.js starts out with Welcome, as much might be an oversight in Rob Eisenberg's presentation where he got ahead of himself. I'm not sure. I thought I'd leave it be rather than redact it. Eventually, the originally, app.js/app.html became the welcome content. Does the new app.js have an .html page to accommodate the routing? Yes it does and it looks like this:

<template>
   <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
   
   <div class="page-host">
      <router-view></router-view>
   </div>
</template>

 
 

He had some markup for interfacing with the router. Here router.isNavigating allows us to conditionally (when applicable) see a spinner if we are attempting to load another "page" and the repeat.for is going to loop through a collection to show us list items with links and thus build out navigation.

      <i class="fa fa-home"></i>
      <span>${router.title}</span>
      </a>
   </div>
   
   <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
         <li repeat.for="row of router.navigation" class="${row.isActive ? 'active' : ''}">
            <a data-toggle="collapse" data-target="#bs-example-navbar-collapse-1.in"...
         </li>
      </ul>
      
      <ul class="nav navbar-nav navbar-right">
         <li class="loader" if.bind="router.isNavigating">
            <i class="fa fa-spinner fa-spin fa-2x"></i>
         </li>
      </ul>
   </div>
</nav>  
<div class="page-host">
   <router-view></router-view>
</div>

 
 

That HTML markup for the nav bar is brought into the new app.html as a consistent menu (regardless of what content is transitioned to in routing) like so:

<template>
   <compose view="./nav-bar.html" containerless></compose>
   
   <div class="page-host">
      <router-view></router-view>
   </div>
</template>

 
 

If you slap containerless on a tag as shown above it will not appear in the HTML markup that makes its way up to the DOM allowing the tag to only exist for your coordination and bookkeeping at the aurelia side of things. That's really all of the basics. I cut out of this tech talk a little early and especially so when I suspected it was crossing out of the basics into the deeper stuff. The following stuff brought in a bunch of photos of tacos. It shows how to bring in other .js libraries for aurelia to do extra stuff too.

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';  
@inject(HttpClient)
export class Tacos{
   heading = 'Tacos';
   images = [];
   url = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=tacos...
   
   constructor(http){
      this.http = http;
   }
   
   activate(){
      return this.http.jsonp(this.url).then(response => {
         this.images = response.content.items;
      });
   }
}

Saturday, July 18, 2015

good habits!

I saw David McCarter speak at the Austin .NET User group on Monday night on good coding practices. He suggested that by the time a bug exists in code that was not proactively prevented in the design phase it takes ten times as long to chase it away as it would have if it were curtailed upfront. In production it takes one hundred times as long, and both of these figures should encourage (scare) you to not be sloppy. He went through his own grocery list of to-dos and I took notes. Things said:

  • Portable Class Libraries seems to be the proper name for what David was referring to when he suggested that most code should be in portable .dlls. This is a new (well, newish) Visual Studio project type (and, yes, you have to start with it to begin with as you can't cast existing projects to this) which allows you to specify what platforms you will deploy the code to (Windows, Xbox, Windows Phone, Silverlight) and then restrains by way of the complier what C# it will allow so that you don't write something that can't roll out to all targeted environments.
  • Inheritance, polymorphism, and encapsulation are the three pillars of object-oriented programming. You should really use them.
  • What's the biggest performance issue in modern apps? The internet itself! Its speed and intermittent availability poses some challenges. Caching data (cache long running reports) and having a policy of "less data transfer" helps (make calls chunky not chatty and only go across the wire when you have to), but in today's world all applications should be architected for being occasional connected to the internet. Think of how Microsoft Outlook lets you send an email even as you sit on an airplane cut off from everything. It just goes to that "Outbox" queuing grounds, right? Brilliant! Why can't posts to Facebook behave like that? Duh. Azure Mobile Services has a solution in this regard and there is a new version of the Microsoft Sync Framework for Windows phone (and also Apple/Android) called SQLite which gives you a dumbed-down (no stored procedures!) MSSQL database which will automatically sync up to the real MSSQL database when it comes online, so that you may just read/write to SQLite! In the absence of sprocs I guess one has to use an ORM or write old school PHP-era select statements in the code itself as was the norm a dozen years ago. You can ship products without a client database and SQLite will just build the first time it is run. This sounds like what I hoped code-first Entity Framework would be like, but I've been burned before so I'm skeptical.
  • He had a slide titled "Perception is Everything!" with copy reading "To ensure your users are happy make sure to work on the perceived speed of the app" and a chart giving a breakdown of what the user perceptions will be at various degrees of lag/delay as measured in milliseconds:
    0- 100 Instant
    100- 300 Small perceptible delay
    300- 1,000 Machine is working
      1,000+ Likely mental context switch
      10,000+  Task is abandoned
    Even in a WinForms application you do not want to make users wait ten seconds. Amazon does not run your credit card when you checkout at its store. It does that later, speeding up the perceived-first-hand process, and then flags you if something went wonky.
  • IntelliTest in Visual Studio 2015 will write unit tests for you. You may click on a method, specify IntelliTest to do its thing, and produce. What does cyclomatic complexity mean? It's a measure of complexity based on the number of possible paths through code. In writing unit tests you should ideally cover all of them. Do you really want to write 700 tests?
  • .dlls should be dumb and stupid. They should not log exceptions or send emails. They should trigger events to hand up to other things to do this.
  • Use .NET Trace Listeners to log exceptions and inner exceptions. Log as much as you can and make sure that you log in a way that is not opaque so that one may actually reverse engineer what happened from the log instead of being left in the dark.
  • Use strong-named assemblies. This prevents someone from hacking into your server, grabbing that .dll named CreditCardProcessor.dll, using JetBrains dotPeek to cast the CLR inside back to C#, putting sinister code inside the pulled out stuff to forward credit card information on to elsewhere, and then recompiling the .dll and replacing it at your server by way of obfuscating the CLR code so that will only make sense if you have the appropriate digital signature.
  • Globalization and localization should be embraced upfront. Some of David's canned C# code for as much looks like so:
       string birthDate = p1.BirthDate.ToString(CultureInfo.CurrentCulture);
       string annualIncome =
             p1.AnnualIncome.ToString(CultureInfo.CurrentCulture);
       string info = string.Format(CultureInfo.CurrentUICulture,
             Properties.Resources.UserInfoFormat, p1.FirstName, birthDate,
             annualIncome);

    Above, "User Info For {0} Born On: {1} Annual Income: {2}." or something like it is going to be at the lookup against UserInfoFormat as the value at the English language resource. Pretty straightforward stuff, huh? A little more new to me was his internationalization friendly way of comparing objects in sorting them:
       public static int ComparePerson(Person p1, Person p2)
       {
          return string.Compare(p1.FirstName, p2.FirstName,
                StringComparison.OrdinalIgnoreCase);
       }

    He said that FxCop was a good tool to use for catching globalization/localization gremlins and that CodeIt.Right by submain will clean up bad code for you in this regard.
  • Julie Lerman is the queen of Entity Framework!

Friday, July 17, 2015

strict versus loose mocking

As best as I can tell, in strict mocking one has to specify what a method on an interface will return if one is to call that method without having an exception thrown. This is the way I've always done things. In loose mocking one however does not have to detail what methods will do on mock objects and instead the methods will just return the default values for the return types (such as null or 0) when they are called without error. Some links I found:

at Windows Server 2012 R2, I can't install the 3.5 Framework

I wish this worked...

  1. open "Server Manager" (probably the leftmost icon at the taskbar)
  2. click "Manage" at the upper right where it says: Manage, Tools, View, Help
  3. pick "Add Roles and Features"
  4. tab through the wizard to reach the set of checkboxes in the "Features" portion of the wizard and check the ".NET Framework 3.5 Features" checkbox there
  5. "Confirmation" is the next page in the wizard and herein you should click the "Specify an alternative source path" link
  6. you will have to specify a path to a file and the file should come from https://www.microsoft.com/en-us/download/details.aspx?id=21
  7. finish up the wizard
  8. run the service pack 1 update at https://www.microsoft.com/en-us/download/confirmation.aspx?id=22

...but it doesn't. I need the 3.5 Frameworks with Service Pack 1 to set up SSMS 2014. :(

a .vsix may just be renamed to be a .zip in order to open it up and see what is inside

This taught me as much.

Set a getsetter by matching its name to a magic string in C#.

This comes from here and seems to work. This test passes:

using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Atty.Core.Tests
{
   [TestClass]
   public class AnotherTest
   {
      [TestMethod]
      public void reflection_works()
      {
         Person person = new Person()
         {
            Name = "Ty Ng",
            UsStateOfResidence = "Iowa",
            Mantra = "It's OK to cry."
         };
         object red = "Red";
         person.GetType().GetProperty("FavoriteColor").SetValue(person, red, null);
         Assert.AreEqual(person.FavoriteColor, "Red");
      }
   }
}

 
 

At .SetValue the first parameter is the instance to affect and the object handed in for the second parameter seems to be the value the getsetter in question, in this case FavoriteColor, is going to get set to. We can hand in almost any type (not dynamic) for the second parameter revealing that an object is expected. Under the hood, the object is upcast to the appropriate type, or at least there is an attempt to do so. In this example, the Person object is the same as the one defined here.

Thursday, July 16, 2015

having "tabid" in the URL line as one of the variables is a DotNetNuke thing

Yuck!

Object.assign in ES6!

This will give us two alerts. The first will have 13 in it and the second will have 42. This is yet another thing I've learned in reading Kyle Simpson's "this & OBJECT PROTOTYPES" ...

var foo = {
   bar: 13
};
var baz = {
   qux: 42
};
var whatever = Object.assign({},foo,baz);
alert(whatever.bar);
alert(whatever.qux);

Addendum 7/17/2015: There may be any number of values handed in. (well, any number two or greater) The first value in is the target and all of the values after it get appended to it.

Use C# attributes to sanity check instances of objects and not just dress up types with metadata.

It's taken me a while to understand why I should really care about attributes in C#. All of the examples I have typically seen show an attribute like so...

using System;
namespace Atty.Core
{
   [AttributeUsage(AttributeTargets.Property)]
   public class MinimumLengthAttribute : Attribute
   {
      public int Requirement { get; private set; }
      public MinimumLengthAttribute(int requirement)
      {
         Requirement = requirement;
      }
   }
}

 
 

...dressing up a class like so:

namespace Atty.Core
{
   public class Person
   {
      [MinimumLength(5)]
      public string Name { get; set; }
      
      [MinimumLength(4)]
      public string UsStateOfResidence { get; set; }
      
      public string Mantra { get; set; }
      
      [MinimumLength(3)]
      public string FavoriteColor { get; set; }
   }
}

 
 

...and then the type being inspected by reflection as suggested here to fish the metadata back out, but... who cares? That really isn't that useful is it? The decorations we are applying to the type tell us that the Name of a Person should be at least five characters long, but that doesn't help us as there is no way to get at the attribute save for with reflection and in doing so we are only having at the type and not instances of the type. Basically we are suggesting that everything growing in a forest should stand at least so tall while measuring none of the trees making an ignorable and ignored law of no consequence.

What do we do about this? There is a solution, but it's not intuitive at all. We need to basically compare the forest to its trees to make sense of sanity checking. Given that MinimumLengthAttribute may decorate getsetters, we need to hand a type (and that could be any type, but not necessarily a Person for a Person-specific sanity checker doesn't benefit from a pattern that uses slap-me-on-at-any-class attributes) into a static method that will make a dictionary of all getsetters decorated by MinimumLengthAttribute and the minimum lengths they propose like so:

using System;
using System.Collections.Generic;
using System.Reflection;
namespace Atty.Core
{
   public static class SanityChecker
   {
      public static void Check(object perishable)
      {
         Type type = perishable.GetType();
         PropertyInfo[] propertyInfo = type.GetProperties();
         Dictionary<string, int> metadata = new Dictionary<string, int>();
         int counter = 0;
         while (counter < propertyInfo.Length)
         {
            MinimumLengthAttribute minimumLengthAttribute =
                  (MinimumLengthAttribute)Attribute.GetCustomAttribute(propertyInfo[counter],
                  typeof(MinimumLengthAttribute));
            if (minimumLengthAttribute != null)
            {
               metadata.Add(propertyInfo[counter].Name,
                     minimumLengthAttribute.Requirement);
            }
            counter++;
         }
         foreach (KeyValuePair<string, int> metadatum in metadata)
         {
            object setting = type.GetProperty(metadatum.Key).GetValue(perishable);
            if (metadatum.Value > 0)
            {
               if (setting == null || ((string)setting).Length < metadatum.Value)
               {
                  throw new Exception("The " + metadatum.Key + " for the " + type.Name + "
                        is inappropriately less than " + metadatum.Value + " characters.");
               }
            }
         }
      }
   }
}

 
 

Alright, as also suggested above, once we have fished a dictionary of rules out of a type with reflection, we are no longer forced to focus on the forest exclusively and we may now move beyond (the few things we may do with the type standalone) to inspect the trees. All that is left is to compare the dictionary to the class instances and throw exceptions when a rule is broken. This allows us to use attributes to define sanity checks and while I've always seen this sort of stuff in applications, it was never anything I had authored myself or really understood the magic of. I get it now. The following tests will all pass given the three classes above:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Atty.Core.Tests
{
   [TestClass]
   public class Tests
   {
      [TestMethod]
      public void happy_pass_should_pass_happily()
      {
         Exception exception = null;
         Person person = new Person()
         {
            Name = "Ty Ng",
            UsStateOfResidence = "Iowa",
            Mantra = "It's OK to cry.",
            FavoriteColor = "Red"
         };
         try
         {
            SanityChecker.Check(person);
         }
         catch (Exception explosion)
         {
            exception = explosion;
         }
         Assert.AreEqual(exception, null);
      }
      
      [TestMethod]
      public void lack_of_a_name_will_throw_an_exception()
      {
         Exception exception = null;
         Person person = new Person()
         {
            UsStateOfResidence = "Iowa",
            Mantra = "It's OK to cry.",
            FavoriteColor = "Red"
         };
         try
         {
            SanityChecker.Check(person);
         }
         catch (Exception explosion)
         {
            exception = explosion;
         }
         Assert.AreNotEqual(exception, null);
         Assert.AreEqual(exception.Message, "The Name for the Person is inappropriately
               less than 5 characters.");
      }
      
      [TestMethod]
      public void state_abbreviations_for_state_names_are_unacceptable()
      {
         Exception exception = null;
         Person person = new Person()
         {
            Name = "Ty Ng",
            UsStateOfResidence = "IA",
            Mantra = "It's OK to cry.",
            FavoriteColor = "Red"
         };
         try
         {
            SanityChecker.Check(person);
         }
         catch (Exception explosion)
         {
            exception = explosion;
         }
         Assert.AreNotEqual(exception, null);
         Assert.AreEqual(exception.Message, "The UsStateOfResidence for the Person is
               inappropriately less than 4 characters.");
      }
      
      [TestMethod]
      public void missing_mantra_should_cause_no_problems()
      {
         Exception exception = null;
         Person person = new Person()
         {
            Name = "Ty Ng",
            UsStateOfResidence = "Iowa",
            FavoriteColor = "Red"
         };
         try
         {
            SanityChecker.Check(person);
         }
         catch (Exception explosion)
         {
            exception = explosion;
         }
         Assert.AreEqual(exception, null);
      }
      
      [TestMethod]
      public void oy_is_not_a_color()
      {
         Exception exception = null;
         Person person = new Person()
         {
            Name = "Ty Ng",
            UsStateOfResidence = "Iowa",
            Mantra = "It's OK to cry.",
            FavoriteColor = "oy"
         };
         try
         {
            SanityChecker.Check(person);
         }
         catch (Exception explosion)
         {
            exception = explosion;
         }
         Assert.AreNotEqual(exception, null);
         Assert.AreEqual(exception.Message, "The FavoriteColor for the Person is
               inappropriately less than 3 characters.");
      }
   }
}

 
 

I asked a coworker what he thought of this sort of thing and he suggested that one probably doesn't want to roll their own thing and that using a pre-made, third party solution like Microsoft DataAnnotations was a better way to go. There are going to have to be a lot of rules (attribute types) you can apply and prewritten code like my static method above that you don't have to maintain or think about yourself for this sort of thing to even be worth your time given the grotesque workaround that is happening beneath the hood, right? My coworker suggested that in PostSharp the AOP capabilities allow one to specify a method to be run before a regular method and that in such a forerunner one will have accessible as a part of the framework both the metadata from applicable attributes and the instances of classes to interface with them. This architecture must be doing out-of-sight what I am doing above in a more complicated/elegant way.

Tuesday, July 14, 2015

tags in Rally

When looking at a story or defect at the details tab they will be at the upper right. You'll see a heading for "TAGS" and an "add" link for adding new tags. There are canned tags and you may also make custom tags I think. These are flags for categorizations of what's up. A defect which cannot be reproduced could be tagged with as much, etc.

no love for the testers?

Where I work I we have a really awesome testing team and a good process to make sure that they are empowered to be effective and not just squeezed for time or in existence merely so that we may pretend that we test in the name of checking a checkbox on a report somewhere. However, the second-class citizen lifestyle does apply to testers in numerous professional environments where their teams are not treated as if to be taken seriously. If development is to wrap up at the end of August and the project has to be done at the end of October after two months of testing, when the development spills over to the end of September, don't expect the October deadline to move forward to allow the testing team to yet have two months to test in many environments. In these bad situations, the amount of time to test is reduced and the testers are just pinched for time and pressured to bless things. This is sad because I've now seen how awesome the safeguard of a testing team can be when it is allowed to do its job. It's also worth saying that the small businesses that I've worked in which had no testing teams and tried to solve all of their problems with unit tests, pair programming, code reviews, and peer reviews now seem misguided.

four nines and five nines

Five nines implies 99.999% availability which means there may be no more than 5.26 minutes of downtime in a given year, while a bigger 52.56 minutes are available for downtime given 99.99% availability, known as four nines.

Monday, July 13, 2015

SCOPE_IDENTITY() and @@IDENTITY in T-SQL

Imagine we wish to insert a record and then take the primary key for that record and use it to turn around and insert another record as suggested here. This could also be done like so:

BEGIN TRANSACTION setup
   INSERT INTO Note (WhateverId, Copy)
   VALUES (@WhateverId, 'hello world')
   DECLARE @NoteId int
   SELECT @NoteId=SCOPE_IDENTITY()
   INSERT INTO Affidavit (WhateverId, NoteId, Copy)
   VALUES (@WhateverId, @NoteId, 'hello lawsuit')
COMMIT TRANSACTION setup

 
 

...and like so too:

BEGIN TRANSACTION setup
   INSERT INTO Note (WhateverId, Copy)
   VALUES (@WhateverId, 'hello world')
   DECLARE @NoteId int
   SELECT @NoteId=@@IDENTITY
   INSERT INTO Affidavit (WhateverId, NoteId, Copy)
   VALUES (@WhateverId, @NoteId, 'hello lawsuit')
COMMIT TRANSACTION setup

 
 

What is the difference between the two? They both have a clipboard cache of sorts of the last primary key used but while SCOPE_IDENTITY() is restricted to the transaction at hand @@IDENTITY has no such restriction so two commits from two different sources happening simultaneously should be able to dirty up its behavior causing heartache.

Sunday, July 12, 2015

There are six simple primitives in JavaScript and also nine complex primitives which are subtypes of object (one of the simple primitives).

  1. string
  2. number
  3. boolean
  4. null
  5. undefined
  6. object
    • String
    • Number
    • Boolean
    • Object
    • Function
    • Array
    • Date
    • RegExp
    • Error

 
 

So what is the difference between string and String? Answer: string actually is a string while String is just used to new up a string.

var foo = "bar";
var baz = new String("qux");

 
 

This is another insight from Kyle Simpson's book "this & OBJECT PROTOTYPES" which I am really enjoying reading!

green to using nolock

I was surprised when this worked all by itself...

BEGIN TRANSACTION setup
   INSERT INTO Note (WhateverId, Copy)
   VALUES (@WhateverId, 'hello world')
   DECLARE @NoteId int
   SELECT @NoteId=NoteId FROM Note
   WHERE WhateverId = @WhateverId
   INSERT INTO Affidavit (WhateverId, NoteId, Copy)
   VALUES (@WhateverId, @NoteId, 'hello lawsuit')
COMMIT TRANSACTION setup

 
 

...without a nolock like so:

BEGIN TRANSACTION setup
   INSERT INTO Note (WhateverId, Copy)
   VALUES (@WhateverId, 'hello world')
   DECLARE @NoteId int
   SELECT @NoteId=NoteId FROM Note with(nolock)
   WHERE WhateverId = @WhateverId
   INSERT INTO Affidavit (WhateverId, NoteId, Copy)
   VALUES (@WhateverId, @NoteId, 'hello lawsuit')
COMMIT TRANSACTION setup

 
 

I guess I am green to using nolock. If I don't need it here, when do I need it? This suggests that this:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

 
 

...will globally allow for not needing locking, but when I asked myself "How may I tell what the transaction isolation level is?" I then found this which has...

SELECT CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncommitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions
where session_id = @@SPID

 
 

...which handed me back ReadCommitted. I guess my local environment isn't wacky. So... when do I need to lock?

Addendum 7/13/2015: I have learned that nolock in T-SQL does NOT apply to the transaction at hand (allowing you to read uncommitted rows), but instead it applies to the other transactions out there in space (allowing you to read uncommitted rows) at the same time from other connections.

T-SQL is NOT case sensitive

I find I can get a lot of goofy things to work when they would blow up in comparable C# space sloppiness.

Saturday, July 11, 2015

the "fat arrow" operator in ECMAScript 6

The old school self-equals-this way of handing this on as predictable state like so...

function superstructureSentence() {
   var self = this;
   return function(act) {
      var sentence = "The ";
      self.foxyAdjectives.forEach(function(f) {
         sentence = sentence + f + " ";
      });
      sentence = sentence + "fox " + act + "s over the ";
      self.doggishAdjectives.forEach(function(d) {
         sentence = sentence + d + " ";
      });
      alert(sentence + "dog.");
   }
}
var glitz = {
   foxyAdjectives : ["quick", "red"],
   doggishAdjectives : ["lazy", "brown"]
};
var structureSentence = superstructureSentence.call(glitz);
structureSentence("jump");
structureSentence("fuck");

 
 

...may now be approached as follows with the arrow.

function superstructureSentence() {
   return (act) => {
      var sentence = "The ";
      this.foxyAdjectives.forEach(function(f) {
         sentence = sentence + f + " ";
      });
      sentence = sentence + "fox " + act + "s over the ";
      this.doggishAdjectives.forEach(function(d) {
         sentence = sentence + d + " ";
      });
      alert(sentence + "dog.");
   }
}
var glitz = {
   foxyAdjectives : ["quick", "red"],
   doggishAdjectives : ["lazy", "brown"]
};
var structureSentence = superstructureSentence.call(glitz);
structureSentence("jump");
structureSentence("fuck");

 
 

I read about as much in "this & OBJECT PROTOTYPES" by Kyle Simpson! Both of these blobs of code give us two alerts, telling us:

  1. The quick red fox jumps over the lazy brown dog.
  2. The quick red fox fucks over the lazy brown dog.

Make inbound parameters optional at a stored procedure!

ALTER PROCEDURE [dbo].[Whatever]
(
   @FooId int = NULL,
   @BarId int = NULL
)
AS

Friday, July 10, 2015

machine.config

...is another .config file in the ASP.NET Framework like Web.config. It can effect how your web site runs just like Web.config and is 32-bit or 64-bit specific living at a path such as:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config

 
 

Anymore, you're going to have to go out of your way to run the 32-bit version in IIS.

Allow a column to have null values in T-SQL.

ALTER TABLE MyTable ALTER COLUMN MyNumber INTEGER NULL

.mp3 files

If you put one in a .zip by itself the .zip will be bigger in file size than the .mp3 was on its own!

QuickWatch

Select the right side of the equals sign of a variable assignment in Visual Studio 2013 (highlight it) while debugging and then right-click and pick "QuickWatch..." from the menu which appears to get a breakdown of what the assignment should be.

Thursday, July 9, 2015

If you undertake a Response.Redirect at a web form's OnInit event the Page_Load event is nonetheless going to run before the redirect even though that will happen downstream sequentially speaking.

Hence, if you are trying to do this in the name of sanity checking if the state exists to even display a web form's contents, you may need to wrap the guts of the Page_Load event in a try/catch or some other safeguard of the like.

Addendum 7/20/2015: The fix for this might be this.

Wednesday, July 8, 2015

When spinning up a new VM in VMware from an .iso you will likely have to install one hundred and one Windows updates.

This is pretty frustrating and means that you should not immediately restart if you need to immediately work on the VM. Don't fall down that pit! This details a way to turn off the Windows Updates. I'm not certain it works. The steps:

  1. Type update at start menu in Windows Server 2008 R2.
  2. Click "change settings" at the left menu of the thing which appears.
  3. Click the "Give me recommended updates the same way I receive important updates" checkbox.

Don't try to separate email addresses with commas instead of semicolons when trying to send an email to parties outside of your contact list in Microsoft Outlook.

Outlook will stress out. You'll get that "Check Names" dialog box wherein you could perhaps create a new contact. Infuriating!

When your server side tool warps the ids at the client side...

Creating a shape such as...

nonsense_nonsense_nonsense_nameinCsharp_nonsense

 
 

It's best to write Selenium tests that latch onto ids not with one-for-one magic string matching but instead by checking to see if the id contains the really important part such as "nameinCsharp" in the circumstance above. This should make the tests less brittle.

Tuesday, July 7, 2015

PII is personally identifiable information.

It's a buzz term for data points which may help pinpoint a person's identity differentiating it from others.

Monday, July 6, 2015

interpolated strings the new String.Format in Visual Studio 2015?

This was shared with the team by my boss today and it has this example in C#:

var s = $"hello, {name}";

Addendum 7/29/2015: name ...is a variable in this bit of C# 6.0.

Sunday, July 5, 2015

page 28 of this & OBJECT PROTOTYPES by Kyle Simpson

Revamping my prior .apply example, I continue to cracksmoke my way through the book I came away with through happenstance at this event:

var unassumingAgent = 13;
function whatever(name, taste) {
   this.unassumingAgent = 14;
   alert(name + " likes " + taste + ".");
}
whatever.apply(null, ["Roy", "strawberries"]);
alert(unassumingAgent + " is my lucky number");

 
 

This is bad! This will tell me that 14 is my lucky number when it's not lucky at all! In his book, Mr. Simpson warns of handing in null at .apply and .bind examples to just sidestep an unneeded this when interfacing with third party libraries because if you haven't written the code yourself for all you know it is warping the global object (window) as he puts it or the first step in the call-site chain of presidence. Clearly that is happening here. The solution is to hand in a dummy object you don't care about. The following will tell me that 13 is my luckly number, and yes I know how comic it is that an atheist believes in luck. I see a distinction between the deep end of bullshit and the shallow end (half-assed fun not blinders on commitment) that I will not delve into at this time.

var unassumingAgent = 13;
function whatever(name, taste) {
   this.unassumingAgent = 14;
   alert(name + " likes " + taste + ".");
}
var chaosContainment = new Object;
whatever.apply(chaosContainment, ["Roy", "strawberries"]);
alert(unassumingAgent + " is my lucky number");

 
 

If it's your own code and you are not worried about making an unused this safe, you can use the spread operator in ES6 instead of .apply to clean up your code a little bit and not spec this at all. The code below and the code above both return the same two alerts.

var unassumingAgent = 13;
function whatever(name, taste) {
   alert(name + " likes " + taste + ".");
}
var things = ["Roy", "strawberries"];
whatever(...things);
alert(unassumingAgent + " is my lucky number");

Saturday, July 4, 2015

currying with bind

Something more from this & OBJECT PROTOTYPES by Kyle Simpson:

function addStuff(yin,yang){
   return(this+yin+yang);
}
var firstStep = addStuff.bind(13,42);
var secondStep = firstStep(3.1415);
alert(secondStep);

 
 

Notice that we may assign some of the parameters downstream in a second step. That is the magic to take note of here in this practice. We will be given 58.1415 in this circumstance. Also note that the definition for this is always handed in first thing with .bind. I suppose we could have had a function signature with three variables and could have handed in null followed by two variables in the first step if as much seems confusing.

the question mark operator in JavaScript

Rewriting my double ampersand example like so:

var four = 4;
var five = 5;
var whatever = four ? four : five;
alert(whatever);

 
 

...it's going to give us a 4. Basically this says, if four is truthy use four and otherwise use five, so if we instead set four to null at the first line we will get 5. Get it?

constructors in JavaScript

In JS, constructors are just functions that happen to be called with the new operator in front of them.

   -Kyle Simpson, this & OBJECT PROTOTYPES

instanceof

I found this example at javascript.info:

function Rabbit() { };
var rabbit = new Rabbit;
alert(rabbit instanceof Rabbit);

 
 

Alright, rabbit instanceof Rabbit is going to give us true if rabbit is a Rabbit and false if rabbit is a Walrus (i.e. not a Rabbit). It turns out that, in this example, rabbit is a Rabbit and hence we will be given true.

Array.prototype.slice.call() madness!

This way to make slice shallow copies à la .slice against not an array but instead a regular object surfaces on page 25 of Kyle Simpson's "this & OBJECT PROTOTYPES" and he does not immediately explain it. Perhaps this is a teaser of something to come. I had to Google it and this example was found at StackOverflow:

var my_object = {
   '0': 'zero',
   '1': 'one',
   '2': 'two',
   '3': 'three',
   '4': 'four',
   length: 5
};
var sliced = Array.prototype.slice.call(my_object, 3);
console.log(sliced);

 
 

The object has to have a length bolted onto it and if the properties don't have numbers for names goofy badness occurs. This example will give us an array with two strings in it, the first being three and the later being four. Why would you ever want to use this horrible functionality? Earlier in his book, Kyle suggests he does not feel that developers should focus on the distinction between the "good parts" of JavaScript versus the "bad parts" of JavaScript and that really you need to understand all of it and not just the stuff you like. Perhaps his philosophy is manifesting in his Array.prototype.slice.call() example.

Declare multiple variables in JavaScript on the same line by way of comma separation.

It's gross and confusing:

var foo = "bar", baz = "qux";
console.log(foo);
console.log(baz);

.concat in JavaScript is for concatenation

var yin = "Hello";
var yang = "World";
var yinyang = yin.concat(yang);
console.log(yinyang);

 
 

Gives us HelloWorld while the following gives us an array of two strings wherein the first string is Hello and the second string in World.

var yin = new Array("Hello");
var yang = new Array("World");
var yinyang = yin.concat(yang);
console.log(yinyang);

wacky double ampersand operator in JavaScript

It will return the right value if the left is truthy and the left value if the left is falsey, so in this example:

var four = 4;
var five = 5;
var whatever = four && five;
alert(whatever);

 
 

...it's going to give us a 5. However if you set the four variable to null it will give us null or if you set the four variable to 0 it will give us 0.

typeof in JavaScript

  1. var x = function(){};
    alert(typeof x);

       ...is going to bubble up: function
     
  2. var x = 33;
    alert(typeof x);

       ...is going to bubble up: number
     
  3. var x = "Hello World.";
    alert(typeof x);

       ...is going to bubble up: string
     
  4. var x = {
       y: "why not?"
    }
    alert(typeof x);

       ...is going to bubble up: object
     
  5. etc.

Thursday, July 2, 2015

Did you know that you may add a NOT NULL column to an existing table that has rows in it with T-SQL?

You have to give a default value and the constraint for it has to be given at the moment the column is added like so:

ALTER Table My_Corny_Table
ADD The_Date DateTime NOT NULL
CONSTRAINT DF_My_Corny_Table_The_Date DEFAULT GETDATE()

_aspxCancelBubble in DevExpress 13

...is not an event in version 15! Pull this out of your JavaScript or it will blow up.

When a build does not restore NuGet packages....

Try pulling everything down out of source control fresh into a fresh folder while first destroying the root folder of the app. That ".nuget" folder needs to go away in the cleansing with everything else.

Wednesday, July 1, 2015

the scope of this in JavaScript

Kyle Simpson's book this & OBJECT PROTOTYPES lists four varieties of bindings for this:

  1. Default Binding just looks up the call-stack for the call-site. One step up the history of calls from the spot at hand is where this is defined. As the name implies, this is the default.
    function sigourneyWeaver() {
       alert("The computer says: " + this.message);
    }
    var message = "Hello World";
    sigourneyWeaver();

     
  2. Implicit Binding has one fishing for this.whatever at an object's properties.
    function sigourneyWeaver() {
       alert("The computer says: " + this.message);
    }
    var computer = {
       message: "Hello World",
       operator: sigourneyWeaver
    }
    computer.operator();

     
  3. Explicit Binding is the .call stuff.
    function sigourneyWeaver() {
       alert("The computer says: " + this.message);
    }
    var computer = {
       message: "Hello World"
    }
    sigourneyWeaver.call(computer);

     
  4. new Binding lets you sidestep the usual truth that when using this in a function, you are not referring to the scope of the function itself.
    function sigourneyWeaver(message) {
       this.reiteration = "The computer says: " + message;
    }
    var noomiRapace = new sigourneyWeaver("Hello World");
    alert(noomiRapace.reiteration);

     

The third of the four, Explicit Binding, is the most interesting. When a primative is handed into a function, behind the scenes it is boxed. The boxing allows for the primative to be created as if newed up. A string is handed to the function such that makes it into the function as if assigned by a = new String("Hello World"); approach. Such affects this like so:

function sigourneyWeaver() {
   alert("The computer says: " + this);
}
sigourneyWeaver.call("Hello World");

 
 

In the concept of Hard Binding the function called with Explicit Binding is always called from a wrapper function to which variables to be passed on are handed in. This keeps the scope of this from behaving unexpectedly. One interesting thing about the example in the book is that it revealed to me that functions have an "arguments" variable which is an array of all variables handed into the function even if or without regard to if they are not defined at function's signature. Observe:

function sigourneyWeaver() {
   alert("The computer says: " + this);
}
function rickMoranis() {
   sigourneyWeaver.call(arguments[0]);
}
rickMoranis("Hello World");

 
 

Now imagine the protected function was swappable at the wrapping function like so:

function sigourneyWeaver() {
   alert("The computer says: " + this);
}
function rickMoranis(gateKeeper, message) {
   gateKeeper.call(message);
}
rickMoranis(sigourneyWeaver, "Hello World");

 
 

Alright, because this is a common pattern for Explicit/Hard Binding JavaScript makes the code immediately above a bit easier to repeat with .bind like so:

function sigourneyWeaver() {
   alert("The computer says: " + this);
}
var rickMoranis = sigourneyWeaver.bind("Hello World");
rickMoranis();

more random notes of sprucing up one's Windows environments

  1. open "Disk Defragmenter" in Windows 7 by typing "Disk Defragmenter" at the start menu and then click the "Configure schedule..." button to set a schedule
  2. when installing from an .iso to a VMware VM you may click on the CD option at the left navigation in VMware and there will be an option ("Use ISO image file:") for picking an .iso file at your main machine outside of your VMs
  3. You can't add hard disk space to a VMware VM while it's running. You need to power it down first. Then, click the Hard Disk option at the left nav and pick "Utilities" to add space or "Add" to add a new partition. If you add a new partition, when you bring your VM back up you need to (assuming Windows Server 2008 R2) open Server Manager and drill down to Disk Management below Storage. Right-click on the grey title of the partition and pick "Online" and then right-click again and pick "Initialize Disk" and finally right-click in the white of the horizontal slat of the drive listing and pick: "New Simple Volume"

When taking a snapshot of a VM in VMware it may be best to have the VM powered off.

It was pointed out to me today that not doing so captures a bunch of other state and balloons the footprint of the snapshot and increases the likelihood of something going South. A snapshot I restored that was taken when the VM was up was sickly at work today and spun and spun while trying to install Windows updates upon a restart.