Monday, September 29, 2014

Don't get too cozy with the iPad emulation in Google Chrome Developer Tools.

At my work we are finding lots of discrepancies between the emulation and what actually happens at an iPad. I thought JavaScript-free dropdown menus would work at the iPad and I was wrong. Depending upon what you have to support perhaps you just have to use JavaScript to craft dropdown menus or maybe your iPad version gets a different look and feel.

Safari for Windows?

One of my superiors mentioned that he doesn't bother testing for Safari in Windows because the browser has just been left to be in the Windows space without the support of upgrades for some time. I found this Wikipedia write up on the browser's history and it seems to validate as much. When I check the version of Safari that I am running at Windows I see that it is 5.1.7 (7534.57.2) which is "old."

Use window.location to route to other pages within a web clip and NOT href attributes in anchor tags.

Having a "link" like so within a web clip...

<li onclick="goElsewhere('http://example.com/foo.html')">Go</li>

 
 

...which utilizes some JavaScript like this...

function goElsewhere(whereToGo) {
   window.location = whereToGo;
};

 
 

...is going to be superior to a traditional link like this...

<li><a href="http://example.com/foo.html"></a>Go</li>

 
 

...because the href links open their targets in new browser windows (outside of the web clip) and they do so even if you decorate the anchor tags with a target attribute of _top or _self unfortunately.

Decorate MVC models with attributes to make CRUD operations against them require less code all-in-all.

Like so:

using System.ComponentModel.DataAnnotations;
namespace Finance.Models
{
   public class Profile
   {
      [Display(Name = "full name...")]
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(20, MinimumLength = 4, ErrorMessage = "Please enter at least 4
            characters")]
      public string Name { get; set; }
      
      [Display(Name = "email address...")]
      [Required(ErrorMessage = "Please enter your email.")]
      [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-+.']\w+)*\.\w+([-+.']\w+)*$",
            ErrorMessage = "Please enter a valid email.")]
      public string Email { get; set; }
   }
}

 
 

The attributes will bias how the model behaves at a form as seen here:

 
 

Our example has the following Controller:

using System.Web.Mvc;
using Finance.Models;
using Finance.Utilities;
namespace Finance.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         Profile profile = Utility.GetCurrentProfile();
         return View(profile);
      }
      
      [HttpPost]
      public ActionResult Index(Profile profile)
      {
         Utility.UpdateCurrentProfile(profile);
         return View();
      }
   }
}

 
 

Our example has the following view:

@model Finance.Models.Profile
@{
   Layout = null;
}
<html>
   <head>
      <title>Whatever</title>
   </head>
   <body>
      @using (Html.BeginForm("Index", "Home"))
      {
         <article>
            <h1>Update yourself:</h1>
            
            <h2>@Html.LabelFor(m => m.Name)</h2>
            <section>
               @Html.TextBoxFor(m => m.Name)
            </section>
            <section style="color:#FF0000; padding-bottom: 40px;">
               @Html.ValidationMessageFor(m => m.Name)
            </section>
            
            <h2>@Html.LabelFor(m => m.Email)</h2>
            <section>
               @Html.TextBoxFor(m => m.Email)
            </section>
            <section style="color:#FF0000; padding-bottom: 40px;">
               @Html.ValidationMessageFor(m => m.Email)
            </section>
            
            <input type="submit" />
         </article>
      }
   </body>
</html>

Saturday, September 27, 2014

edible insect

Imagine a bat flying through a cave towards a stalactite hanging from the cave ceiling (not a stalagmite poking up from the cave floor, although that variant of speleothem would really work just fine in my story too) and on the way to the stalactite, for every step along the journey the bat must make it pings ahead, across all the positions in space it must yet cross that it will eventually pass through, in an attempt to find a juicy insect to eat along the way. While the bat is making only one trip there are many pings making trips, one for each of the increments in the bat's flight. If you write code this should sound like a loop within a loop to you. I've encountered in my history some interview questions with puzzles that have answers that fit this shape of things for finding an edible insect. One example: Here is a list of stock prices during a stretch of time and I want you to tell me what is the most amount of money I could have made by buying at the optimal time and selling at the optimal time. Another: What is the longest palindrome in a sentence? Imagine having to whiteboard static methods for these scenarios which could successfully be tested like so:

using System.Collections.Generic;
using Algorithms.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Algorithms.Tests.Utilities
{
   [TestClass]
   public class CrawlerTests
   {
      [TestMethod]
      public void FindLargestPossibleGain_happy_pass_test()
      {
         List<double> stockPricesOverTime = new List<double>()
         {
            15.67,
            18.88,
            40.22,
            41.88,
            32.19,
            11.88,
            22.17,
            39.42,
            27.17,
            27.86,
            11.11,
            22.28
         };
         double largestPossibleGain =
               Crawler.FindLargestPossibleGain(stockPricesOverTime);
         Assert.AreEqual(largestPossibleGain,27.54);
      }
      
      [TestMethod]
      public void FindTheLargestPalindrome_happy_pass_test()
      {
         string sentence = "Otto drove the racecar to the madam he had the eye for.";
         string largestPalindrome = Crawler.FindTheLargestPalindrome(sentence);
         Assert.AreEqual(largestPalindrome, "racecar");
      }
   }
}

 
 

I've heard that the first puzzle may be solved in one loop, although I cannot imagine how. In an interview however, and beyond esoteric heroics, when these puzzles come up, you are being tested to see if you can come up with an algorithm that could be considered O(n²) in Big O notation and you should craft a solution with a loop inside of a loop like these:

using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Utilities
{
   public static class Crawler
   {
      public static double FindLargestPossibleGain(List<double> stockPrices)
      {
         double largestPossibleGain = 0;
         int outerCounter = 0;
         while (outerCounter < stockPrices.Count)
         {
            int innerCounter = outerCounter + 1;
            while (innerCounter < stockPrices.Count)
            {
               double immediateGain = stockPrices[innerCounter] -
                     stockPrices[outerCounter];
               if (immediateGain > largestPossibleGain)
               {
                  largestPossibleGain = immediateGain;
               }
               innerCounter++;
            }
            outerCounter++;
         }
         return largestPossibleGain;
      }
      
      public static string FindTheLargestPalindrome(string sentence)
      {
         List<char> characters = sentence.ToLower().Replace(" ","").ToCharArray().ToList();
         string largestPalindrome = "";
         int outerCounter = 0;
         while (outerCounter < characters.Count)
         {
            int innerCounter = outerCounter + 1;
            string potentialPalindrome = characters[outerCounter].ToString();
            while (innerCounter < characters.Count)
            {
               potentialPalindrome = potentialPalindrome + characters[innerCounter];
               string potentialPalindromeBackwards = "";
               char[] potentialPalindromeCharacters = potentialPalindrome.ToCharArray();
               Array.Reverse(potentialPalindromeCharacters);
               foreach (char character in potentialPalindromeCharacters)
               {
                  potentialPalindromeBackwards = potentialPalindromeBackwards + character;
               }
               if (potentialPalindrome == potentialPalindromeBackwards)
               {
                  if (potentialPalindrome.Length > largestPalindrome.Length)
                  {
                     largestPalindrome = potentialPalindromeBackwards;
                  }
               }
               innerCounter++;
            }
            outerCounter++;
         }
         return largestPalindrome;
      }
   }
}

 
 

The total number of steps in these challenges aren't really represented by n to the power of two as for in incrementing through the first loop the ground to cover in the second loop luckily decays. Instead it would be half of the value derived by multiplying n by one less than n, so instead of there being one hundred steps for a collection of ten sequential items there would be forty-five. Anyways, I hope you can see how these problems are solved. I found them mind-boggling at first and wanted to write a blog posting about them. The thing to keep in mind is that the window within the second loop progressively shrinks. As the bat flies it has less distance to ping across to the stalactite at any one point in time in contrast to any one previous point in time. Puzzles in which we are just comparing two points in a sequence in which one point does not have to precede the other can perhaps just be solved in one loop. The puzzles here are not such puzzles however. Our bat cannot just fly to the stalactite and find an insect along the way all by its own. An inner loop comes into play. Our bat needs to ping to find an insect.

sensitivity/specificity

There was a meeting of the IEEE (Institute of Electrical and Electronics Engineers) Thursday night at AT&T labs in which Choudur Lakshminarayan gave a talk advertised as "Big Data, Cyber-Biological Systems and Pattern Recognition" which was also dubbed "Automation Classification Heartbeats" in Mr. Lakshminarayan's slideshow. By 2018 the United States will be spending $13,100 per head on its own in the name of healthcare. Wouldn't it be nice to get this cost down? Some opportunities being eyed for potential savings come in shape of technical solutions for monitoring and reporting, perpetually, a person's physique and sending preventative alerts when metrics start straying from their norms. "It's time to go to the doctor now Chuck, sooner rather than later. Something feels off." ...could be told to you in a friendly computer-generated voice saving your life, yes, but also saving you, me, and everyone some money in the form of one less tax increase perhaps. Just as we proactively monitor the tectonic plates of the earth to predict earthquakes we may see cardiac quirks a comin' by attaching a device to a subject that is perpetually monitoring the subject, separating heart beats from both lung vibrations and speech, and then looking for outliers in the patterns. Data is perpetually being wired beyond the device to a central data store in Choudur's vision opening the door to some challenges regarding security and privacy, but centralized "big" data is needed in the name of getting a clear aggregate of suggestions of what really is normal in the name of reducing false positives of what is not normal. In the image here the topmost line of data shows a healthy heartbeat in the timeline of an electrocardiogram (often called an EKG or ECG) recording. The middle row shows "premature ventricular fibrillation" or agitation in the event of... drama! The last row shows the heartbeat of someone who died of heart failure in advance of his demise. Clearly the last row looks more like row before it than the topmost row and it stands to reason that at some point the heartbeat in the last row strayed out of a shape that was closer to the first row and into a shape closer to the second row before it progressed to its state of mad high kicks. If we have the data telling us what the first two shapes look like how may we algorithmically tell when our current real time data sampling is more like a raisin than a grape? Using data deemed healthy by doctors reading electrocardiograms and also data deemed outside the bounds an aggregate of what is healthy is condensed into an average. Heartbeats follow a PQRST pattern on an electrocardiogram in which there are separate steps labeled P, Q, R, S, and T with the R representing the upper spike. When this spike strays too far above or below what is expected then we have a match for a would-be-issue. When the audience heard this idea they started to revolt against the notion that an average of the data could represent, for example, men and women equally or persons of different weights perhaps, but Choudur counter argued that when a doctor reads an electrocardiogram that no consideration is given to gender, or lifestyle, or if the individual is a smoker. Electrocardiograms are all read the same and thus there may be, in this circumstance, an average that applies to just about everyone. There was a woman in the crowd who was eighty-five who had been expected to only live to be seven as she had an extra large heart which gave funny readings ever implying that she was on death's door all her life, so she would be an outlier, but, again, for most of us, an average of the aggregate of "big data" should represent how our hearts should behave. Most of us have seventy-two heartbeats a minute. There is room for false positives and false negatives and we do need a way to polish our algorithm is the name of reducing these. To that end:

  1. Sensitivity may be thought of as true positives divided by the sum of true positives and false negatives.
  2. Specificity may be thought of as true negatives divided by the sum of true negatives and false positives.
  3. A positive prediction value (PPV) comes from true positives divided by all positives both true and false (the sum of true positives and false positives).
  4. F score comes from doubling the value derived from multiplying sensitivity by PPV and then dividing the doubled number by the sum of sensitivity and PPV. An F score of 1 suggests a perfect algorithm and an F score of 0.9 means you're doing pretty well in Choudur's opinion. The 1 represents 100% matching of good to good and bad to bad and the 0.9 is a grade of 90%, etc.

To submit a url to Google for crawling...

...one used to go to http://www.google.com/addurl and while that URL seems to still exist it now falls over to https://www.google.com/webmasters/tools/submit-url it seems. By the way today appears to be Google's 16th birthday. Happy sweet sixteen. You sure are in a sweet position. Google, I love you and I hate you. I wonder if it was a mistake to spin up my blog at your Blogger. Well, it's done now. Whatever.

Friday, September 26, 2014

How to do JavaScript-free modern day dropdown menus with just CSS and HTML which work in Internet Explorer 9 and better browsers.

This simple example...

<!DOCTYPE html>
<html>
   <head>
      <title>Whatever</title>
      <style type="text/css" media="all">
         nav ul {
            display: inline-table;
         }
         nav ul li {
            display: inline;
            padding: 2px;
            background-color: #EEEEEE;
            border: 1px solid #000000;
            float: left;
         }
         nav ul li:hover > ul {
            display: block;
         }
         nav ul li ul {
            position: absolute;
            display: none;
            padding: 0px;
         }
         nav ul li ul li {
            display: block;
            float: none;
         }
      </style>
   </head>
   <body>
      <nav>
         <ul>
            <li><a href="#">Marx Brothers</a>
               <ul>
                  <li><a href="#">Chico</a></li>
                  <li><a href="#">Harpo</a></li>
                  <li><a href="#">Groucho</a></li>
                  <li><a href="#">Gummo</a></li>
                  <li><a href="#">Zeppo</a></li>
               </ul>
            </li>
            <li><a href="#">Stooges</a>
               <ul>
                  <li><a href="#">Moe</a></li>
                  <li><a href="#">Larry</a></li>
                  <li><a href="#">Curly</a></li>
                  <li><a href="#">Shemp</a></li>
               </ul>
            </li>
         </ul>
      </nav>
      <article>Other content to overlay with dropdowns...</article>
   </body>
</html>

 
 

...behaves like so:

 
 

I emulated an Apple iPad 3 / 4 in Google Chrome's Developer Tools and the submenus open when the top list items are clicked but not without also triggering the links within the list items. I suppose there are other concerns to think about in supporting the iPad. Also, a submenu will just sit open until one opens a different submenu or clicks randomly elsewhere in the browser (which will close the submenu).

Addendum 9/29/2014: It turns out that this doesn't work in an iPad after all. See: this

Apply a stylesheet style only at the iPad!

This is inspired by this:

#foo {
   display: block;
   margin: 0;
}
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and
      (orientation: portrait) {
   
/* iPad Portrait */
   #foo {
      font-size: 2.5em;
      padding: 15px;
   }
}
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and
      (orientation: landscape) {
   
/* iPad Landscape */
   #foo {
      font-size: 2.5em;
      padding: 15px;
   }
}

Position a background image some number of pixels off of the lower right corner of the element being styled in CSS.

background-position: right 5px bottom -5px;

...is markup in contrast to offsetting from the upper left corner like so...

background-position: 5px -5px;

Easter egg

...is a term for a hidden link or feature.

Which of your tasks in Rally still need your attention?

  1. Pick the "Tasks" option under the "TRACK" menu.
  2. At the filter controls above all the line items at column headings, change the setting for "Owner" to be yourself instead of being blank.
  3. The setting for "Views" should also be "Active" but it likely is already.

BladeLogic

...seems to be for managing a datacenter and server automation stuff. I heard of it today.

Wednesday, September 24, 2014

Extension methods cannot be dynamically dispatched.

To use the ViewBag in an Razor using statement to make a form tag you will have to cast the dynamic object to a string, like so:

@using (Html.BeginForm("Results", (string) ViewBag.WhereToGo))
{

 
 

Don't try to the .ToString() thing. That is not the fix. That will cause an error that ends with: ...has no applicable method named 'BeginForm' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Add a comment in Razor markup (not that I'm encouraging comments).

@* this is just a comment *@

(I hate code comments. They're gonna grow stale.)

Get the name of the current Controller in Razor markup.

@HttpContext.Current.Request.RequestContext.
      RouteData.Values["controller"].ToString()

Bonus: If you use "action" instead of "controller" it does what you'd expect.

Url.Action

...is a pretty good way in Razor markup to get a route to a specified Controller Action. Behold:

<button onclick="@("window.location.href='" + @Url.Action("Bar",
      new { id = @Model.Id }) + "'");">Go</button>

 
 

Unlike @using(Html.BeginForm implementations where one has to specify a Controller and not just an Action, with Url.Action one just needs an Action. The most immediate Controller will be used in the absense of a specification, but you may also give a specification like so:

<button onclick="@("window.location.href='" + @Url.Action("Bar", "Foo",
      new { id = @Model.Id }) + "'");">Go</button>

 
 

This stuff works without regard to the complexity of whether or not you are running an IIS application wherein the URL starts with http://localhost/whatever and the routes will all start with a forward slash specifying the root of the site, and I do indeed mean the real root of the site even in the circumstance of an IIS application.

Put spacing between words and letters in CSS.

.whatever
{
   letter-spacing: 1px;
   word-spacing: 5px;
}

Payment Card Interface (CA-PCI) is currently on version 4.0.

Per this it is the interface to talk to to do much financial services stuff in SAP R/3 which is one of the common things the SAP app is called (others include SAP ERP, SAP Business Suite, and SAP ECC 6.0 in which ECC stands for ERP Central Component and for which there have been seven enhancement packs but no new version in years) ...hybris lies outside of CA-PCI and one interacts with it with web services

Oracle Siebel

...is a CRM solution not unlike Salesforce.com.

Oracle eBusiness Suite's footprint is how big?

I learned today that Oracle eBusiness Suite has more deployments in North America than SAP which makes me question the factoid I learned during my stay at @hand that there are only two hundred some odd companies using Oracle eBusiness Suite. I guess both that fact and this new fact could be true at the same time. I dunno.

Tuesday, September 23, 2014

Don't you just hate the source control conflicts you get from minified CSS made from LESS with Web Essentials?

When everything gets jammed onto one line it can be painful to clean up in a merge. Well, you really don't have to keep these files in source control to begin with. (As much will solve this problem.) Only the .less files need to be kept in source control while the .css, .css.map, and .min.css files may just be generated. In Visual Studio 2013 if you go to "Options..." under the "TOOLS" menu you will get the "Options" dialog box. At the left menu, if you pick "LESS" under the "Web Essentials" tree you will be able to set the setting for "Compile files on build" to be true at the right pane. This will force the .css, .css.map, and .min.css files to update upon a build. Note that if you pull down fresh code from source control and these files don't exist to being with that you do have to trick them into being there upfront. Do this by just opening all the .less files and adding a superficial change like a line break or something. I know this is ghetto.

What if you just need an at symbol in a .cshtml page and you don't want to break into Razor syntax?

You may double up the at symbol to just have a single at symbol appear in the HTML that gets rendered. I mean to say that this Razor markup...

<style type="text/css" media="all">
   @@media (max-width: 1030px) {
      .Seller {
         background: url('@ViewBag.Seller.SmallLogoPath');
      }
   }
   @@media (min-width: 1030px) {
      .Seller {
         background: url('@ViewBag.Seller.LargeLogoPath');
      }
   }
</style>

 
 

...gives you this HTML markup:

<style type="text/css" media="all">
   @media (max-width: 1030px) {
      .Seller {
         background: url('http://example.com/Images/ebay-sm.png');
      }
   }
   @media (min-width: 1030px) {
      .Seller {
         background: url('http://example.com/Images/ebay-sm.png');
      }
   }
</style>

 
 

By the way, when you jam a media query into a style tag inside of HTML like this, the classes have to be nested in the query and not the other way around. Otherwise it will not work, or at least not in Google Chrome.

ViewData and TempData in MVC applications.

This implies that ViewData and TempData are user-interface-for-the-web dictionaries that one would put stuff into and take stuff from in exactly the same syntactical manner as interacting with Session or the ViewState of the web forms world, casting, null checks, and all! ViewData seems a more ghetto version of ViewBag using the old paradigm from a time before dynamic. TempData is portrayed in the link I provide at the beginning of this paragraph as a lightweight version of Session allowing data to survive the journey across a RedirectToAction although I bet I would just use Session for most things as it is less esoteric, and yet, this argues that the fact that TempData only survives redirects makes it a little more secure for shepherding about sensitive information.

HP WinRunner is another testing tool.

The Wikipedia article says that it allows one to record and playback navigations through a user interface not unlike, I suppose, Selenium. I don't know if you test the web or desktop apps with WinRunner. I mention it because a coworker brought it up today at lunch.

NetWeaver is SAP's SOA solution?

That is kinda what I take away from this which says: "NetWeaver is an application builder from SAP for integrating business processes and databases from a number of sources while exploiting the leading Web services technologies."

Monday, September 22, 2014

Nest one style within another in CSS.

Herein, in order to decorate an element with "Bar" and have it actually use the class, "Bar" must sit within another element decorated with "Foo" at its id designation.

#Foo{
   width: 400px;
   height 200px;
   padding-top: 10px;
   background-color: #0000FF;
   .Bar {
      width: 400px;
      height 100px;
      background-color: #FFFF00;
   }
}

 
 

Addendum 9/30/2014: This is not true at all. You may do this sort of thing in LESS which complies to CSS like this:

#Foo{
   width: 400px;
   height 200px;
   padding-top: 10px;
   background-color: #0000FF;
}
#Foo .Bar {
   width: 400px;
   height 100px;
   background-color: #FFFF00;
}

 
 

Immediately above is how to do CSS nesting.

12pt equals 1em equals 16px equals 100% in default CSS font-size scenarios.

This has a pretty good cheat sheet.

Saturday, September 20, 2014

in big O notation

O(n)implies an algorithmic solution may happen with just one loop through a collection of items
O(n²)implies that each or potentially each item in the outer loop has to churn through a second loop in the name of finding a solution to our problem so iterating over 8 things could have up to 64 steps (8x8)
O(n³)three loops! we're are starting to have performance problems... DANGER!

The difference between Dictionary and SortedDictionary in C#...

...seems to be one of memory management. I think the SortedDictionary type uses something like a tree under the hood to hold its information. There does not seem to be a difference in that the SortedDictionary has more methods for more functionality hanging off of it. I'm not seeing that yet. Am I wrong?

Virtual Reality

I met Rabi Satter at an event earlier this month and he invited me to attend a different event he was to hold at the Microsoft Center on Wednesday on Xamarin. I attended but Rabi, trapped in a meeting at his work, never made it and his Xamarin workshop was not to be. It ended up be a really fun evening nonetheless. I ended up getting to goof off with an Oculus virtual reality headset, and, yes, virtual reality is back!

The Oculus was owned by Dean Herko (below left) and he and I am another gentleman named Rahul Varanasi who joined us (below right) spent the evening in an impromptu meeting messing about with the toys that Dean happened to have with him. (Beyond the Oculus there was also a Kinect and a Leap.)

Inside of the headset, there are lenses which beam light directly into the eyes. You also wear earphones while you wear the headset so that your ears may be tricked along with your eyes. The headset does a good job of tricking you and giving you an immersive experience. It made me feel wobbly some. Dean recommended that I hold onto a table in front of me a couple of times while I was using the apparatus. It doesn't immediately hurt the eyes, but at the same time I was ready to come out from under the Oculus after using it for maybe five to ten minutes. It was good, but something more than a touch of this good thing is overwhelming.

Dean had me walk through maybe three environments. The one I liked the best that I recommended that Rahul try was one in which one walked around and in a villa overlooking what I suspect was meant to be the Mediterranean. It was awesome. This was what Dean and I could see on Dean's laptop while Rahul wore the headset. I promise that what Rahul was seeing was much more convincing.

An XBox Controller was used to walk forward and move about in this environment. (Even if the XBox is to die, it, in its day, brought us some interesting technology that will be used in other ways. I'll get to the Kinect in a moment. It ties heavily into the XBox giving you sort of a Nintendo Wii experience without having to hold a controller, and yet it should have life in other apps beyond the XBox.)

A sensor (which I suppose was also a camera???) focused on where the Oculus was so that the software could adjust imagery when you turned your head. When I turned my head and looked about the experience reacted accordingly seamlessly. One of the things you have to do at the start of using the Oculus is pose looking straight forward so that the software knows where your head should face when you are facing forward. Guys, whoever you are that made this stuff, good work! I was fooled. Keep doing what you're doing.

In the picture below the sensor for the Oculus sits atop Dean's laptop, but that other device in front of the laptop is a Kinect (a different kind of sensor/camera body motion detector) and we played with it some too.

It does skeletal tracking and will map twenty five points on your body onto a model which represents where your arms, legs, hands, etc., are at. There is a company called BODY{SNAP} that will allow you to make a 3D model of yourself for use in games. The models have Kinect-friendly skeletons which should react to the movement of your twenty-five points. On the laptop's screen above you may see the Kinect figuring the three of us out.

I only mention the Kinect because it has a counterpart in the Oculus world called the Leap. Above, the Leap is that device in front of the laptop below Rahul's hand. It is making sense of Rahul's hand as you may see on the screen. Cool stuff, huh?

I go to the Microsoft Center in Austin for talks a lot, but this isn't usually the format. As I mentioned there was a talk by Rabi Satter which ended up being not to be. There was also an event hosted by Jeffrey Palermo (above left) on Azure going on at the same time. Thanks to Shawn Weisfeld (below left) of Microsoft for keeping the doors open for us. Martin Tatar also helped man the shop so thanks to him too. I met him for the first time on Wednesday. He is in the purple shirt above. I guess you can't really tell who he is.

Interesting things mentioned by Shawn included that TFS (Team Foundation Server) is Microsoft's ALM (Application Lifecycle Management) solution and that he himself was an ADM (Application Development Manager) meaning that he did code reviews for best practices and helped with the deploying and packaging of apps.

Friday, September 19, 2014

Bonus!

The Web Essentials LESS implementations will not only render .css files from .less files but will also make .min.css files with minimized CSS! When adding a new file an option for "LESS Style Sheet" should be findable under Markup under Web under Visual C# in Visual Studio 2013 if you have Web Essentials.

Have Web Essentials make minified JavaScript files from your .js files and keep them up to date.

Here is an example. I made a file called Whatever.js which had this in it:

var whatever = "hello";
var somethingMore = whatever + " world";
alert(somethingMore);

 
 

In the Solution Explorer in Visual Studio 2013, I right-clicked upon the file I made and then picked from the menu which appeared: Web Essentials > Minify JavaScript file(s)

 
 

var whatever="hello",somethingMore=whatever+" world";alert(somethingMore);
/*
//# sourceMappingURL=Whatever.min.js.map
*/

...ended up in a Whatever.min.js file and a Whatever.min.js.map file was also created to associate the Whatever.js file with the Whatever.min.js file. Now whenever I alter and save the Whatever.js file the Whatever.min.js file updates.

 
 

var whatever = "hello";
var somethingMore = whatever + " Mars!";
alert(somethingMore);

...this change to Whatever.js for example creates this change at Whatever.min.js:

 
 

var whatever="hello",somethingMore=whatever+" Mars!";alert(somethingMore);
/*
//# sourceMappingURL=Whatever.min.js.map
*/

Thursday, September 18, 2014

The MAC (media access control) Address for an iPad...

...is at: Settings > About > Wi-Fi Address

how to use Ankh

Open a project from: FILE > Open > Subversion Project... ...to use ankhsvn! Do not expect to open a project already working with TortoiseSVN and have the ankh functionality. If you right-click on the solution in the Solution Explorer and pick "Commit Solution Changes" you may push up to the repository. There are options for "Revert" and "Update Solution to Latest Version" in the same spot which do what you'd expect.

How are credit cards bound to corporate accounts?

Let's say that I'm Joe Blow and I work for Sears. I have a Sears credit card. The name on the card will not be "Sears" it will be "Joe Blow" so how is the card associated with Sears? The bin on the credit card will fall within a bin range for Sears. The bin is the first 6 or 7 digits of the credit card number.

 
 

Addendum 3/15/2016: bin stands for bank identification number

business objects versus objects to just show in MVC views

This blog posting tersely illustrates why one might not want to hand one's business objects into a view, but instead craft vanity objects explicitly for presentation and map the real objects to and from them. It touches on AutoMapper and gives a good explanation of how you work with it as a concept, but it also gives an interesting simpler scenario:

  1. I need to hand a business object into a view where the object may be edited at a form.
  2. Some of the parameters at the object should be strings, but not just any values are allowed. The values should be populated by dropdown lists.
  3. A new type, to be handed into the view, will wrap both the business object and enums or something similar used to hydrate the dropdown lists with legitimate options.

Also, in the lightweight, not AutoMapper approach, if I have an object called FruitCake but I wanted to hand a FruitCakeViewModel type into a view in the name of editing a FruitCake at a form, I would have a FruitCakeViewModelBuilder to make a FruitCakeViewModel from a FruitCake and a FruitCakeMapper to cast a FruitCakeViewModel back to a FruitCake. The blog posting suggests these should be instance classes, but I'm going to try to make these static utilities. We are beginning to build out this sort of thing at an app at my work. Let's see how it goes.

Wednesday, September 17, 2014

Web Essentials has a toolbar!

It seems sort of corny so far, but perhaps I am premature in saying that. It is smart enough to appear at an application I've made in Visual Studio 2013 at the VM where Visual Studio 2013 is installed when running the app from Visual Studio, when running the app as an IIS application, and when running the app as an IIS web site. I can make the toolbar just go away by clicking the "Auto-hide" checkbox, and if I want it back this points out that you may bring it back up in Google Chrome by just clicking the Ctrl key. The toolbar floats in the lower left corner of the Chrome browser and until you take your mouse there it is sort of muted like a watermark.

...but, I need the tilde in JavaScript!

My superior was not in love with the spaghetti mess I made here in JavaScript in the name of trying to find the url of the root of a web application while also accomodating IIS application scenarios wherein the root of the url may just be http://localhost/yourfoldernamehere where one must not mistake http://localhost/ as the base of things. He suggested that I determine the base of a url in C# (where it is much easier) and then bubble up the value into a hidden form field in HTML from which point it could be slurped into JavaScript. In an ASP.NET MVC controller one may get the base url like so:

var x = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");

 
 

Noteworthy: System.Web.VirtualPathUtility.ToAbsolute("~/") has a dance partner in the web forms world in Page.ResolveUrl("~/") (I think) and should just give you a forward slash if you are not doing the IIS application thing. If you are doing the IIS application thing then you will get the name of that second piece of the route after localhost with forward slash bookends. I experimented with @Request.Url.Host.ToLower() and it turned out to be inferior to Request.Url.GetLeftPart(UriPartial.Authority) as it left off the "http://" bit.

Importing one .less file into another...

...looks a lot like importing one .css file into another. Example:

@import "Whatever.less";

When checking to see if an element has a style with jQuery, the absence of a style manifests differently in different browsers.

A truthy/falsey check will behave the same in both IE and Chrome, but if you try to make an equality match on the value you'll get different things for the falsey circumstance. Consider x here:

var x = $('#Whatever').attr("style");

 
 

It will match to "" in most browsers and yet match to undefined in IE. This means you can't do...

var y = x.indexOf('whatever');

 
 

...to fish for something in x without a sanity check to make sure x is truthy first.

Imperial

...is the name of the other system of measurement that is not the metric system. The imperial system has feet, pounds, and gallons while the metric system has meters, grams, and liters.

Tuesday, September 16, 2014

Web Essentials has LESS support!

At http://vswebessentials.com/ get "Web Essentials 2013 for Update 3" which will require that you first have Update 3 which you may get like so:

  1. go to "Extensions and Updates..." at the TOOLS menu in Visual Studio 2013
  2. click on "Updates" at the left of the "Extensions and Updates" dialog box which appears
  3. find Update 3 and click its "Update" button

Once you have everything and it works, when you make a change in a .less file and then save the file, the appropriate updates will cascade to your .css files which are complied from .less files! You will see that familiar "This file has been modified outside of the source editor. Do you want to reload it?" alert to which you will answer "Yes" of course. I think Web Essentials also does .js to minified .js stuff too. This means the death of Chirpy I'd imagine.

The tilde is that symbol you get when you press the upper left most key while holding Shift and (when it is not denoting a finalizer) it denotes the root of a web application!

Observe:

Whatever whatever;
using (var reader = new StreamReader(HttpContext.Server.MapPath("~/SiteMap.xml")))
{
   var xmlSerializer = new XmlSerializer(typeof(Whatever));
   whatever = xmlSerializer.Deserialize(reader) as Whatever;
}

 
 

Do note that the code above is C# and not JavaScript and there is no tilde in JavaScript. In JavaScript you need to do something like this:

function whereAmI() {
   var url = window.location.href;
   var urlChunks = url.split("/");
   var url = "";
   var matchMade = false;
   urlChunks.forEach(function(chunk) {
      if(!matchMade){
         if (url == "http://" || url == "https://" || url == "http://localhost/" || url ==
               "https://localhost/") {
            if (chunk.toLowerCase() != "localhost") {
               matchMade = true;
            }
         }
         url = url + chunk.toLowerCase() + "/";
      }
   });
   if (url.indexOf("?") > -1) {
      urlChunks = url.split("?");
      url = urlChunks[0] + "/";
   };
   if (url.indexOf("&") > -1) {
      urlChunks = url.split("?");
      url = urlChunks[0] + "/";
   };
   return url;
};

 
 

Why didn't I just use window.location.hostname you ask? Because .hostname will not find the base url for an IIS application which will have a base like so: http://localhost/whatever/

Determine if you are using an iPad in JavaScript.

This says to do it like so which seems to work:

var isIpad = navigator.userAgent.match(/iPad/i) != null;

The screen real estate on an iPad seems to be 1024 by 768 pixels.

This says a few things consistent with such.

Addendum 9/18/2014: The new iPads which carry the name iPad Air have twice (2048x1536) the resolution!

A coworker mentioned to me that the Moto 360 circular-faced smart watch has a piece of the face that is always black.

I think it is a sliver at the base of the watch. This doesn't matter if the watch is black in watch mode, but you can see it when the whole of the screen lights up I hear. So far, I think the Apple Watch looks better truth be told.

Indemnity

...is insulation from legal liability. I see this term in legalese a lot.

yet another test

this is yet another test!

tentacles

Alec Gillis and Tom Woodruff Jr. are two guys who used to work for/with Stan Winston who was a fairly big name in Hollywood special effects until his recent death. His surviving understudies are now to roll out a horror movie called Harbinger Down which will feature exclusively old school foam/latex rubber suit monsters and supposedly no CGI (computer-generated imagery). The film was crowd-funded and I'd like to get behind it and endorse it without having ever seen it and without knowing if it is any good. If the movie turns out to be terrible that's great too and it will sort of meet expectations. It's going to star Lance Henriksen so that sort of seems consistent with it being bad in a good way. Now what does any of this have to do with software and why should I mention it at this blog? I like this image I found online of peeps on the movie set working with what has been suggested to be "practical effects" (not CGI).

They are all doing what they love, wrangling a thing with many tentacles, trying to make sense of it, trying to get it to behave and work. This seemed to say a lot about software to me. :) I promise I will not fill this blog with a bunch of noise just as I've also promised here. Bear with me. I think I've gotten this out of my system now.

test

just testing

Monday, September 15, 2014

?v=1.2.3 ...or something similar could be bolted onto the end of file paths in your HTML calling out to .css and .js files in your application.

If you increment the version number as you increment the version, when you roll out code to production, it will jog the cache of users and allow them to have the latest/greatest without being frozen in the past. One way to do this with Razor markup would be like so:

<script src="~/Scripts/Whatever.js?v=@Utilities.RetrieveVersionNumber()"></script>

 
 

On the C# side we could have a static method like this:

public static string RetrieveVersionNumber()
{
   return System.Reflection.Assembly.GetExecutingAssembly().GetName()
         .Version.ToString();
}

 
 

If the version seems to come back as 0.0.0.0 all the time, this is probably only happening in your local environment. The 0.0.0.0 should be replaced with a real number when you view the deployment to production's HTML.

The Uri type in C# may parse out the domain from a url!

A test like so would pass:

string url = "http://example.com/whatever?foo=bar&baz=qux";
Uri uri = new Uri(url);
Assert.AreEqual(uri.Host, "example.com");

carousel

...is the name for one of those HTML controls wherein a series of (often clickable) dots are cycled through while a different (often clickable) banner is displayed for each dot. Often one banner with fade into another or slide to another in a transition between two.

Sunday, September 14, 2014

When you right-click in Visual Studio 2013 and pick "Go to Declaration" only to end up at an interface...

...this does not mean you've hit a brick wall. Right-click on the name of the interface at the interface itself next and pick "Go to Implementation" to find the class hydrating the interface with its public methods. Do not manually search for the name of the interface to find its dance partner. I'm embarrassed to admit that I used to do this. Ha.

Addendum 9/15/2014: Ctrl-Shift-G (which is perhaps a ReSharper shortcut???) will allow you to go to the implementation if you use this hot key after clicking upon the name of an interface at an interface, or will allow you to pick between going to the declaration of the interface or drilling two steps down to the implementation of the interface (from upstream where in code an instance of the interface is instantiated). This was mentioned to me over Twitter by @jphamilton when I first advertised this blog posting.

wearable tech?

I was just in the Barnes and Nobles Booksellers up the street and I saw this cover of Time magazine which is projecting that wearable tech is about to affect our lives as shepherded in by the coming Apple Watch. We've been hearing about wearable tech for a year and a half or so now. Will it indeed change our lives? I still see no reason not to cling to my iPhone for all my immediate out-in-public tech necessities, i.e. checking news/email and getting driving directions. Maybe there is something more in the magic that I don't yet see because I haven't wanted to try. I dunno. We've been hearing about Arduino and the internet of things for a spell now too, longer than wearable tech, and so far it all just seems like toys to me like... mmmm... everything Macintosh. I found it kind of comic that the dying world of print media would tell us what's next and trendy in technology.

Use Chocolatey to install OWIN.

This was mentioned by Reaz Haq (right below) at the Austin .NET User Group Monday night. Chocolatey was characterized as like NuGet for machine install stuff. There is exactly one package one may install to set up OWIN. This was kept simple.

Friday, September 12, 2014

A double hyphen in MSSQL will comment out everything after it on the same line.

Therefore a single tick followed by a double hyphen may be used in an SQL injection attack to throw away sanity checking at an end of a line of SQL.

I learned today that the TRACE verb is typically turned off at a webserver.

No wonder I could not get it to do much here. This suggests you must explictly turn TRACE on at Web.config to get it to work in an ASP.NET application. It's example is:

<configuration>
   <system.web>
      <trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/>
   </system.web>
</configuration>

The PIN block for your credit card is made from a combination of your PIN and the data in the magnetic strip.

I guess the PIN block and not your unencrypted PIN is sent outwards from machines where you punch in your PIN at a keypad??? I kinda get that from this.

Foo[0].Bar

Would be a good name for a form field at a form which posts to a Web API Post method which at its signature expects an object which has a property called "Foo" which is a collection of a type of which has a property called "Bar." The first of the Foo collection would get its Bar value set to the value of the form field in this circumstance.

Swapping between a list of line items and a collection of detailed "product highlight" callout boxes for items.

My boss found these links which show off "product highlight" callout boxes for a list of items:

  1. http://vnjs.net/www/project/freewall/example/demo-filter.html
  2. http://suprb.com/apps/gridalicious/
  3. http://www.jqueryrain.com/?4p48mK1P

 
 

The last of these shows off swapping to and from a list. I guess if I were to author something myself, each item would be a div with other divs inside of it. I think that way, by switching CSS styles alone I could create an effect in which one format could easily fall over to another. It occurs to me that this sort of thing lends itself well to the narrow mobile world too where there could just not be a (horizontal-space-heavy) list format for the items I guess.

 
 

Also, a different coworker today mentioned: http://css-tricks.com/snippets/css/a-guide-to-flexbox/

cross-site request forgeries

...come up when you open a sinister web site and it tries to read your cookie data and then use credentials in a cookie to break into a different web site. Don't store passwords in cookies kids.

Big O notation

...may be used to measure just now complex an algorithm is. I don't really understand it. There is more about it here.

Thursday, September 11, 2014

Use Server.Transfer from a landing page to a page with the real content you want in a web forms application to prevent some back button issues.

If you, for example, have an iFrame with a temporary URL that will not work twice due to modifications being made at the database the first time, then the iFrame is going to cough up an error when someone navigates onto your page with a back button. I got around this in an application I am working on by putting a dummy empty page in front of the page holding the iFrame and redirecting to it through Server.Transfer which, unlike Response.Redirect, does not alter the URL line. I had to introduce some randomness to get it to work in the particular application in front of me. I did so like this:

Server.Transfer("iFrame.aspx?" + Guid.NewGuid());

A super simple OnActionExecuting/OnActionExecuted example.

using System.Web.Mvc;
namespace InterstateHighway.Controllers
{
   public class HomeController : Controller
   {
      protected override void OnActionExecuting(ActionExecutingContext filterContext)
      {
         ViewBag.Number = 1;
         base.OnActionExecuting(filterContext);
      }
      
      protected override void OnActionExecuted(ActionExecutedContext filterContext)
      {
         ViewBag.Number = ViewBag.Number + ViewBag.Number;
         base.OnActionExecuted(filterContext);
      }
      
      public ActionResult Index()
      {
         ViewBag.Number = ViewBag.Number + ViewBag.Number;
         return View();
      }
   }
}

 
 

...if our action above takes us to a view which looks like this...

<p>@ViewBag.Number</p>

 
 

...then the number 4 will be displayed in the view.

Ignore a file (in committing) that is checked out with/within TortoiseSVN.

  1. The file to ignore will need a change to differentiate it from what is in source control. If you do not need to intentionally drift your file away from what is in source control (i.e. think your local Web.config) then you may need to put a superficial line break in the file. Otherwise, just change up your local version.
  2. Right-click on the topmost folder associated with what is checked out from Subversion and pick "SVN Commit..." from the menu which appears.
  3. A list of files to potentially commit will appear here and to ignore your file you should right-click upon it and then pick "ignore-on-commit" which is not immediately in the menu which appears but which may be found in the second menu that appears when you mouse over "Move to changelist" at the base of the menu which immediately appears.

This will do the trick. It will keep you from accidentally committing that thing that needs to stay out of sync with what is checked in. The "ignore-on-commit" list will appear in the same pane for committing and you may always click on your outlier file here and pick "Remove from changelist" to set its state back to committable. To actually commit you will either need to check the checkbox by the item or close the window and reenter it where you will see the checkbox checked by default.

Wednesday, September 10, 2014

Apple Pay

...is a means to store credit card credentials at an iPhone or Apple Watch. You may take pictures of your physical credit cards and the numbers/details may be read from the pictures in the name of getting them into the system. When using an iOS app that is integrated with Apple Pay you may then push credit card specs to the vendor that keeps the app. I believe the credit card numbers are tokenized for security, etc.

In making sense of the typical one HTML page JavaScript test runner in a continuous integration process...

...it has been pointed out to me that instead of scrapping the HTML and jumping through a bunch of hoops that one may just try to find any one instance of a CSS class for an error anywhere within the contents and then fail the build based upon that.

FxCop

...is the JSLint of C#!

A coworker mentioned that one may generate temporary credit card numbers for Citibank Visa cards.

This suggests that this may be done for a few types of cards and that the advantage is that if you use a temporary card number at a sketchy website that should a problem arise it is easy to tell exactly which party is abusing your card.

I am starting to experiment with Jasmine testing within Visual Studio using ReSharper to run the tests locally.

This works. I can run these tests out of a .js file with ReSharper.

/// <reference path="../jasmine.js" />
describe("whatever()", function () {
   var myNumber = 0;
   beforeEach(function () {
      myNumber = 1;
   });
   afterEach(function () {
      myNumber = 1;
   });
   it("one plus one is two", function () {
      myNumber = myNumber + myNumber;
      expect(myNumber).toBe(2);
   });
   it("one plus two is three", function () {
      myNumber = myNumber + 2;
      expect(myNumber).toBe(3);
   });
});

 
 

I got jasmine.js from here. I struggled today to figure out how to reference another file in the name of testing it. I'm still tinkering with that. More soon.

Free Stuff

I went to the Austin .NET User Group last night and while I was waiting for the tech talk to start a gentleman there told me about:

  1. SafeLink which is one of many similar government programs that will give you a free cellphone (not a smartphone, but something that looks like it was made ten years ago) if you qualify by being poor enough. You also get X number of minutes a month for free.
  2. FreedomPop if approached just right is a vendor that will give you a USB key for a one time fee that will allow you to surf the internet for free. However, I was cautioned that there are plenty of pitfalls in their "paperwork" that allow you to end up with hidden charges and you have to know how to navigate these tricky waters to really come away with free service.

ACH stands for Automated Clearing House.

When your paycheck is automatically deposited into your checking account, that act is an ACH payment.

Tuesday, September 9, 2014

Challenge: Something is being calculated at the same line it is being returned and you want to see what the calculated value is in Visual Studio 2013.

If you set a breakpoint at the line in question, there is nothing you may easily mouse over to see the calculated value. So what do we do?

I am embarrassed to admit that I used to just break the one line of code into two. I'd cast the calculation to a variable and then return the variable in a second line of code while placing a breakpoint at the second line so that I could tell what is in the variable at the first line. In the example here we get at the integer 55 which is what we want... but there has to be a better way, right?

Sticking with one line of code, you may highlight (drag the cursor over to make a selection) just the calculation, right-click upon it, and pick: "Add Watch"

The "Watch" pane will appear at Visual Studio's base, and, look, there is the number 55!

Monday, September 8, 2014

Another way to get back the contents of a GET method from an ASP.NET MVC Web API Controller at C#!

This should EVEN work in web forms, but don't expect it to work with POST, PUT, or DELETE.

string url = @"http://www.example.com/api/whatever?foo=bar";
WebRequest webRequest = WebRequest.Create(url);
HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
Stream dataStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(dataStream);
string responseFromServer = streamReader.ReadToEnd();

An example of using XDocument in C# to read and make sense of XML.

In this example myMagicString would just hold XML:

XDocument xDocument = XDocument.Parse(myMagicString);
foreach (XElement child in xDocument.Root.Elements())
{
   if (child.Name == "statuscode")
   {
      DoWhatever(child.Value);
   }
}

 
 

You would use .Load instead of .Parse methinks if myMagicString held the name of a file to crawl.

Sunday, September 7, 2014

In C# background threads do not keep an application alive.

They only live as long as a foreground thread is running and once all foreground threads are done running in an application, the application itself will stop running dropping any stray background threads. This is a danger in using background threads.

The .IsBackground property hanging off of the Thread type may be set to true or false to manage this trickiness.

I was halfway to understanding something when impatience set in and I started hacking!

Get your mind around the second half of the if/else statement switching based around .IsSuccessStatusCode here which looks like this:

} else {
   throw new Exception("Ouch!");
}

 
 

What if the exception which said "Ouch!" were to be thrown in the Web API controller at api/something and we wanted to capture the word "Ouch!" in the else half of our if/else. How would we do so? So far, I've only figured out how to do so with the code which follows which functionally does the same thing as the code above in that they both throw an "Ouch!" exception while the two approaches keep the "Ouch!" magic string in different locales. I mean to communicate that the message variable will end up with "Ouch!" inside of it assuming that the Web API controller at api/something throws an "Ouch!" exception exactly as the middlemost of three lines above does. Make sense? I'm starting to babble.

} else {
   string exception = response.Content.ReadAsStringAsync().Result;
   string message = exception.Split('"').ToArray()[7];
   throw new Exception(message);
}

 
 

Doesn't splitting the exception variable and finding the eighth piece of it seem ghetto to you? Me too! This was the only way so far I have found to get "Ouch!" by itself. That isn't because there isn't another way. This is just all that I have tried so far. When I set a breakpoint in the application and look at what ends up in the exception variable, Visual Studio 2013 tells me that this is in there:

"{\"Message\":\"An error has occurred.\",\"ExceptionMessage\":\"Ouch!\",\"ExceptionType\":\"System.Exception\",\"StackTrace\":\" at MyNamespace.SomethingController.Post(SomeType someType) in c:\\\\source\\\\stuff\\\\Controllers\\\\MvcController.cs:line 23\\r\\n at lambda_method(Closure , Object , Object[] )\\r\\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\\r\\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\\r\\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\\r\\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\\r\\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\\r\\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()\"}"

 
 

I can probably cast this to a particular type in C#, but what type? I tried mapping it to an Exception type in the same way I map to the MyCustomType type in the link I provide above, but my efforts were to no avail. Here are some links that I found which were helpful, but only so helpful:

  1. http://stackoverflow.com/questions/12103946/httpclient-doesnt-report-exception-returned-from-web-api
  2. http://www.codeproject.com/Articles/611176/Calling-ASP-NET-WebAPI-using-HttpClient

Addendum 9/7/2014: I tried to beat this challenge a few more ways. I tried to deserialize to an Exception type without luck for example. In looking at the first of the two links above, I now wonder if something like the following would work. I dunno.

} else {
   string exception = response.Content.ReadAsStringAsync().Result;
   Exception trueException = new Exception(exception);
   throw new Exception(trueException.Message);
}

I don't need to do this to throw an exception. That is a bad example. If I just want to elegantly get at what is at trueException.Message in the shape of a string how do I do so? That is the big question here.

Saturday, September 6, 2014

There is no trim in JS in IE8.

Imagine a long frustrated exhale here.

Sitecore

The Austin .NET meetup (a meetup.com group) met at a business called Engagency which does work within the sphere of "customer intelligence" (will explain, don't worry) and a Ben Bartlett of Engagency gave a talk on what Engagency does with Sitecore, an ASP.NET CMS which has a few surprising tricks up its sleeve that I've certainly not seen in working with DotNetNuke and Ektron. Sitecore has a capacity for recording clicks for unknown visitors and collecting this data into a record set about which certain assumptions may be made. The clicking upon one banner instead of another may be telling of a user's interests and similarly which pages beyond the home page are browsed may comparably be illuminating/insightful. Clearly, at an online storefront it is a goal for the keepers to make sales from visitors, but upstream of those acts there is another hurdle that must be cleared for a customer to make it all the way through the sales funnel to a conversion. A customer must transition from an unknown visitor to a known visitor. The moment at which a party enters his/her contact information in a form does not necessarily have to occur at the same moment that party is ready to check out and give credit card information. Ben did not say this out loud, but his talk sort of had a subtext suggesting that this may not be the best approach and that potential sales may be falling out of the funnel without a more refined means of engaging with potential clientele. For example, at http://sitecoredemo.namics.com/ which is a demo Sitecore app for a travel agency dubbed "Jetstream" the process from beginning to end through the sales funnel might look like so: an unknown visitor finds Jetstream online and lands at its homepage

  1. the IP address and geolocation (which is only so accurate) is recorded for the unknown visitor (this is the only implicit data we have of our guest so far)
  2. the visitor stays instead of abandoning the site and he/she clicks about some
  3. based upon a click on an advertisement for the Caribbean, Sitecore's analysis of the metrics within the implicit data we've gathered on our unknown guest tell us he/she is closest to fitting the persona of "Sally the Sunbather"
  4. in a face-to-face, technology-free conversation one might listen first and then respond, and in drawing a parallel here in our workflow we have listened to implicit data up to the point that we know we are talking to "Sally the Sunbather" and we next respond by slanting the banners and advertisements which appear at Jetstream's site to be tailored to Sally
  5. we get our Sally to visit a "let-us-keep-you-updated-on-specials" form slanted to Sallyesque interests and our Sally provides us with explicit data by completing the form (name, email address, etc.)
  6. we now have explicit data on Barbara Simmons which is superior to the implicit data we had on "Sally" as Barbara Simmons has become a known user, though we may not have come this far without attention to the implicit data
  7. at this point we are next walking through what Ben called an "engaging plan" in which we ask "where would you like to go?" followed by "would you like to look at flights to there?" followed by "would you like to book a flight?" as we chitchat our way to a conversion
  8. last step: Barbara Simmons makes a credit card transaction for an airplane ticket

The magic of Sitecore is that it records the implicit data of clicks here-and-there (customer intelligence) and tries to use it advantageously in the name of transitioning unknown visitors into known visitors.

Friday, September 5, 2014

Call an API controller with HttpClient from the C# side!

Following up on this, I found this which explains not only how to call an ASP.NET MVC Web API controller from within a regular MVC controller in C#, but also how to account for scenarios in which the API controller barfs.

using (var client = new HttpClient())
{
   client.BaseAddress = new Uri("http://www.example.com/");
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new
         MediaTypeWithQualityHeaderValue("application/json"));
   var whatever = new { Foo = 13, Bar = 42 };
   var response = client.PostAsJsonAsync("api/something",
         JsonConvert.SerializeObject(whatever)).Result;
   if (response.IsSuccessStatusCode)
   {
      MyCustomType myCustomType =
            response.Content.ReadAsAsync<MyCustomType>().Result;
      DoSomethingInteresting(myCustomType);
   } else {
      throw new Exception("Ouch!");
   }
}

 
 

Note that just as there is a .PostAsJsonAsync there is also a .PutAsJsonAsync and a bunch of other verb specific methods hanging off of HttpClient. The whatever variable above is the thing we are handing in to our ApiController at the method signature.

 
 

Addendum 9/27/2018: System.Net.Http is the namespace that drives HttpClient above.

Thursday, September 4, 2014

signing tokens

If application A and application B share a shared key for encryption then one of the applications could hand a "token" (perhaps a Guid) to the other both encrypted with the shared key and also outright unencrypted at the same time. The receiving party could then encrypt the unencrypted token with the shared key and validate its legitimacy based upon if it matches the encrypted token. In these circumstances there is of course the risk that the key becomes compromised (leaked) and it also would be wise if only two parties shared the same key regardless which is to say that if application A dreamt up the key to begin with and handed it to application B that application A should not give the name key to application C as well.

Only one partial class in C# needs to inherit from another class in order for the class comprised of partial classes to inherit from the parent.

This is a good trick for making generated code (which typical takes the shape of partial classes in sane implementations) play nicely with inheritance without manually changing generated code (which should smell like a bad idea to you).

Wednesday, September 3, 2014

make Visual Studio always "Run as administrator"

  1. right-click on the Visual Studio icon in the taskbar in Windows Server 2012 R2
  2. a menu will appear where you should right-click on "Visual Studio 2013" within the menu
  3. a second menu will appear and you should pick "Properties" from this menu
  4. a "Visual Studio 2013 Properties" dialog will appear and here you should pick the "Compatibility" tab
  5. check the checkbox for "Run this program as an administrator"
  6. click "Apply"
  7. click "OK"

Xsd2Code++

...is a tool for taking an XSD and automatically generating C# code to sanity check XML against the XSD and to serialize XML to and from a C# object of a shape consistent with the XSD. Subtle points such as whether or not a collection should end up as an array or a list on the C# side are customizable in Xsd2Code++ code too.

Addendum 11/18/2014:The classes Xsd2Code++ makes in C# are partial classes in the name of extensibility. As suggested above, there will be methods in the generated classes for deseralizing from and serializing to the type at hand.

When editing an XML file in Visual Studio 2013 there will be an XML menu at the toolbar.

pick "Create Schema" from this menu to make an XSD for the XML file

Tuesday, September 2, 2014

maybe create a sproc, but always alter it!

IF OBJECT_ID(N'dbo.Create_Response_Packet') IS NULL
BEGIN
   PRINT 'Create procedure : dbo.Create_Response_Packet'
   EXECUTE('CREATE PROCEDURE dbo.Create_Response_Packet AS RETURN 0')
      GRANT EXECUTE ON Create_Response_Packet TO Data_Intercept_Role
END
GO
ALTER PROCEDURE [dbo].[Create_Response_Packet]
(

reset your username/password in TortoiseSVN

  1. to clear the username and password in subversion
  2. right click on a folder and pick TortoiseSVN > Settings
  3. go to "Saved Data"
  4. click "Clear..." at "Authentication data"
  5. do something that would require you to be logged in as this should prompt you to log in anew

string whatever = Request.RawUrl;

...is a pretty good way to get what is at the URL line into a variable in C# in an ASP.NET MVC Controller action! However, if you are running an MVC site within an iFrame and you need to know the url at the browser itself and not at the iframe HTML tag you'd better use this instead:

string whatever = Request.UrlReferrer.OriginalString;