Monday, September 30, 2013

Call a GRUNT task from the command line.

cd whatever
npm install
grunt foo

 
 

...run from the command line (at a Windows command prompt) would fire off the foo task in this Gruntfile.js file which would in turn fire off the bar, baz, and qux tasks:

module.exports = function(grunt) {
   grunt.initConfig({
      pkg: '<json:package.json>',
      sweet: {
         //whatever
      },
      sour: {
         //whatever
      },
      salty: {
         //whatever
      },
      clean: ["Release"]
   });
   grunt.registerTask('bar', 'sweet');
   grunt.registerTask('baz', 'sour');
   grunt.registerTask('qux', 'salty');
   grunt.registerTask('foo', ['bar', 'baz', 'qux']);
};

 
 

Add user permissions to a Mercurial branch in Fogbugz Kiln.

...at the "Settings" as suggested here.

Create a subrepository in Mercurial!

  1. Pull down the code for the parent-to-be repository into a folder.
  2. Make a new folder within the repository and pull down the child-to-be repository into the new folder. (I did not see an option for "Clone..." beneath the option for "TortoiseHg" when I right-clicked on the folder I made and this was probably so as the folder already sits inside of another repository's folder structure. I got around this by right-clicking on a random folder elsewhere, picking "Clone..." and then setting the values for both Source and Destination appropriately.)
  3. Add a line to the .hgsub file in the root folder of what has been pulled down for the parent-to-be repository like so:
    mysubordinate = http://ourserver01/FogBugz/Kiln/Code/Stuff/Whatever
    ...if the child-to-be repository is pulled down into a folder called "mysubordinate" which sits in the root of the parent-to-be stuff along with the .hgsub file. If you want to nest the child-to-be repository a few folders deep you may do something like this:
    build/mysubordinate = http://ourserver01/FogBugz/Kiln/Code/Stuff/Whatever
    ...herein "build" could be a preexisting folder or a newly made one existing only to buffer the subrepository from the repository a little bit.
  4. Commit the changes to the parent-to-be repository both locally and then to the server.

optimist is for option parsing in the Node.js space

I am looking at a project right now where variables are defined for Node consumption in an Ant build script like so:

<exec executable="${node.exec}">
   <arg value="${stuff.root}/folderholdingapackagedotjsonfile" />
   <arg value="--user=${stuff.user}" />
   <arg value="--password=${stuff.password}" />
   <arg value="--tag=${build.number}" />
</exec>

 
 

folderholdingapackagedotjsonfile would contain a package.json with a main specification which will direct to a .js holding something like this:

'use strict';
var argv = require('optimist')
   .usage('Usage: node folderholdingapackagedotjsonfile --url [url] --user [email] --password
      [str] --tag [str]')
   .default('url', 'http://www.example.com/')
   .demand(['user', 'password', 'tag', 'statusFilter', 'categoryFilter'])
   .describe('user', 'its your username')
   .describe('password', 'its your password')
   .describe('tag', 'its your version')
   .describe('url', 'its your locale')
   .argv;
var thingtodeferto = require('./somethingelse');
var settingstohandoff = {
   url: argv.url,
   user: argv.user,
   password: argv.password,
   tag: argv.tag
};
thingtodeferto.run(settingstohandoff);

 
 

Our .js file is thus able to kick off a process in somethingelse.js in the same folder as itself and package.json by pushing the variables from Ant into the "run" function in the form of settingstohandoff. Note that while we do not hand in a url from Ant, we could do so.

using Ant with Jenkins!

Call a Jenkins variable from an Ant Script like so:

<condition property="build.number" value="${env.BUILD_NUMBER}" else="0">
   <isset property="env.BUILD_NUMBER" />
</condition>

 
 

You may want to use Ant instead of NAnt (there is also an "Execute NAnt build" build step) with Jenkins as it will just jive with Java-based Jenkins out of the box where NAnt will require the ASP.NET runtime. My challenge today is to find a way to latch onto a Jenkins variable from GRUNT!

Jenkins variables you may use in builds!

The link which reads "See the list of available environment variables" in Jenkins at an "Execute shell" line item opens up to this cheat sheet:

 
 

The following variables are available to shell scripts

BUILD_NUMBER
    The current build number, such as "153"
     
BUILD_ID
    The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)
     
JOB_NAME
    Name of the project of this build, such as "foo" or "foo/bar"
     
BUILD_TAG
    String of "jenkins-${JOB_NAME}-${BUILD_NUMBER}". Convenient to put into a resource file, a jar file, etc for easier identification.
     
EXECUTOR_NUMBER
    The unique number that identifies the current executor (among executors of the same machine) that's carrying out this build. This is the number you see in the "build executor status", except that the number starts from 0, not 1.
     
NODE_NAME
    Name of the slave if the build is on a slave, or "master" if run on master
     
NODE_LABELS
    Whitespace-separated list of labels that the node is assigned.
     
WORKSPACE
    The absolute path of the directory assigned to the build as a workspace.
     
JENKINS_HOME
    The absolute path of the directory assigned on the master node for Jenkins to store data.
     
JENKINS_URL
    Full URL of Jenkins, like http://server:port/jenkins/
     
BUILD_URL
    Full URL of this build, like http://server:port/jenkins/job/foo/15/
     
JOB_URL
    Full URL of this job, like http://server:port/jenkins/job/foo/
     
SVN_REVISION
    Subversion revision number that's currently checked out to the workspace, such as "12345"
     
SVN_URL
    Subversion URL that's currently checked out to the workspace.
     

Clever or Ghetto: A way to "test" private methods in C#?

You could make all of your private methods protected and then in your test project make an object which inherits from your object that has the protected methods. You then have both encapsulation and testing. Is this legitimate? As I think about it, I suppose the child object for testing would have to have public convenience methods that one could call which would just fall over to the projected methods. Hmmm. Now my idea is getting a little too complicated. Good morning.

Saturday, September 28, 2013

PostMan is a Chrome extension for testing Web APIs.

It came up in the talk I mention here and sure seemed a lot less noisy than Fiddler. You hit APIs with it (send dummy data for testing) and then you see the JSON you get back. That's it. Get it: here

weinre for droid

weinre (pronouced winery) is a debugging tool for Android. A lot of the tools rolled for Google Chrome are rerolled into weinre which runs on a Node server.

Zamzar still exists for free PDF generation.

Go to zamzar.com. Hand it a word document. It will eventually email you back a PDF!

Knockback.js

...is for using Knockout and Backbone in tandem! Eric Anderson mentioned that Backbone is better than Knockout for REST integration. People like Knockout over Backbone as it is less verbose. Meh. Have your cake and eat it too.

numeric type unification!

I finished the bit of this that is on dynamic and I now see two uses of it. The first is simple, you may hand a dynamic object to a method which takes a parent and then overload the method with a method which takes a child and if the dynamic object is of the child (has a matching runtime type) it will fall into the child's method when the method signature is called and will otherwise fall into the parent's signature (assuming that the dynamic type is at the very least of the parental type or one of its other child types). Numeric type unification is the other use for dynamic. Hand two dynamic objects into a method and then do mathematics against them. Join them with a + and hand the value back, etc.

Did you know that ASP.NET Web API controllers return serialized JSON by default for their methods' return values?

I seems like I did know this, but I got reminded of it Thursday night and it surprised me a little. I made this example today:

using System.Collections.Generic;
using System.Web.Http;
namespace WebApiExperiment.Controllers
{
   public class ExperimentController : ApiController
   {
      public Dictionary<string, int> Post()
      {
         var dictionary = new Dictionary<string, int>();
         dictionary.Add("foo", 1);
         dictionary.Add("bar", 2);
         dictionary.Add("baz", 3);
         dictionary.Add("qux", 4);
         return dictionary;
      }
   }
}

 
 

I latched ahold of the "dictionary" in JSON form from a view as seen below. I tried at first to make a dictionary of int,string instead of the other way around, but there was then no way to call into the serialized blob that returned in a shape like so: result.1 (result.foo is golden however)

<script src="/Scripts/jquery-1.8.2.js"></script>
<script language="javascript">
   $(function () {
      myAsynchronousThing();
   });
   function myAsynchronousThing() {
      $.ajax({
         type: "POST",
         url: '/api/Experiment/',
         dataType: 'json',
         success: function (result) {
            alert(result.qux);
            $('#result').html(JSON.stringify(result));
         }
      });
   }
</script>
<div id="result" style="z-index: 10;"></div>

 
 

I bring this all up because I saw Blake McCabe speak at Polyglot Programmers on Thursday night. He presented on an app he made that returned serialized IEnumerable collections. He was calling the ASP.NET Web API from jChartFX charts and they were cool too.

I saw Jason Harmon speak on Behavior-driven development at the Austin API meetup at uShip on Wednesday night.

He asserted that BDD* (behavior-driven development) is not good for testing and no rival to TDD (test-driven development). Mr. Harmon did argue that the Gherkin descriptive rules and their Given/When/Then imperative style are beneficial for articulating how an application works in a layman's way in lieu of a syntactical way, thus allowing DDD (domain-driven design) concepts to bubble up into something visible to non-technical minds. He has a slide with BDD, TDD, and DDD sitting within three separate and overlaying circles. He suggested that you needed all three intertwined and that they should all love each other (my words, not his). Another slide suggested:

  • Devs know how to build it
  • Testers know how to test it
  • Product knows how to sign off
  • Documentation has a head start
  • Stakeholders know what they're getting

 
 

Yes! I managed to make the ordered list above without having the bullets from the ordered list overlay the floating image I have of Jason Harmon in Internet Explorer. That has been a problem in all of my other postings of late. Now the bullet points are just hidden beneath the image and I can live with that. Anyways, I digress. Tools for BDD include:

  • Cucumber is for Ruby.
  • Cucumber-JVM is for Java.
  • SpecFlow is for ASP.NET
  • Lettuce is for Python

 
 

An imperative style example follows. It gives a readable English description of how a product behaves or how a product will eventually behave when the spec is met. There is also a declarative style to Gherkin which is less verbose and more abstract, but the example below is of the imperative style instead.

Scenario: Get nearby places name
   Given I use the geonames host
   When I access the resource url "/findNearbyPlaceNameJSON"
   And I provide parameter "username" as "jharmon"
   And I provide parameter "lat" as "30.4754724"
   And I provide parameter "lng" as "-98.1564068"
   And I retrieve the JSON results
   Then then status code should be 200
   And it should have a list "geonames"
   And the list should have at least 1 item

 
 

Circling back to my mid-blog-posting distraction, I will offer that I use the following HTML for the image you see:

<div style="width: 260px; height: 830px; float:left;">
   <div style="width: 620px; height: 830px; margin-left: -380px;">
      <div style="width: 620px; height: 830px; z-index: 10; position: absolute;">
         <img src="http://www.tomjaeschke.com/blog/JasonHarmon.jpg" />
      </div>
   </div>
</div>

 
 

*Addendum: Mr. Harmon tweeted me with: @jaeschke Great writeup, but 1st sentence lost me. To clarify, BDD is good for AC testing, TDD is good for unit testing. Different layers :)

Push through new requests for materials for work orders in Oracle E-Business Suite.

From the home page of the Oracle E-Business Suite web interface click upon "Receiving Transactions (Inventory : Transactions : Receiving)" at the upper right to spawn a Java Form (you're going to need Firefox) for pushing through requests for new materials for work orders. If you are warned that the plugin you are about to use is unsafe, just press forward and use the plugin nonetheless.

In the Java Form you will first be asked to pick an organization. Pick an organization. Windows for "Find Receiving Transactions" and "Receiving Transactions" will appear. Just close them. Then navigate to Setup under Inventory in the remaining window.

Under Setup, navigate to Interface Managers beneath Transactions.

Either double-clicking here or picking Launch Manager from the Tools menu should spawn the Interface Manager window. Click on "Cost Manager" and then pick Requests from the View menu.

Addendum 10/4/2013: It may be "Material transaction" instead of "Cost Manager" that you should click upon. I'm not certain now.

Click the Find button on the dialog which appears, this should start the approval process.

Friday, September 27, 2013

Today marks Google's 15th anniversary!

We are approaching out own 15th anniversary at @hand as well. The management has asked that we dig up old photos of ourselves from 1998. Where were you in in 1998? 15 years ago today I had just begun working at a now dead multimedia company called DECA, Inc. (Drury Engineering & Computer Art, Incorporated) in Houston, Texas. This photo was taken there before the year ended by Robert Messer.

I looked at my journal entry from 15 years ago and it looks like that day (9/27/1998) was the day I saw the Robert DeNiro movie "Ronin!"

How do I make a bootstrapper project for IoC in an ASP.NET/C# Solution? (please reply)

Guys, I am used to a solution which has separate projects for, the UI, the core, and the infrastructure. But, in looking over the shoulders of others, I know there are also solutions that have a separate bootstrapper project exclusively for managing the IoC relationships in the solution. In these scenarios, does the UI inherit from the bootstrapper which inherits from the infrastructure? Does the bootstrapper get hit first and send routing stuff into the UI? (That seems less likely.) Thoughts?

Thursday, September 26, 2013

An iPhone Web Clip is a shortcut to a specific website or web page that can be created in the iPhone web browser and stored on the iPhone's home screen.

The "Add to Home Screen" trick is probably an example of how to make a web clip. The description in the title of this blog posting comes directly from here verbatim.

Addendum 9/27/2013: The above may be dead wrong. It got voted down on Reddit. I found on Wikipedia: In addition, Mac OS X v10.5 "Leopard" released in late 2007, includes new widgets. One of these is Web Clips, which allows any user to turn a rectangular section of any webpage into a widget (This, however, only works with Safari). The widget updates as the website does, and all links and other interactive material in the widget's selection of the webpage works as if the website is being accessed from Safari. Another new widget is Movies, which allows users to find currently playing movies at local theaters, view trailers, and purchase tickets directly from Dashboard. Wait, now I've found this which reinforces what I first found. I suppose I shouldn't blog about things I've just heard about in passing based on my own "Google research." Alright, now I'm at work and the smart guy who told me about web clips reinforced my original belief. I guess haters are gonna hate on Reddit. I am glad I went through this drama however, because now I've learned of these metatags for managing web clip icons:

<link rel="apple-touch-icon" href="/custom_icon.png"/>
<link rel="apple-touch-icon" href="touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png" />
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png" />

Odd fonts don't work well in Chrome. There is no anti-aliasing.

...and by odd I mean the stuff you fish for with @font-face and not the web-safe fonts.

sticky positioning

Per this sticky positioning is of a new kind of CSS position value (like but not like fixed and absolute) which may be called like so:

.sticky {
   position: -webkit-sticky;
   position: -moz-sticky;
   position: -ms-sticky;
   position: -o-sticky;
   top: 15px;
}

 
 

This is a hack for making headers and footers consistently hug the top or base of a visible area on a web page even when one scrolls to another place on the page. The movie here shows off what I mean. You will have seen this trick on smartphone-friendly versions of web sites and not upon "regular" web sites. This is a HTML5 mobile space UX thing. There are also ways to chase this with JavaScript.

I don't understand how to universally check for connectivity yet.

One of the guys I work with shared this link on how iOS7 behaves and misbehaves with regards to HTML5. It is factfinding done by the Sencha guys. You will notice a callout screaming: "We recommend that organizations standardized on HTML5 development, hold off on upgrading to iOS 7 until an update fixes these issues." ...and that says lots, eh? We were just talking about this in our standup meeting and the usual way of checking to see how many bytes of connectivity are being returned on an iPhone in Safari and using that to determine if one has a connection or not (zero bytes means not) is messed up in iOS7. Note that in Android one has to check a different way too and that outside of smartphoneland one may just use navigator.onLine perhaps like so. I don't understand how to universally check for connectivity yet. I am just now realizing it is not trival.

Unicode characters break String.length in JavaScript.

Consider:

<!DOCTYPE HTML>
<html>
<head>
   <meta charset="utf-8">
   <title>My Test</title>
</head>
<body>
   <div id="first">this and that</div>
   <div id="second">this & that</div>
   <div id="third">this &amp; that</div>
   <script type="text/javascript" src="jquery-1.8.2.js"></script>
   <script type="text/javascript">
      $(function() {
         var first = $('#first').html();
         var second = $('#second').html();
         var third = $('#third').html();
         alert(first.length);
         alert(second.length);
         alert(third.length);
      });
   </script>   
</body>
</html>

 
 

You would think that the three alerts would contain first a thirteen, second an eleven, and finally another eleven. Instead fifteens are returned instead of the elevens! A coworker mentioned yesterday that Unicode characters break String.length in JavaScript. I'm not sure exactly what he had in mind, but in doing some experimenting, I did find this dirtiness. However, I found other places where the dirtiness does not rear its ugly head. Below an eight, a seven, and a seven are returned as expected:

<!DOCTYPE HTML>
<html>
<head>
   <meta charset="utf-8">
   <title>My Test</title>
</head>
<body>
   <div id="first">Jaeschke</div>
   <div id="second">Jäschke</div>
   <div id="third">Jæschke</div>
   <script type="text/javascript" src="jquery-1.8.2.js"></script>
   <script type="text/javascript">
      $(function() {
         var first = $('#first').html();
         var second = $('#second').html();
         var third = $('#third').html();
         alert(first.length);
         alert(second.length);
         alert(third.length);
      });
   </script>   
</body>
</html>

 
 

This behaves exactly like the code before it too, returning 8, 7, and 7 as is ideal:

<!DOCTYPE HTML>
<html>
<head>
   <meta charset="utf-8">
   <title>My Test</title>
</head>
<body>
   <div id="first">Jaeschke</div>
   <div id="second">J&#x00E4;schke</div>
   <div id="third">J&#x00E6;schke</div>
   <script type="text/javascript" src="jquery-1.8.2.js"></script>
   <script type="text/javascript">
      $(function() {
         var first = $('#first').html();
         var second = $('#second').html();
         var third = $('#third').html();
         alert(first.length);
         alert(second.length);
         alert(third.length);
      });
   </script>   
</body>
</html>

Wednesday, September 25, 2013

Disable phone number links in Safari!

Don't you hate it when you make a web site wherein a digit sits by itself in a div and your iPhone decides the number is a phone number and makes it a hyperlink? Me too! Luis Sanchez, a coworker, told me today about a trick to turn this "feature" off in Safari however. It is to use a metatag like so:

<meta name="format-detection" content="telephone=no">

 
 

This is best thing I've learned all month!

540

...should be used as a magic number to judge if a device is a smartphone (or smart watch I suppose) in lieu of 600 as I had thought before. This has come from the team I work with as the better way to go. What is more, one should not make this decision based upon browser width alone, but should measure against browser width if it is less than browser height but browser height if it is less than browser width. I suppose the measuring has to be done in JavaScript as Bryan Harclerode mentioned today that my media queries CSS approach is not going to behave itself in every environment. (The reason to use 540 instead of 320 as a bellwether for whether or not to show that left nav or just put some links along the screen's bottom is to accommodate Android environments and not just iPhones.) In Androidland, the discrepancy between CSS pixels and device pixels can make CSS3 media queries misbehave it seems. Both min-width and max-device-width may be "sick." Disregard my blog posting on 600. 540 is the new 600.

Tuesday, September 24, 2013

switching from Oracle Asset Management to Oracle Asset Management

If you try to log into a new instance of Oracle Asset Management (of the Oracle eBusiness Suite ERP) at a new server via the browser, switching from a different instance on a different server, you may hit a brick wall. Try closing out the browser and opening it back up again. There are some cookies or something that get cached which may cause heartache in this scenario. It makes me cranky.

Home (Maintenance Super User, Vision Operations)

If you log into Oracle Asset Management (of the Oracle eBusiness Suite ERP) as a maintenance superuser and you see a great series of links instead of the familiar tabs reading...

  1. Home
  2. Assets
  3. Work Requests
  4. Work Orders
  5. Stores
  6. Budget Forecasts
  7. Failure Analysis
  8. Construction Units

...you may get back to these tabs by clicking "Home (Maintenance Super User, Vision Operations)" at the upper right.

Where to add TNS names.

Use Agent Ransack to search your PC for "tnsnames.ora" as this file should have your TNS names. Edit in Notepad or Notepad++. Add a new entry like so:

MYTNSNAME =
   (DESCRIPTION =
      (ADDRESS_LIST =
         (ADDRESS = (PROTOCOL = TCP)(HOST = FOO)(PORT = 1521))
      )
      (CONNECT_DATA =
         (SERVICE_NAME = VIS)
      )
   )

Monday, September 23, 2013

"Add build step" under the "Configure" settings in Jenkins...

This may be used to add another build step such as calling a NAnt build. Two such steps are shown in the image below. The "Execute shell" and "Invoke Ant" steps below may be drug on either side of each other by the sets of 16 grey dots at their titles to reorder the build order. The "Execute shell" step may be run to use a GRUNT script with a "Command" setting such as this:

cd build/foo
npm install

What is the difference between dependencies and devDependencies?

devDependencies will get installed from a npm install foo command. These may include testing tools like mocha which are nice to have but not strictly needed to run the npm package at hand. dependencies are must haves. If there is a way to install a npm module without the means I just suggested, I do not yet know what it is, but I get the impression that a simpler way exists based upon things I've read at:

As suggested here devDependencies should be listed as a collection of associated package names and version numbers. Node is able to crawl what is registered at its "registry" to it to find these. dependencies look exactly the same. Also, one may, instead of a version number, give a url to a gzipped tarball.

npm publish http://www.example.com/foo.tar.gz

...may be the command to push an npm package up to "the registry" in node.js per this.

The "main" specification within package.json will denote which .js file to use as the gateway to an npm package.

"main": "foo/bar"

 
 

...for example will try to find "bar.js" in the "foo" folder. The module.exports object specified in the .js file specified in main will be returned. For example:

module.exports=baz;

 
 

...will return a baz variable which might be newed up like so:

var baz = {};

 
 

...and may have functions bolted onto it like this:

baz.run = function() {
   return "qux!";
};

new up numerous variables on the same line in JavaScript

var foo = {}, bar, baz, qux = 42;

npm does not stand for anything. It is not an acronym.

This FAQ says verbatim: The first seed that eventually grew into this flower was a bash utility named "pm", which was a shortened descendent of "pkgmakeinst", a bash function that was used to install various different things on different platforms, most often using Yahoo's yinst. If npm was ever an acronym for anything, it was node pm or maybe new pm.

People still use tarballs!

When specifying dependencies or devDependencies in a package.json file, instead of specifying the version number of a package for Node.js to go procure by itself, you may just specify a tarball hosted somewhere out on the web! I suppose this is one way to install your own home-rolled stuff as dependencies. Here is how the markup could look. (This example also includes using GIT for managing dependencies/devDependencies.)

"dependencies": {
   "foo" : "http://www.example.com/foo.tar.gz",
   "node-fogbugz": "git://github.com/icodeforlove/node-fogbugz.git",
   
etc...

If you are wondering what a .tar.gz file is in lieu of just a .tar tarball, well, so was I. Partway down this the following is given verbatim:

  1. tar puts multiple files into a single (tar) file.
  2. gzip compresses one file (only).
  3. So to get a compressed archive, you combine the two

 
 

.gz is "gzip" ...get it?

Specify a NAnt script to run in Jenkins!

  1. Log in and also go to the project in no particular order.
  2. Click on "Configure” at the left navigation.
  3. There is a bunch of stuff to configure here. Scroll down to: "Execute NAnt Build" (a draggable area below "Build"*)
    • Enter the path to the NAnt build file relative to the head of the repository's file structure you are using at the fill-in-the-blank field for "Nant Build File” ...an example could be: build/nant.build if you have a "build" folder at the root of your repository and a "nant.build” file within it.
    • Enter the targets to be run at: "Targets”

*If this build step does not exist you will need to add it. You may have to install a NAnt Plugin to get this to work...

Alien Blue is a Reddit Client for iOS.

Reddit is a news/entertainment website where users submit things and the submissions get voted up or down.

Sunday, September 22, 2013

The distinction between static and runtime types in C# is important.

More from this, if you make a new Dog type object in C#, its runtime type is Dog and its static type is Dog. If you upcast the Dog to an Animal then the runtime type is still dog and the static type is Animal.

Call a field that contains a delegate in C#!

class Dog : Animal
{
   public Action Woof = () => Console.WriteLine("woof!");
}

 
 

This is more fun from this video and Joe Albahari uses it like so:

dynamic x = new Dog();
x.Woof();

"upcast" to dynamic

Going through this a smidge more, I find I want to offer an easier example of casting to dynamic than what I offered here. Observe:

namespace Whatever.Whatever
{
   public static class TortureChamber
   {
      public static string GetScreams(dynamic guest)
      {
         return guest.Scream();
      }
   }
}

 
 

We may use our TortureChamber by handing in any object that has a public (or perhaps internal) Scream method on it, such as a Clown:

namespace Whatever.Whatever
{
   public class Clown
   {
      public string Scream()
      {
         return "Honk! Honk! Honk!";
      }
   }
}

 
 

If we do something like this...

Clown clown = new Clown();
string result = TortureChamber.GetScreams(clown);

 
 

The result variable is going to end up with "Honk! Honk! Honk!" in it. The runtime process will try at runtime to find a Scream method upon the dynamic object given our code in TortureChamber, but not until that method is called. If the public (or perhaps internal) Scream method is not there on the type cast to dynamic at the method signature, then the compiler will nonetheless not "know" to complain about it. The harsh reality of the missing method won't be exposed until runtime. There is no compiler safety. That is what dynamic is all about! An example of a runtime error might be:

'Whatever.Whatever.Mime' does not contain a definition for 'Scream'

 
 

This happens at runtime if Mime has no public (or perhaps internal) Scream method like so:

namespace Whatever.Whatever
{
   public class Mime
   {
   }
}

 
 

This would cause the error:

Mime mime = new Mime();
string result = TortureChamber.GetScreams(mime);

Saturday, September 21, 2013

make an asynchronous call midstream in a procedural process within JavaScript

A procedural process is going to have to be broken into two functions around an asynchronous call or more yet if there is more than one such call in a series of happenings. For example consider this process:

  1. We start with the number 1.
  2. We fish for the number 2 asynchronously and add it to the 1 when we get ahold of it.
  3. We then add the sum of the 1 and the 2 to the number 3.
  4. We throw an alert with the sum of the 1, the 2, and the 3 in it which should be equal to 6.

 
 

Well, the following approach will NOT work:

$(function () {
   myProcedure();
});
function myProcedure() {
   var myValue = 1;
   myValue = myAsynchronousThing(myValue);
   myValue = myValue + 3;
   alert(myValue);
}
function myAsynchronousThing(myValue) {
   $.ajax({
      type: "POST",
      url: '/GoGetTwo/',
      dataType: 'json',
      success: function(result) {
         return myValue + result.Whatever;
      }
   });
}

 
 

In the above approach, the myAsynchronousThing function will return undefined and the alert will ultimately throw NaN. That is because the value in the success callback within myAsynchronousThing returns asynchronously. I struggled today to find a way to force this value to return as shown in a scenario above, but everything I saw in my Googling ultimately suggested that I needed to give up on a strict need to return something synchronously by way of somehow manhandling the asynchronous into the synchronous. The function that would use the asynchronous call just needs to be broken up into two bookend functions around an asynchronous call like so:

$(function () {
   myProcedure();
});
function myProcedure() {
   var myValue = 1;
   myAsynchronousThing(myValue);
}
function myProcedureContinues(myValue) {
   myValue = myValue + 3;
   alert(myValue);
}
function myAsynchronousThing(myValue) {
   $.ajax({
      type: "POST",
      url: '/GoGetTwo/',
      dataType: 'json',
      success: function(result) {
         myProcedureContinues(myValue + result.Whatever);
      }
   });
}

 
 

The above will work just fine. Also, a variation on the above is:

$(function () {
   myProcedure();
});
function myProcedure() {
   var myValue = 1;
   myAsynchronousThing(myValue, myProcedureContinues);
}
function myProcedureContinues(myValue) {
   myValue = myValue + 3;
   alert(myValue);
}
function myAsynchronousThing(myValue, useMeAtTheEnd) {
   $.ajax({
      type: "POST",
      url: '/GoGetTwo/',
      dataType: 'json',
      success: function(result) {
         useMeAtTheEnd(myValue + result.Whatever);
      }
   });
}

 
 

As an aside, do you know who Chronos (or Khronos) is in Greek myths? He is the God of time. Hence asynchronous and synchronous are named for him (or perhaps a more generic version of the same Greek word for time) as are words like chronological. He doesn't look very happy in this image. Maybe it's my first (bad) implementation in this blog posting that has him cranky. I don't see why the others would make him sour per say. I do tend to annoy.

Having typed up this blog posting, I am now realizing that the image above, which comes straight from the Wikipedia page I give a link to, has 666 on it! Also, I give three separate examples which each try to return a 6. Spooky! I promise this is coincidence and not some hidden satanic agenda on my part. :P I could try to change the content above, but I'm just going to let it be.

there will now be a whopping great intermission

JavaScript ten second pause:

var theFuture = new Date();
theFuture.setSeconds(theFuture.getSeconds() + 10);
while (new Date() < theFuture) {
}

.then()

jQuery's deferred stuff allows you to chain a .then() onto things like so:

$.ajax({
   type: "POST",
   url: '/whatever/',
   dataType: 'json',
   success: function (result) {
      alert('fires first assuming a synchronous scenario');
   }
}).then(function () {
   alert('fires next assuming a synchronous scenario');
});
alert('fires first assuming an asynchronous scenario');

 
 

By the way, I am bringing this up because I am struggling to find a good way to force an asynchronous call to resolve before proceeding procedurally. If you are in control of the call and it is not something in another library getting wrapped by your logic, you can always just specify async: false like so:

$.ajax({
   async: false,
   type: "POST",
   url: '/whatever/',
   dataType: 'json',
   success: function (result) {
      alert('fires first assuming a synchronous scenario');
   }
}).then(function () {
   alert('fires next assuming a synchronous scenario');
});
alert('fires first assuming an asynchronous scenario');

Friday, September 20, 2013

one billion dollar quarterly loss!

BlackBerry Limited (formerly RIM or Research in Motion) is preparing the public for the news of an one billion dollar quarterly loss as of today. Eighty percent of shipped BlackBerry 10 phones are expected to be returned per a CNN.com quote from a Neeraj Monga! Wow, when I think back on how New Coke tasted in the 80s it suddenly seems like it didn't taste all that bad. There are flops and then there are all-stakes-in-desperation-measures which are flops. Ishtar and Howard the Duck seem like pretty good movies all of a sudden. The Edsel smartphone company is to let go of forty percent of its own (around 4,500 warm bodies) and by "Edsel smartphone company" I mean BlackBerry Limited. What a fallout! You know what sounds tasty right about now?

When Lou Gerstner took over at IBM he was smart enough to see that John Fellows Akers' idea of breaking the company up into a bunch of smaller companies was foolish. The one thing that Big Blue had going for it was the big part. It could still do big things, they would just become different big things. Gerstner transitioned the company from computer sales to consulting to an extreme wherein "International Business Machines" was sort of a misleading name and in doing so he saved a sinking ship. It would have been foolish NOT to course correct upon taking the helm, because the longer he might have held onto the dying business model the less likely he likely would have been (when the denial of the modern reality wore off) to be able to scramble to safe ground. At BlackBerry they have forfeited forty percent of the company in denial.

a brief history of covariance

http://www.albahari.com/nutshell/WhatsNewCs4.aspx offers, amongst many other things, a brief history on what has changed over time in C# with regards to covariance. It gives a Jon Skeetesque history lesson. Covariance at its simplest happens when one implicitly upcasts from a child to a parent (at perhaps the hand-in to a method signature), but the more interesting and, yes, painful things to think about have to do with implicitly upcasting collections of children to collections of their parent. You could do this with an array, the de facto go to collection (are there any others before C# 2.0? Session/ViewState perhaps?) before generics in C# 1.0. You could cast an array of Scorpions to an array of Arachnids, but, as Ben Albahari portrays it in this video, this came with significant problems. One could take in an array of Arachnids at a method signature and be opening the door to really be taking in an array of Scorpions. Within the method if one replaces one of the Arachnids with a new Arachnid, in the case of an array of Scorpions being handed in, the method is going to break due to a type mismatch. It is also perfectly compiler-safe to replace one of the Arachnids with a different child type in this method, such as a Spider, but this too invites trouble and run-time blow-ups. To make compiler-safety for generics covariance closer in keeping to run-time reality for generics in the next version of C#, the upcasting of collections was largely forbidden. The only way you can really do it is by way of the where keyword like so:

void Write<T> (List<T> foo) where T : Arachnid
{

 
 

To insert a specific type into our collection we also have to go through some pain (which is better than being allowed to slip in something explosive haphazardly in an easy manner):

foo[0] = (T)(object) new Spider();

 
 

As of C# 4.0 there is support for more implicit covariance in generic interfaces such as IEnumerable which allow a collection to be handed in but not significantly doctored up after the fact. The pendulum swung back the other way a little bit.

status codes cheat sheet!

http://servererrorcodes.com/400/ seems like a good cheat sheet on the status codes of webland. It tells us:

100isContinue Server Code
101isSwitching Protocols
200isOK Server Code
201isCreated
206isPartial Content
301isMoved Permanently
302isFound Server Code
304isNot Modified
307isTemporary Redirect
400isBad Request
401isUnauthorized
403isForbidden
404isNot Found
500isInternal Server Error
501isNot Implemented
502isBad Gateway
503isService Unavailable
504isGateway Timeout
505isHTTP Version Not Supported

Addendum 10/19/2014: I realize this list is incomplete. For example 204 is "No Content" and 410 is "Gone" per this.

runscope looks like it is for API troubleshooting

It looks like one calls out to runscope instead of an API an then runscope passes through to the API (and back) based upon what i see at https://www.runscope.com/. Works with:

  1. Ruby
  2. Python
  3. JavaScript
  4. cURL
  5. Android
  6. iOS
  7. C#
  8. Java
  9. PHP
  10. Go
  11. COBOL

Thursday, September 19, 2013

When you accidentally write on your whiteboard with a sharpie...

  1. scribble dry erase marker over the top of it
  2. wait thirteen minutes (or so)
  3. erase!

I just found this trick by Googling and ending up at http://www.wikihow.com/Remove-Permanent-Marker-from-a-White-Board and I endorse this approach. By the way, this is also the way to get rid of really old, stubborn, dry erase marker scribblings which have been left to sit for too long.

Wednesday, September 18, 2013

Don't try to wrap a list around a floating div.

It won't behave well in modern Internet Explorer. (see: this) I'm kicking myself. How did I make this mistake?

good morning Compatibility View

Check out http://tom-jaeschke.blogspot.com/2013/09/i-saw-net-ninjas-toolbelt-talk-by.html in Internet Explorer 10. Toggle between "Compatibility View" being on and off. (Find this in the "Tools" menu.) Watch the numbers in the ordered list I have end up on top of the photo I have when not in Compatibility View. Grrr. Wait a minute. As I type this, I am realizing that Compatibility View must signify IE7. If I press F12 in Internet Explorer, I can click on the place that says "Browser Mode: Whatever" in the pane that pops up to change Internet Explorer to mimic various older versions. It is really only IE7 where my ordered list looks good. Hmmm... more soon.

Tuesday, September 17, 2013

Don't be creative and don't be lazy in SEO.

More content from this talk (and beyond):

Don't be creative. Creative people are not the ones who should be driving the SEO on a web site. The content experts should instead. Creative people have an innate need to try new things and push the envelope. This isn't what you want. Find the winning play and keep repeating it. Make small tweaks instead of delving into wild tangents. One place people used to be creative which is no longer as applicable is in link building. From 2004 to 2009 these should have been your SEO priorities from highest priority to lowest priority:

make the website's pages accessible to engines
build links to individual URLs for higher rankings
optimize on-page keyword usage/targeting
create content people want to consume and share
optimize metadata, schema, rich snippets, etc.

This is not the modern reality however (as we will see momentarily). Look at analytics for what people are looking for in their search results. If you have a search engine at your own site, record what people search for and, in particular, pay attention to those search results for which no hits are being matched. What isn't the public finding at your site? You may need to try to target the appropriate search engine for your market. Google has upwards of sixty percent of the search traffic in the United States, but, beyond that, it has nearly exclusive rights in some other nations. Yahoo controls Japan. YouTube is the second most trafficked search engine in the United States. Do not get creative with a cluster bomb strategy across numerous engines. If you think of the typical American male grocery store shopping behavior of: get in, get what you want, get out ...well, this logic is what everyone thinks when searching. Cater to it. Don't complicate it. The online public will spend time browsing and lollygagging in other venues, but not in search. Creative people should be channeled towards the other venues, not search. PR peeps are a little better suited to SEO than creative types, but ultimately content is king not hype and SEO marketers should be filling their own niche, you know?

 
 

Don't be lazy. Laziness will take you down a black hole. If you get a gym membership you will probably want to have it in your head to go to the gym on a regular basis. If you just plan to go to the gym when you feel like it you won't be too productive there. The same is true for SEO. Keep a calendar in the name of up-keeping your content. If you read a few articles a day related to your business, write a paragraph on your thoughts once every three days and reference the articles in your copy. This is all you need for a blog posting. Overall, these should be your SEO priorities from highest priority to lowest priority:

create content people want to consume and share
make the website's pages accessible to engines
optimize on-page keyword usage/targeting
optimize metadata, schema, rich snippets, etc.
build links to individual URLs for higher rankings

Google has done away with its tool for gauging the viability of would be search terms, and most of the other major search engines have either followed suit or let their widget fall into disrepair. There is a not-free player in this space called Human Discovery, but for the most part you will need to learn to walk without this crutch going forward. Type in would-be search terms into Google itself and see how the autocomplete behaves. This is the new (marginally opaque) Ouija Board. Be green, be thrifty, and be rich. Being green and thrifty means recycling content as suggested above and also retweeting and acknowledging those who interact with you in kind. Be rich means not being too lazy to use images, video, news, etc. Seventy percent of all search results come from blended search anymore in lieu of a "Google Classic" approach. Don't be lazy in crafting content. Ask yourself: How will success be measured, am I on topic, and is it best to spend time spinning new content or reinforcing existing content? Anyways... you're up. Pull up your blog. It's time to start jaw-flapping ...with something substantive to say.

Mercurial chaser commit

When fixing a tangled mess this way in Mercurial/TortoiseHg, one may end up with two branches joining in a hollow/white bubble at the top of the TortoiseHg visuals. Others may end up yet seeing two distinct heads however. This means you still need to commit on some level. I made a superfical commit to make sure I really resolved things in a mess I made a moment ago. I know this sort of chaser is ghetto.

Also, please note: I don't drink or encourage drinking. It's just a funny picture. It fits, no?

a better posting on JavaScript's !! thing

It has been pointed out to me that this posting is bad. The double exclamation points are not an operator in and of themselves. Instead, they are two ! operators. This scenario...

return !foo ? 42 : 13;

 
 

...is going to return 42 if foo is zero/false/undefined (see this for more) and 13 otherwise. When we add an extra exclamation mark like so...

return !!foo ? 42 : 13;

 
 

...we are just doing the opposite. The !! is akin to the null coalescing operator of C# in effect (in this example in tandem with the question mark in that the question mark starts behaving like the double question marks of C#) and thus is a little easier for someone like me who knew C# before JavaScript to read. The first (right) exclamation does a conversion from what may be to a boolean type. The second (left) exclamation just flips that value. Thanks to grnndaddy for this explanation.

max-width

...is the opposite of min-width so to speak in media queries. It does exactly what you think it might do.

@media (max-width: 600px) {
   .whatever {

 
 

This suggests that max-device-width (in contrast to max-width) would measure the width of the device itself (and not the active area within the browser) and that it, yes, it does not react to browser resizing. Lame.

Do you want to inspect the HTML and CSS of specific elements with Google Chrome Developer Tools?

To do this, just right-click on a desired element (in Google Chrome) and pick "Inspect element" from the pop-up menu which appears. This will also allow you to scrape out the element's HTML too. I have often wondered how Firefox could keep up its feature set with the competition of Microsoft Internet Explorer and Google Chrome. I once found an article about how the keep up was possible that was so complicated that I just gave up on trying to understand it. Whatever. With this feature, for me, I see no reason to use Firebug (the Google Chrome Developer Tools of Firefox) again. This really extinguishes Firefox in my mind.

emasculation of HTML tables via... display: block;

Slap this CSS on a table! If the table had one row of six cells, the cells will now each behave like div tags following each other vertically. Everything that was tablelike about the table is gone. Unbelievable! This comes from another smart person I work with, Stepan Riha. I am no slouch to CSS and I knew you could manhandle much, but this really surprised me.

.foo
{
   display: block;
}
 
.foo tbody
{
   display: block;
}
 
.foo tr
{
   display: block;
}
 
.foo tr td
{
   display: block;
}

600

Addendum 9/25/2013: Disregard what is below. 540 is the new 600.

One of the smart people I work with, Bryan Harclerode, mentioned today that six hundred is a good number to use when gauging browser width (in number of pixels) when trying to draw a line in the sand to determine if one is viewing a browser on a mobile device or a bigger tablet or laptop. This is better than 320 as it takes Android stuff into account.

dropping $(document).ready in jQuery

$(document).ready(function() {
   yawn();
});

...may be simplified as...

$(function() {
   yawn();
});

pageinit event in jQuery mobile

I found this which touches on the pageinit event which seems to fire off in one page jQuery mobile applications just before a transition to a new page begins. At my work, we are using it like so:

(function() {
   useJQuery();
   function useJQuery() {
      if(!window.$) {
         setTimeout(useJQuery, 100);
      } else {
         $(document).bind('pageinit', function() {
            alert('Yay!');
         });
      }
   }
})();

jQuery's innerWidth() rocks!

$(function() {
   $('body').addClass(($('body').innerWidth() > 320) ? "great" : "meh");
   ($('body').innerWidth() > 320) ? alert('great') : alert('meh');
});

Monday, September 16, 2013

Google searches of four to eight words in length are trending while "traditional" two to three word searches are waning.

Running an eight word long search at Google was practically unheard of nine years ago, but is increasing regular as human beings get more and more used to narrowing in on what they want in a Google search. This means the possibilities for optimizing for keywords have now opened up. The two to three word market will trend towards being more of the domain of pay-per-click traffic. The four to eight word market is for those of us who have SEO chops now. This wisdom came in an Austin SEO talk today at The Flying Saucer where Bill Leake of Apogee Results spoke.

I'll write more about the rest of the talk later on. I offer the really important bit of info above however.

Wednesday, September 11, 2013

make payments from a smartphone

The all-wise Wikipedia says: "Near field communication (NFC) is a set of standards for smartphones and similar devices to establish radio communication with each other by touching them together or bringing them into close proximity, usually no more than a few inches." I learned today that:

  1. Andriod phones make the most of this technology to allow one to make a payment for food at a McDonald's across Bluetooth from a smartphone.
  2. This does not exist in iPhoneland. Apple is supposedly working on something called iBeacon instead per: this

fonts to code with?

Adobe Source Code Pro is a monospaced font for coders addressing some of things that concern them. For example, the lower case L is distinct from a pipe symbol or a capital letter I.

 
 

PragmataPro is comparable:

Zoom 2x

To make the WM 6.5 Professional Client described here appear bigger on your screen:
  1. pick "Configure..." from the "File" menu
  2. go to the "Display" tab in the "Emulator Properties" dialog box which appears
  3. check the "Zoom 2x" checkbox
  4. click the "OK" button

parent/child meter relationships in Oracle's eBusiness Suite

A meter may have a child (called a target) in Oracle's eBusiness Suite. When the parent meter increments the target meter increments proportionately. The target meter values may vary from their parent's per their initial definition, but their values may not be updated independently.

Tuesday, September 10, 2013

no goto in C#

Something that came up in a conversation last night was that VB.NET has gotos. I remember when I was first learning C#, that I took a five day training at New Horizons on C# and was told there was no goto. That was a big adjustment for me back then. Chuckle.

 
 

Addendum 1/25/2014: Please see this as it turns out there is a goto of sorts in C#. I was wrong.

Oracle has sequences where MSSQL has identities.

Don't expect to define a table in Oracle to have an auto-incrementing numeric field. Instead one specifies an integer field and then has to hand in some sequence syntax whenever one writes to the column in the name of making a number count upwards.

I saw Gregory Beamer speak on In-Memory OLTP last night.

OLTP (On-line Transaction Processing) is the stuff of a normalized schema. In-Memory OLTP, as described by Gregory Beamer last night at the Austin .NET User Group is really just the art of keeping tables and stored procedures in memory (after being read out of .dlls). It is something coming in MSSQL 2014. This feature is not unlike Memcached and has ACID Durability by way of using FileStream to push data back to cache. The reason to use this feature to begin with is to eliminate slowness due to lock contention or CPU bottlenecking. The in-memory content may perform multiple times faster and alleviate the pain of a chokepoint. To use this feature at a database one must empower it through a few alterations like so:

ALTER DATABASE imoltp ADD
      FILEGROUP [imoltp] CONTAINS
      MEMORY_OPTIMIZED_DATA
GO
ALTER DATABASE imoltp ADD FILE(NAME
      = 'imoltp_dir',
      FILENAME='c:\data\imoltp') TO
      FILEGROUP [imoltp]
GO

 
 

Then create an in-memory table like so:

CREATE TABLE [Customer] (
   [CustomerID] INT NOT NULL PRIMARY
         KEY NONCLUSTERED HASH
         WITH (BUCKET_COUNT= 1000000),
   [CompanyName] NVARCHAR(40) NOT
         NULL INDEX [IName] HASH WITH
         (BUCKET_COUNT = 1000000),
   [ContactName] NVARCHAR(40) NULL
)
WITH (MEMORY_OPTIMIZED = ON,
      DURABILITY = SCHEMA_AND_DATA);

 
 

Make the bucket size twice that of the number of rows you think you might have. Triggers and CLR do not exist in the in-memory space. There are no "large objects" either such as varchar(max) or XML blobs either. You cannot alter in-memory tables. You have to destroy them and recreate them to make a tweak. When spinning up an offline instance of MSSQL Server it will take a moment for the in-memory tables to indeed be in-memory, but once they are there they are golden. An in-memory sproc looks like this:

CREATE PROCEDURE [dbo].[InsertOrder] @id INT, @date DATETIME
   WITH NATIVE_COMPILATION, SCHEMABINDING, EXECUTE AS OWNER
AS
BEGIN ATOMIC
   WITH (TRANSACTION ISOLATION LEVEL = SNAPSHOT,
         LANGUAGE = 'us_english')
   
--the guts of the stored procedure go here
END

There is a thirty character limit on names of tables, columns, and foreign key references in Oracle.

What is more, foreign key references by convention have names which include the names of the two tables they associate together plus a few other characters. This means that table names really need to be kept terse. If a column is indexed, then the number of the index, such as a two for the second index, will be, by convention, bolted onto the column name like so: mycolumn_2 ...so here too there is, to some extent, reason to be wary of pushing how long a column name may be up to the thirty character cap.

asset genealogy in Oracle's eBusiness Suite's Asset Management web interface

Following this, I should note that when one removes an asset from a parent asset, what one does is set an end date for a history record kept at a genealogy table. One of the confusing things about the screen for asset swapping is that one may see assets no longer associated with their parents at a parent's lists of assets. One just has to know that child assets shown which have end dates are in fact notes of history and not records empowering an active association. When a new child asset is associated with a parent, the child will get a history/genealogy record that will have a start date but not an end date. Also note that as genealogy records change that a column in the genealogy table does get the "last date of update" column revisited, but the comparable column in the asset table itself is not revised. If a parent is removed or added to an asset, the asset record itself will in no way reflect the change. The metadata in the genealogy table carries this information.

Monday, September 9, 2013

I have finally finished reading C# 4.0 in a Nutshell!

I did it. I read a thousand page (well, 995 pages with a six page Preface) reference manual on C# 4.0! Since I've been reading it everyone has started using C# 4.5 and I've had four different jobs. I was obsessed with reading this book in 2012 and managed to read 700 of the pages before 2012 ended, but this year I've really been burnt out and have been reading at a rate of a page a day. The last quarter of the book is on threading and various patterns for safely locking objects that multiple threads will use. I was pretty checked out in reading that stuff. There is surprisingly another quarter of the book which is on XML stuff. (transforming XML, serializing types to XML, etc.) The other half of the book which was the not the quarter on threading nor the quarter on XMLing was really, really good however. Now I can really said I've read something, though I think one of the lessons from this is not to read a thousand page tomb again. I am much stronger for it. Congratulations to Joseph and Ben Albahari for writing the informative: C# 4.0 in a Nutshell! They are smart men to say the least. Here is what I've learned:

  1. Encapsulation in contrast to the Open/closed Principal
  2. M magic for decimal creation
  3. default values for value types in an array
  4. bottleneck through parent
  5. virtual and override
  6. casting a child class to a parent interface
  7. delegate example
  8. Func example
  9. use Action instead of Func when you wish for a Func to return nothing
  10. multicast delegate example
  11. closures
  12. = () =>
  13. events
  14. Math.Pow
  15. Put methods in a class that require casting to an interface to use!
  16. how getsetters reflect
  17. user interface technologies
  18. DateTimeOffset
  19. using IFormatProvider and ICustomFormatter
  20. using string.Format with flags enums
  21. set the culture of the current thread
  22. Tuples
  23. Process
  24. predicates
  25. Array.ConvertAll shows off the power of delegates
  26. type-changing across .Select
  27. lazy execution of IEnumerable
  28. expression trees
  29. query from one IEnumerable type collection to another
  30. .AsEnumerable()
  31. .AsQueryable()
  32. Upcast to an Interface!
  33. Cross Join Queries and Non-equi Join Queries
  34. expressions in C#
  35. Skip and Take
  36. Join/Distinct/Union/Structs/lookups
  37. Intersect/Union/Except
  38. SelectMany
  39. let
  40. LINQ to XML
  41. XML, XPath, and XSD
  42. XSLT
  43. IDisposable
  44. using
  45. Code Contracts
  46. Contravariance
  47. where T : Whatever
  48. File I/O
  49. Networking Cheat Sheet
  50. remoting
  51. the GAC has priority over the bin
  52. instance method
  53. the parameterless constructor on a base class is always called
  54. attributes
  55. use dynamic to add nonspecific types in C# 4.0
  56. use dynamic to cherry pick more specific types
  57. visitor pattern
  58. dynamic method calls
  59. static state
  60. unmanaged code and the C# extern keyword
  61. #if(!DEBUG)
  62. encrypt and decrypt
  63. signature versus public key handshake
  64. finalizers
  65. threading
  66. write your own equality comparisons
  67. spinning
  68. why use PLINQ?
  69. why not use PLINQ?
  70. asynchronous methods
  71. MarshalByRefObject
  72. unsafe
  73. fixed
  74. handing in delegates to APIs
  75. COM
  76. regular expressions
  77. conclusion

 
 

Addendum 1/25/2014: Please see this as it turns out the post you are looking at is not the last post on C# 4.0 in a Nutshell.

 
 

Addendum 3/14/2014: My reference to C# 4.5 should really be a reference to the ASP.NET 4.5 Framework which uses C# 5.0.

 
 

Addendum 6/2/2014: This is yet another blog entry after I thought I was done blogging of C# 4.0 in a Nutshell.

 
 

Addendum 6/24/2014: This is still yet another blog entry.

 
 

Addendum 3/1/2015: Yet again!

Diff to other repository in Mercurial and TortoiseHg?

The trunk has:
  1. recent coworker changes
  2. a bunch of older changes
  3. the original check-in
Your shelf has:
  1. your changes
  2. recent coworker changes
  3. even more of your changes
  4. a bunch of older changes
  5. the original check-in

How may you do a diff of the two so that you may see..

  1. your changes
  2. even more of your changes

...?

There is not a way to cross compare two repositories like this. Moreover, since you have been periodically merging commits pushed up to the trunk into your own shelf your history is dirty and there is no easy way to do a diff to see only what you changed before pushing it to the trunk. Grrr. The thing to do to prevent this is to not drag in updates to the trunk to your shelf until you are ready to push your own changes to the trunk. Sure, there is a way to unmerge the "recent coworker changes" changeset, but this is much more painful than just approaching working in Mercurial the right way to begin with.

Sunday, September 8, 2013

Temp tables lingering in memory in Mircosoft SQL Server Management Studio queries make me cranky.

I don't know how turn this feature off. I seem to be able to hack around the problem by closing a query window where I've made a temp table and then just opening a new query window. That way there won't be a blow up when I make a temp table I've "already made."

I saw Dan Hollenbeck speak at The JavaScript Austin Meetup Group on "Three Backbone.Marionette/Node.js Apps: Useful Patterns and Lessons Learned."

The talk was on Thursday night. In beginning his talk, Mr. Hollenbeck emphasized a trend towards having more and more logic live at the front end of an application as the JavaScript space blossoms. In Backbone.Marionette SPA applications, Models (Business Logic, SQL) and Controllers (API) live Server-side (Node code I suppose in Dan's scenario), but a bigger piece of the overall pie lies at the Browser-side:

  • Models, Collections (State, AJAX)
  • View Helpers (Cell Render)
  • Routers (URL Glue)
  • Controllers (App Glue)
  • Events (Object Eventing)
  • Specialized Views (UI Eventing, Data Eventing, please see this which Dan Hollenbeck also detailed regarding eventing)
  • App Modules (App Life-Cycle, App Initializers)
  • Layouts (View Composition)
  • Regions (View Management)
  • View Callbacks (UI Widgets, View Clean-Up)

One of the criticisms I've heard of Backbone is that it is abundant with boilerplate code. Dan asserted that boilerplate code is not a bad thing and it is healthy to write it. It keeps your head in the game and allows you to understand what is really going on. You don't want to abstract too much away. The folder structure for a Backbone app looks like: api, docs, models, node_modules, processing, public, routes, ssl, etc. In the public folder are folders for all, css, img, and js. The folders inside the js folder are broken up by function/resource based upon different parts of the domain. This is not how you, strictly speaking, have to keep the contents of the js folder, but rather this is Dan's recommendation for keeping things sane. In eventing, listen from short lived objects, such as view, to a long lived object, such as models, and not the other way around as the other way around may cause a memory leak. View are unaware of the context in which they are being invoked. There are four kinds:

  1. Marionette.ItemView ...for a single object or a collection
  2. Marionette.CollectionView ...allow one to iterate over a collection
  3. Marionette.CompositeView ...tree/leaves/branches
  4. Marionette.Layout ...this is a container that holds the other views, has "slots" wherein you may place other views and if you put a new item in a slot then the Layout view will do the work of disposing of the prior occupant (without causing a memory) leak for you

Please note that a Backbone.Marionette application is a one page application wherein the stateless web suddenly has state and ongoing life. Challenges and benefits come with this. Helpers are used for markup dress-up. Views defer to helpers. Akin to my recent dojo/dojox experience there is an "App" variable in Backbone implementations which is the central player.

var App = new Backbone.Marionette.Application({
   models: {},
   collections: {},
   views: {},
   routers: {},
   lang: {},
   helpers: {},
   layouts: {},
   events: _.clone(Backbone.Events)
});

 
 

Initializers come in many shapes, for example upon the triggering of a view:

//Define Event Handler
App.events.on('car:detail:show', function(car){
   var dialog = new App.views.carDialog({
      model: car
   });
   dialog.render();
});

 
 

Dan refered to data points three tiers deep within the App variable such as App.events.on as "namespaces!" Here is how we would use what we just put in this namespace.

//trigger event to show dialog
var model = new App.models.Car({});
App.events.trigger('car:detail:show', model);

 
 

Another initializer, the Marionette.AppInitializer is executed just once immediately after the application starts:

Add.addInitializer(function () {
   
//Define Event Handler
   App.events.on('car:detail:show', function(car){
      var dialog = new App.views.carDialog({
         model: car
      });
      dialog.render();
   });
});

 
 

A view will/may have an initializer:

App.views.CarDialog = new Backbone.Marionette.ItemView({
   initialize: function(options) {
      this.model = options.model;
      this.collection = options.collection;
      _.bindAll(this, 'onCancelClick', 'onSaveClick');
   },
   ui: {
      wheel: 'input',
      dashboard: 'fieldset#dashboard',
      button: 'button.delete'
   },
   onEventFnc: function(event){
      this.ui.dashboard.hide();
      var wheels = this.ui.wheels.val();
      this.ui.button.button({icons: {primary: 'ui-icon-plus'}}
   },
   template: 'script#car-detail',
   templateHelpers: {
      horsePowerRender: function(horsepower){
         return horsepower + ' HP';
      }
   },
   events: {
      'click span.ui-icon': 'iconClick'
   },
   collectionEvents: {
      'sync': 'render',
      'destroy': 'render',
      'deselected': 'onUnselectionEvent',
      'selected': 'onSelectionEvent',
      'error': 'error'
   },
   modelEvents: {
      'change:wheels': 'renderWheels'
   },
   
//etc...

 
 

Clearly, there is a lot more going on above than just the initializer. :) In closing, an example of a model:

App.models.Car = Backbone.Model.extend({
   urlRoot: '/api/cars',
   shiftTransmission: function(transText){
      var trans = 'U';
      switch(transText){
         case 'park': trans = 'P'; break;
         case 'drive': trans = 'D'; break;
         case 'reverse': trans = 'R'; break;
      }
      this.save({trans: trans}, {
         url: '/api/cars/' + this.get('id') + '/transmission',
         silent: true
      });
   },
   isTransmissionIn: function(transText){
      var gear = this.get('gear');
      switch(transText){
         case 'park': return (trans === 'P')? true : false;
         case 'drive': return (trans === 'D')? true : false;
         case 'reverse': return (trans === 'R')? true: false;
      }
      return false;
   }
});

 
 

Other tools mentioned in this talk:

  1. Underscore.js was being used in Dan's app, of course.
  2. SendGrid for sending emails, an outsourced service.
  3. Loggly for remote logging. If you have an application straddling multiple servers, it may be painful to find the right machine to remote desktop into in the name of checking logs. Use a third party tool for consolidation.
  4. Dan said he tried to work with "X.js" (this is what I heard) and found it painfully complicated. He likes Backbone.js because there is just one page of documentation to read and understand. I wonder if he meant Sencha Ext JS.
  5. The sponsor who bought our pizza was Tech Pines and they have a testing platform for CasperJS/PantomJS headless browser technologies.
  6. DigitalOcean is a cheapo cloud service.
  7. Ember.js used to be called Sproutcore.
  8. Google Chrome Developer Tools were heralded as much better than the Firefox Firebug of yore. One of the things you may do with the tools is monitor how much of a memory footprint a one page web application consumes.
  9. gmail has a 40 to 60 megabyte profile as a one page application. If they can be this big you can go big too. Dan said his apps spike up to around 13 to 26 megabytes of memory.
  10. Twitter Bootstrap and jQuery UI are two of the few and far between providers that Dan trusts for third party eye candy which will not cause memory leaks in one page applications. When evaluating a dress-up widget for if it is safe or not, look to see if it has a Destroy() function or better yet, look to see if it is something you can just rewrite in a safer shape. Most third party eye candy is not yet made to be safe in one page applications and is instead built with the assumption that the user is just going to change pages away at some point doing all "garbage collection" work needed. This oversight may lead to (in one page applications) memory leaks and zombies, pieces of the DOM which ideally should have gone away yet rear their ugly heads inappropriately to your dismay.
  11. Amazon Web Services (AWS) allow up to a terabyte of hosting space. With this may come:
    • RDS is a cloud database.
    • OpsWorks is Amazon's canned configuration PaaS (platform as a service) stuff.
    • S3 is for document storage.
    • SQS (Simple Service Queue) is for data jumping between servers. It makes sure nothing gets lost when a server crashes. Think NServiceBus.