ASP.Net Controller API nuggets

Write Directly to Response Stream

Stack-o basically covers this already but kinda danced around how minimal the code can really be for the basic scenario…

//ignore this...
//e.g. $.ajax(url, { procName: "", parms: {deliveryDate:"3/2/2016"}, returnParmName: "" }, ...)
public class GenericProcArgs
{
  public string procName { get; set; }
  //from: http://stackoverflow.com/questions/5022958/passing-dynamic-json-object-to-c-sharp-mvc-controller
  //super convenient way to receive JS object with arbitrary properties to be fed straight to proc parms
  public dynamic parms { get; set; }
  /// <summary>
  /// whether to titleCase the JSON property names (handy for feeding auto built datagrids)
  /// </summary>
  public bool titleCase { get; set; } = false;
  public string returnParmName { get; set; }
}

//here's the beef...
public ActionResult GetProc(GenericProcArgs args)
{
  Response.ContentType = "application/json";

  using (var proc = new Proc(args.procName))
  {
    proc
      .AssignParms(args.parms as IDictionary<string, object>)
      .ExecuteJson(Response.OutputStream, args.titleCase);
  }
  return new EmptyResult();
}

  • in my experience, the ContentType wasn’t even necessary but it feels like good practice
  • here i’m using a database layer represented by my own custom Proc class… which is a bundle of convenient methods wrapped around SqlCommand … in this case, it’s firing SqlCommand.ExecuteReader() and writing the results directly to the response via Newtonsoft.Json StreamWriters… i honestly haven’t done a real profile on this call stack but it feels like a nice straight shot from sql streaming through web tier transform to client
  • another nifty nugget in play here is the usage of C# Dynamic to catch arbitrary JS objects posted from the ajax client, and that Dynamic is then inherently castable to a Dictionary

Kendo UI Nuggets

Grid doesn’t like spaces in dataSource field names

(I happen to be subscribing to KnockoutJS observable here to receive data feed but that naturally depends on your framework of choice.)
Typical Kendo JS error: invalid template
Particularly note the way the columns property is generated.
[crayon toolbar=”always” lang=”js”]
sigCapVm.packingSlips.subscribe(function (newval) {
var gridPackingSlips = $(“#gridPackingSlips”);
var kgrid = gridPackingSlips.data(“kendoGrid”);
if (kgrid && kgrid.columns.length) kgrid.dataSource.data(newval);
else {
if (kgrid) kgrid.destroy();
gridPackingSlips.kendoGrid({
//workaround for autogenerating columns with spaces
//from: http://www.telerik.com/forums/field-name-with-space-and-other-than-numeric-creating-issues-to-load-the-grid#23fk8zzWZkioYCn7Tr4xFg
columns: $.map(Object.keys(newval.length === 0 ? {} : newval[0]),
function (el) {
if (el.startsWith(““)) return; //by convention, don’t show fields starting with “
return { field: ‘[“‘ + el.replace(“#”, “\#”) + ‘”]’, title: el }
}), //hash aka pound (#) is special character in kendo template syntax
dataSource: { data: newval },
noRecords: { template: “no records found for those inputs” },
height: “20em”,
change: function (e) {
//good to remember that we’re not doing a true knockout binding here vs setting the grid’s dataSource.data property above
//so we have to “manually” connect the selected row back to the viewmodel here
var selectedPackingSlip = e.sender.dataItem(e.sender.select());
var vm = ko.contextFor(gridPackingSlips[0]).$root;
vm.selectPackingSlipId(selectedPackingSlip._PackingSlipId);
},
resizable: true,
//scrollable: false,
sortable: true,
filterable: false,
selectable: true
});
};
});
[/crayon]

Nuget Cheatsheet

tip command line
uninstall all packages matching pattern get-package | ? {$_.Id -like "Human*" } | % { uninstall-package $_.id } 1

  1. speaking of Humanzier, just install Humanizer.Core to get English only 

Updating 2006 MacBook Pro to Windows 10

There’s a fair amount of noise to wade through out there on this topic… this post is a humble gathering of the current state, cira February 2017… once we get the various bits lined up, it’s surprisingly smooth sailing with FULL compatibility under Windows 10 x64, even the latest “Anniversary Edition”… over 10 years later something as complex as Windows maintaining this much hardware compatibility is pretty amazing in our industry.

My Specific Hardware

  • MacBook Pro 2,1 17″ Late 2006, model A1212 – Core 2 Duo T7600 “Merom”

Hopefully these basic steps are still helpful to folks with similar oldness.

Creating Bootable Win10 Install Media

not as easy as one might think – this firmware is very finicky… USB Thumbdrive based boot is a complete no-go (everybody has tried, you won’t be the first : )… we must create a very specifically formatted boot DVD… but it’s not that bad

  1. Media Creation Tool – from any other working Win10 x64 you have handy, we get to start with MSFT’s very pleasant Windows 10 download utility… this will readily get us to an ISO file … but we’ll need to jack with a bit…
  2. “Multi-catalog” fix – this era of Apple machines were born with a rather anemic version of 32 bit EFI which only supports a very specific DVD ISO format (this guy had a good explanation under “How-to: Making a standard Linux distro ISO compatible with 32-bit EFI Macs”)… the gist is that MSFT tends to provide especially it’s x64 media via “Multi-catalog” ISO format, intended to support both “legacy” BIOS style booting as well as EFI… but our firmware is too brain dead and even though it’s kinda EFI, it can actually only handle BIOS style booting.
    1. first go ahead and mount that stock ISO on your working Win10 box…
    2. then the reformat is accomplished via oscdimg.exe cmdline:
      oscdimg.exe -n -m -be:\boot\etfsboot.com e:\ Win10_fixed.iso
      (replace e: above with whatever drive letter is assigned to your mounted iso)
  3. Burn Baby !! – now we’re clear to go ahead and burn that resulting “Win10_fixed.iso” to a DVD (I’m keen on ImgBurn).

Pretty Boot Selector Anyone ?

  • at this point we should be able to toss that DVD into our SuperDrive and power cycle while holding option to get the Mac’s native drive selection screen…
  • but to get a little more fancy, i’m keen on the rEFInd Boot Manager for a little more cute “OS selector” screen… easy steps:
    1. From the Mac side, download the latest zip… extract…
    2. and then from Mac Terminal: sudo ./refind-install

Prep your partition and Install

  1. Create New Partition – if you don’t already have an existing BootCamp parition – for the record, nothing specifically depends on using Mac Bootcamp Assistant tool’s magic… it’s totally fair game to use standard Mac Disk Utility to open a new partition for Windows to be installed to
  2. INSTALL – we’re finally ready to insert the DVD, power cycle while holding option and select the DVD icon to begin installing!
  3. (OPTIONAL) Format Existing Partition – after a couple prompts, you’ll get to the Win10 installer’s “partition selection” screen… if you’ve already got a previous Windows install, there’s a decision to be made… by default the installer will leave any previous Windows files on the drive under “windows.old” folder, to facilitate migrating your personal data… in my case, my drive is so small that i knew i had to format my existing BootCamp partition to provide all the room possible… this partition screen has handy options to do many basic partition maintenance tasks including format…
    • if you’re OCD like me, you can even jump out to a CMD.EXE prompt via SHIFT+F10 and do things like DISKPART to format with your preferred volume label (i’m keen on “BOOTCAMP”… be very careful to select the right disk and volume before executing FORMAT… DISKPART has zero safety rails.

Post Install – Detailed driver links and notes

  1. Intel Chipset Drivers – given this mobo is Core 2 Duo, ICH7 cira 2006, it most likely corresponds to Intel’s “900 series”… but there’s no real guesswork to be done here since the Intel chipset bundles cover a wide compatibility range and the most applicable one was last updated Version: 9.2.0.1030, Date: 4/21/2011… in my experience, chipset drivers can mean the difference between random crashes and rock solid stability so this install should not be skipped… if nothing else it tends to eliminate a lot of Device Manager red squigglies
  2. Video – ATI x1650 with DeviceId 71c5 – Microsoft provides a bundle technically labeled for “ATI FireGL V5200” but the corresponding INF files actually support many other related DeviceIds… make sure to go after the Win7 v8.561.0.0 bundle of the larger 20MB size (the smaller one didn’t hit for me)…
    • this is really the toughest piece to locate and get slammed in so, once you’ve got it nailed, the rest is all down hill =)
  3. BootCamp (v6) – it appears this old model Mac hardware aligns with the drivers included with BootCamp as of v4… but it seems a few bits might have been updated since then… so as one approach, start with installing v6 and then peanut butter the v4 bundle over that
    • BootCamp v4 & 5 are readily available via Apple Support but v6 is not… if you have a working Mac install around, the Boot Camp Assistant (BCA) will download the latest bundle… in Sierra’s BCA it’ll be under the “Action” menu… I wound up with v6.0.6136 as of 2017-06-13.
    • If you don’t have access to BCA, I found this helpful post which referenced direct Apple link to v6.0 build 6136
    • unzip that BootCamp v6 rar exe and fire up $\Apple\BootCamp.msi (as administrator required)… this will blast thru loading a bunch of drivers… many of which won’t actually apply to this machine’s hardware but really no harm-no foul as an initial base layer… if nothing else, it’s nice to have the latest BootCamp Control Panel icon in your task tray =)
  4. BootCamp v4 – now go back and fill in the following Win10 working drivers from BootCamp v4 bundle (v4.0.4326, direct):
    1. Audio = IDT SigmaTel (this’ll turn off the red light in the headphone jack : )
    2. iSight Web Cam
    3. BlueTooth – nothing kicked in till i ran Bluetooth “Enabler” Installer

Nirvana!

  • if all goes well (doesn’t it always? ; ) you should have a clean Device Manager with ZERO red squigglies, along with fully working…
  • Hardware accelerated video
  • HiDef Audio
  • iSight WebCam
  • BlueTooth – spoke too soon… Bluetooth stack was present and superficially happy looking but wouldn’t successfully complete pairing with Apple Keyboard… fortunately i also had a spare Broadcom BCM20702 Bluetooth 4.0 USB dongle and it lit right up and worked straight away… i’m loosely going to chalk this up to Windows 10 not having all the bits aligned to go back to the Bluetooth 2.0 era.
  • Working Sleep behavior via Lid Close, etc.
  • and Cute little BootCamp Control Panel tray icon

Misc Bits

  • Macs like to run on their Real Time Clock (RTC) corresponding to UTC… so if we want to play along we can set our BootCamp Windows to do the same… just right mouse on your task tray clock into “Adjust date/time” flip off/on the “Set time automatically” toggle to force system clock to update after applying that reg setting

It really does work!  : )

image

Fixing OpenSSL on WordPress Windows PHP 5.6+

Background:

i ran into OpenSSL errors during the Disqus plugin setup.
there’s tons of hits suggesting various solutions, below is the very simple solution that worked for me…

Sample error messages:

SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Failed to enable crypto in ...

TL;DR:

  1. download latest cacert.pem
  2. place it in a pertinent folder (e.g. $\wp-includes\certificates)
  3. edit your php.ini > openssl.cafile={full path to cacert.pem}

JavaScript (ES7) async wrappers perfect for Chrome.Bookmarks API

Background:

I tasked myself with a little project to sync my Chrome Bookmarks Bar with my Diigo links.

image

Chrome’s Bookmarks API is very straightforward but it is a traditional async callback style call… so it became a good opportunity for me to cozy up to EcmaScript v7’s (ES7) async/await support… since this is done in a Chrome Extension, it lends itself to this hard dependency on ES7 syntax…

async/await is supported as of Chrome v55 in Dec.2016

to me, the basic gist of this shift to async away from traditional callbacks means that we get to flatten all those nested callbacks like this:

//
call_method1(function(response1){
  call_method2(function(response2){
  });
});

to this:

//
let response1 = await call_method1();
let response2 = await call_method2();

admittedly, maybe not super dramatic when you boil it down like that but it really feels like previously complex nested code is easier to read/maintain and modularize when this is now available

Great async reference articles:

Code Nugget:

I want to elaborate further on the very happily working Diigo solution, but for now just the basic async bits…

//
//here's the wrapper
//one main thing to be aware of is that the native Promise object is what we can "await" on
function createBookmarkAsync(parms) {
  return new Promise(function(fulfill, reject) {
    chrome.bookmarks.create(parms, fulfill);
  });
}

//simple usage of the above wrapper
$('#btnRefreshDiigo').click(async function() { //CRITICAL = note the "async" before the function declaration... otherwise google unhelpfully reports that await is an undeclared identifier
  let diigoFolderId = (await createBookmarkAsync({parentId: "1", title: "Diigos"})).id;
  //now continue coding knowing that this code wont execute until the async call returns, very cool!!
}

Also handy for Fetch() API:

it was also great to use the very nicely straightforward new’ish Fetch API (Chrome v43+) and await on that response vs something like jquery.ajax

//
let response = await fetch(json_api_url, { credentials: 'include' }); //the credentials bit passes existing cookies (e.g. leveraging existing login)
let jsonText = await response.text();
let items = JSON.parse(jsonText).items;

[SOLVED] Certain Font Awesome icons not showing in Xamarin iOS

Problem

None of the icons in the FA v4.7 release were showing up for me, while all the others were… so I had a basic working scenario but not entirely.

Background

  • I was doing a simple approach of showing the icons in a Label like so:
    <Label FontFamily="FontAwesome" Text="&#xf2b5;" />
  • I had my FontAwesome.ttf file under the iOS project’s Resources folder and via a font explorer tool I confirmed that the v4.7 icons were indeed present in that file
    • for the record, the new v4.7 icons look to begin at unicode hex xf2b5 (“handshake-o”)
    • I also had my own FontAwesome.ttf listed under my Info.plist > UIAppFonts along with another custom font I was using successfully
  • From previous approach, I also had the Iconize library loaded… with it’s “iconize-fontawesome.ttf” listed in Info.plist as well

[crayon title=”broken Info.plist (excerpt)” toolbar=”always”]
UIAppFonts

iconize-fontawesome.ttf
iconize-material.ttf
RichardsonBrandAccelerator.ttf
FontAwesome.ttf

[/crayon]

Solution

The clue that tipped me off was that i noticed Iconize was built with an older version of FontAwesome… so as a guess, I re-ordered my FontAwesome.ttf entry ABOVE the iconize-fontawesome.ttf like below… and wouldn’t you know it, that actually did the trick! : )

[crayon title=”WORKING Info.plist (excerpt)” toolbar=”always”]
UIAppFonts

RichardsonBrandAccelerator.ttf
FontAwesome.ttf
iconize-fontawesome.ttf
iconize-material.ttf

[/crayon]

Automatic Header Links

I envied this little eye candy on some other blogs and it was easy to throw together.
 
image

If you’re on WordPress, a plugin like Simple Custom CSS and JS comes in handy for stuff like this.

CSS

a.headerLink:hover {
  color: inherit;
  opacity: 1;
}
a.headerLink {
  position: relative;
  transition: opacity 0.5s ease-in-out;
  cursor: pointer;
  opacity: .2;
}
a.headerLink i.fa {
  position: absolute;
  left: -1.5em;
}
a.headerLink:focus {
  color: inherit !important;
}

JS

  $(':header:not("[class]")').each(function(idx, el){
    var l = $(el);
    var name = l.text().replace(/\W+/g, "");
    l.prepend('<a name="'+name+'" class="headerLink" href=#'+name+'><i class="fa fa-chain"></i></a>');
  });

Xamarin iOS Provisioning Gotchas

I managed to create scenario where debugging from Visual Studio 2017 to iOS Simulator was giving me absolute fits because the error messages are so unhelpful… as usual, it was my own fault of course, but gosh it’s scary how easily one can fall in that deep dark pit where hopes and dreams go to die ; )

Example Error Messages

  • Application X need to be rebuilt due to an inconsistency between the connected Mac and the local app
  • Visual Studio cannot start the application automatically because it was signed with a Distribution provisioning profile. Please start it by tapping the application icon on the device

TL;DR

In my case it was because the “Bundle ID” aka “App ID” set in my info.plist was incompatible with the provisioning profiles actually available on my Mac build host and selected in the iOS project settings.

More background

  1. My Provisioning Certificates had expired (as we know, issued from http://Developer.Apple.com) … that did throw me off for a bit but eventually I got the clue and went through the Apple Developer account renewal process…
  2. Funny thing, I’d been waiting for our Apple Enterprise Developer aka In House distribution account to finalize… I noticed it had finally opened up (there’s a big yellow sign indicating 2wk delay between approval and the corresponding “In House” radio button becoming available on the provisioning profile page) and decided to just run with that vs my personal Developer keys…
  3. This meant I was creating all the necessary provisioning bits from scratch…
  4. First up, creating my App ID aka Bundle Id record (cue foreboding thunderclap)… ‘course when you’re establishing a new name, it’s always fun to apply your more current understanding of just what that name should be… here’s where I messed up, this App ID gets embedded in the provisioning profile which must then be the same as what’s in your iOS project’s info.plist > CFBundleIdentifier entry !!
  5. So while I did realize I needed to go select those new Identity/Provisioning profile entries in the iOS project settings > iOS Bundle Signing page, there’s nothing obvious in the error messaging to smack us in the head about App Id conflict.

Saving Grace

reading this post… suggested compiling under Xamarin Studio on the Mac for more error visibility… that’s a good basic technique reminder… I also use Xcode for this at times… at this point we’ve got Visual Studio for Mac so i fired that up and it did indeed provide significantly more helpful messaging, which got me back on track – Good to know !

Developer vs Distribution Profile – what’s the difference?

Somehow I’d never really run smack into this but one pertinent difference during development is that choosing a Distribution Profile will require you to manually launch your app on the iOS Simulator vs Visual Studio being able to launch it for you… so choose a Developer profile until you’re really in the mode to push builds out to real end user devices.

image

Aurelia – initial paper cuts

Baseline Wishlist for Dev Tools & Architecture

  • JS Framework: Aurelia (i’m coming from KnockoutJS most recently and keep hearing good things about Durandal v2, aka Aurelia … namely, clean conventions based on vNext web standards, etc.)
    • JS “evolution”: TypeScript (i’m jacked TS v2.1 finally achieved transpiled async/await support for ES5)
  • IDE: Visual Studio 2017 (currently RC2)
  • Web Server: Asp.Net Core, and generally try to track on .Net Standard / Core

Base Installs

(followed this guide up to the create project step)

  • latest nodeJs, this brings npm (node -v, i’m on v7.3.0)
  • latest jspm: npm install -g jspm (jspm -v = 0.16.48)
  • latest typescript: npm install -g typescript (tsc -v = Version 2.1.4)
  • latest typings: npm install -g typings (typings -v = 2.1.0)
  • latest .Net Core (equivalent github downloads page) (dotnet --version: 1.0.0-preview4-004233)
    • However, my yeoman generated csproj was complaining about missing asp.net core 1.1.0 dependencies so needed to get new bits… after installing .Net Core v1.1.0, dir C:\Program Files\dotnet\shared\Microsoft.NETCore.App showed i had a new 1.1.0 folder but dotnet --version still shows 1.0.0-preview4-004233 … need to be a little more enlightened about how this stuff sits

Project Starter Template

went looking for a more streamlined template project story than what was current as of the above guide…

Microsoft ASP.NET Core JavaScript Services which, AWESOME, includes yeoman generator specifically for Aurelia -AND- Visual Studio 2017 CSPROJ style, no way!!
(nice! they just updated the JS Services docs to include Aurelia 4 days ago :)
npm install -g yo generator-aspnetcore-spa
cd your_new_empty_project_directory
yo aspnetcore-spa

image

Debugging on iOS Chrome

No iOS browser provides any debugger tools -BUT- on Mac, we can fire up the Xcode iOS Simulator => Browser and attach Mac Safari to get full debug tooling!

  • Install Xcode from the App Store (free)
  • Launch Simulator from Xcode > Xcode main menu > Open Developer Tool > Simulator
    • fire up your url in iOS Chrome/Safari
  • Stack-o post for Mac Safari remote debug config – the gist:
    • Mac Safari > Preferences > Advanced > “Show Develop menu in menu bar”
    • Mac Safari > Develop menu > Simulator > choose desired browser tab by url

image

Aurelia Fetch Client and uncle PolyFill

  • i needed above js debug because my app skeleton’s “Fetch data” page worked on Windows Chrome but failed on iOS Chrome…
  • wound up finding this issue (over 1yr old)
    referring to fetch polyfill npm install whatwg-fetch --save… which sure enough, along with Aurelia’s Bring your own polyfill docs, wound up resolving my issue – yay!
    [crayon title=”$\ClientApp\app\components\fetchdata\fetchdata.ts” toolbar=”always”]
    import ‘whatwg-fetch’; //this is the new line
    import { HttpClient } from ‘aurelia-fetch-client’;

    [/crayon]

Misc Configs

  • handy reminder, enable external access to IISExpress site (e.g. so a mobile on your LAN can get to it):
    • first add site binding:
      [crayon title=”$\.vs\config\applicationhost.config” toolbar=”always”]

      <system.applicationHost>








      [/crayon]
    • then from command line:
      netsh http add urlacl url=http://address:port/ user=everyone

Off to the races?

basic working project.
working server side debug.
working client side debug.
working ajax call.
fresh copy of “Learning Aurelia” on the Kindle

I’m gone like the wind!