Connect() 2014

So the company I work for got the opportunity to present in a customer panel at Connect this year, and I was one of the 'speakers'. Microsoft did a great job of making the trip awesome for us, and the event itself was a ton of fun.

If you are bored, you can check out the promo video here: http://channel9.msdn.com/Events/Visual-Studio/Connect-event-2014/Skanska-USA-Visual-Studio--Azure , the talking session itself wasn't recorded.

 

However, all of that is *totally* irrelevant to the best part of the trip. Our handler the first night asked if there was anything he could do for us, and I said I always wanted to meet Scott Hanselman and then immediately forgot about it, they always ask things and I wasn't really expecting anything, so I didn't think about what I would *actually* do if he showed up....

 

So about 15 minutes later, Scott Hanselman walks up and introduces himself and I......

.....

.....

....totally stood there with my mouth hanging open until he left.

 

*SCORE*, got to meet Scott Hanselman...heh

 

You're doing it totally wrong if you can't laugh at yourself, even if it sucks when it happens Sealed

Honeywell "No Signal"

I had to reset my wireless Honeywell thermostat, wireless in has a base station mounted to the furnace, not wireless as in accesses the internet, and it was a bit of a pain, so I wanted to document it here.

Hold down 'Fan' and the Up arrow.

Hit next until the left number is 39, then up/down until the right number is 0. Then hit Done until it starts searching. It will find the base station that 5 minutes ago it couldn't and you will once again have heat/air.

Done!

INTERCAL string generator in C#

If you don't know what INTERCAL is, you probably don't want to. If you do, the you probably know how exciting it is to create strings in. So I wrote a quick console app in C# that takes a string and spits out the INTERCAL to generate the same output.

In case you are wonder, to print Hello World! in INTERCAL, the code looks like this:

DO ,1 <- #12
PLEASE DO ,1 SUB #1 <- #238
DO ,1 SUB #2 <- #108
DO ,1 SUB #3 <- #112
DO ,1 SUB #4 <- #0
DO ,1 SUB #5 <- #64
PLEASE DO ,1 SUB #6 <- #242
DO ,1 SUB #7 <- #26
DO ,1 SUB #8 <- #244
DO ,1 SUB #9 <- #168
DO ,1 SUB #10 <- #24
PLEASE DO ,1 SUB #11 <- #16
DO ,1 SUB #12 <- #162
PLEASE READ OUT ,1
PLEASE GIVE UP

C# code to generate intercal strings is below (No code reviews, I know its ugly and hacky, let a man have a moment's fun!):

namespace IntercalStringCreator {
    class Program {
        static void Main(string[] args) {
            string text = string.Empty;
            do {
                Console.Write("Enter text:");
                text = Console.ReadLine();
                int previous = 0;
                int next = 0;
                int displayNext = 0;
                string output = string.Empty;

                var bytes = ASCIIEncoding.ASCII.GetBytes(text);

                Console.WriteLine();
                Console.WriteLine("DO ,1 <- #" + bytes.Count());

                for (int i = 0; i < bytes.Count(); i++) {
                    next = bytes[i];
                    displayNext = GetNext(previous, next);
                    Console.WriteLine((i%5 == 0 ? "PLEASE " : string.Empty) + "DO ,1 SUB #{0} <- #{1}", i + 1, displayNext);
                    previous = next;
                }
                Console.WriteLine("PLEASE READ OUT ,1");
                Console.WriteLine("PLEASE GIVE UP");
                Console.WriteLine();
            } while (text != string.Empty);
        }

        static int GetNext(int previous, int desired) {
            int reversedoriginal = Reverse(previous);
            int reverseddesired = Reverse(desired);
            return Fix(reversedoriginal - reverseddesired);
        }

        static int Reverse(int x) {
            string s = Convert.ToString(x, 2).PadLeft(8, '0');
            if (s.Length > 8) {
                s = s.GetLast(8);
            }
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            s = new string(charArray);
            return Convert.ToInt32(s, 2);
        }

        static int Fix(int x) {
            string s = Convert.ToString(x, 2).PadLeft(8, '0');
            if (s.Length > 8) {
                s = s.GetLast(8);
            }
            return Convert.ToInt32(s, 2);
        }
    }

    public static class StringExtension {
        public static string GetLast(this string source, int tail_length) {
            if (tail_length >= source.Length)
                return source;
            return source.Substring(source.Length - tail_length);
        }
    }
}


Remember, with great power, comes great responsibility.

Bob shows up in a Microsoft video

Microsoft did a customer story about one of our apps at Skanska as part of the Azure usage push. You can check it out here: https://customers.microsoft.com/Pages/CustomerStory.aspx?recid=5847 (I am in the developer view video).

I wasn't going to be in the video, but a last minute issue meant another developer was unavailable, so I basically did it all off the cuff. They did a pretty good job keeping me from looking like an idiot, but I am sure it took a lot of editing. They even have my job title as Code Poet, which is a win to me :) (Actually our communications team made them put my real job title in there with it because they hate happiness)

Anyhow, good times, and I do really enjoy some of the speed of delivery Azure has given us, so my praise was totally valid :) Now if they would just finish App Insights.... ;)

 

Link Bomb (mostly angularjs stuff)

http://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make

http://devchat.tv/adventures-in-angular/010-aia-preferred-backends

http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-i-the-fundamentals

https://github.com/witoldsz/angular-http-auth/blob/master/src/http-auth-interceptor.js

http://bootsnipp.com/resources

 

Introverts rule… quietly. - rands

Windows 8 Multimonitor Trick

This might be common knowledge, but I wasn't aware, so it might help someone else as well.

Typically the clock on the task bar only shows up on the primary monitor, so if you are running something that runs full screen on the primary monitor (i.e. a game), you can no longer easily see what time it is. If you right click the task bar and untick 'Lock all taskbars' you can drag the 'primary' task bar to another screen. Then you can do your thing and still see when it is way past time for you to have went to bed :)

Sadness surrounds the iPad office apps

I was pretty excited to check them out since I have several licenses to Office 365.

Imagine my surprise when I found out Office 365 Small Business means I can't edit documents, I have to upgrade to Office 365 Small Business Premium...

Thanks, I guess?

Loop compare property values of two instances

Something quick and dirty, and it isn't recursive so it just does the first levelish, but that is all I needed.

    public class CompareEngine {
        public bool Compare<T>(T left, T right) where T : class {
            return Compare(left, right, new string[]{});
        }
        public bool Compare<T>(T left, T right, params string[] ignore) where T : class {
            if (left != null && right != null) {
                var type = typeof(T);
                var ignoreList = new List<string>(ignore);
                var unequalProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => !ignoreList.Contains(x.Name))
                    .Where(x => type.GetProperty(x.Name).GetValue(left, null) != type.GetProperty(x.Name).GetValue(right, null)
                        && (type.GetProperty(x.Name).GetValue(left, null) == null || 
                            !type.GetProperty(x.Name).GetValue(left, null).Equals(type.GetProperty(x.Name).GetValue(right, null))))
                    .Select(x => new { x.Name, Left = type.GetProperty(x.Name).GetValue(left, null), Right = type.GetProperty(x.Name).GetValue(right, null) });
                unequalProperties.ToList().ForEach(x => Console.WriteLine("Property not equal {0} left is {1} right is {2}", x.Name, x.Left, x.Right));
                return !unequalProperties.Any();
            }
            return left == right;
        }
    }

 

Code Comments

"Don't comment bad code - rewrite it"

    -- Brian W. Kernighan and P.J. Plaughter

Knockout Table Sorter Binding

I grabbed the original code off of a stack overflow post and just updated it to handle nulls and made it case insensitive.

To use, alter THs to this where you want them to sort.

<th data-bind="sort: { arr: Accounts, prop: 'AccountName'}">Account Name</th>

ko.bindingHandlers.sort = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var asc = false;
        element.style.cursor = 'pointer';
        element.onclick = function () {
            var value = valueAccessor();
            var prop = value.prop;
            var data = value.arr;

            asc = !asc;
            data.sort(function (left, right) {
                var rec1 = left;
                var rec2 = right;
                if (!asc) {
                    rec1 = right;
                    rec2 = left;
                }
                var props = prop.split('.');
                for (var i in props) {
                    var propName = props[i];
                    rec1 = rec1[propName];
                    rec2 = rec2[propName];
                }
                return rec1 == rec2 ? 0 : (!ko.utils.unwrapObservable(rec1) ? rec1 : rec1().toLowerCase()) < (!ko.utils.unwrapObservable(rec2) ? rec2 : rec2().toLowerCase()) ? -1 : 1;
            });
        };
    }
};

Modernizr

An odd comment to find in something so widely used...Of course I only found it when I was checking to make sure I had removed all of my own cursing alerts...

//   daneden.me/2011/12/putting-up-with-androids-bullshit/

First day of each month in a date range

Borrowed the initial query from stack overflow, but tweaked it for my needs. Used getdate to make my specific range in this example version. Have had to solve this specific issue a couple of times and got tired of having to rewrite it so I wanted to store a copy here ;)

WITH mycte AS (
  SELECT getdate() DateValue
  UNION ALL
  SELECT  DATEADD(MONTH,1,DateValue)
  FROM    mycte   
  WHERE   DateValue < dateadd(MONTH,24,getdate())
)

SELECT  DATEADD(m,DATEDIFF(m,0,DateValue),0) as FirstOfMonth
FROM    mycte
OPTION (MAXRECURSION 0)

Random Link Post

Disk2VHD

Microsoft Code Samples

Synergy

Simplexity

Planets

Removing the requirement for encryption on your custom STS while in development

When working locally with claims, it is nice to be able to remove SSL and cert encryption for the convenience of your environment, though you would of course want to re-enable it for production.

Most of the changes are pretty obvious until you get to what needs to change in the Issue method in your custom SecurityTokenService.

I think the easiest path is just grab the override method below. I left their block of code in that normally stops you from progressing (mainly the signingcredentials) so you can re-enable it with whatever parameters you are using to decide if you are enforcing credentials.

        public override RequestSecurityTokenResponse Issue(ClaimsPrincipal principal, RequestSecurityToken request) {
            if (request == null) {
                throw new ArgumentNullException("RequestSecurityToken can not be null");
            }
            this.ValidateRequest(request);
            Scope scope = this.GetScope(principal, request);
            if (scope == null) {
                throw new ArgumentNullException("Scope can not be null");
            }
            this.Scope = scope;
            this.SecurityTokenDescriptor = this.CreateSecurityTokenDescriptor(request, scope);
            if (this.SecurityTokenDescriptor == null) {
                throw new ArgumentNullException("SecurityTokenDescriptor can not be null");
            }
            SecurityTokenHandler securityTokenHandler = this.GetSecurityTokenHandler(request.TokenType);
            if (securityTokenHandler == null) {
                throw new ArgumentNullException("SecurityTokenHandler can not be null");
            }

            //if (this.SecurityTokenDescriptor.SigningCredentials == null) {
            //    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString("ID2079"));
            //}
            //if (this.Scope.TokenEncryptionRequired && this.SecurityTokenDescriptor.EncryptingCredentials == null) {
            //    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString("ID4184"));
            //}

            SecurityTokenDescriptor.TokenIssuerName = GetIssuerName();
            SecurityTokenDescriptor.Lifetime = this.GetTokenLifetime(request.Lifetime);
            SecurityTokenDescriptor.Proof = this.GetProofToken(request, scope);
            SecurityTokenDescriptor.Subject = this.GetOutputClaimsIdentity(principal, request, scope);
            if (string.IsNullOrEmpty(request.TokenType)) {
                string[] tokenTypeIdentifiers = securityTokenHandler.GetTokenTypeIdentifiers();
                if (tokenTypeIdentifiers == null || (int)tokenTypeIdentifiers.Length == 0) {
                    throw new ArgumentNullException("TokenTypeIdentifiers are required");
                }
                SecurityTokenDescriptor.TokenType = tokenTypeIdentifiers[0];
            } else {
                SecurityTokenDescriptor.TokenType = request.TokenType;
            }
            SecurityTokenDescriptor.Token = securityTokenHandler.CreateToken(SecurityTokenDescriptor);
            SecurityTokenDescriptor.AttachedReference = securityTokenHandler.CreateSecurityTokenReference(SecurityTokenDescriptor.Token, true);
            SecurityTokenDescriptor.UnattachedReference = securityTokenHandler.CreateSecurityTokenReference(SecurityTokenDescriptor.Token, false);
            return this.GetResponse(request, SecurityTokenDescriptor);
        }

Godaddy SSL crt to pfx

I had to do this twice and had to look it up both times, so I figured I would write it down this time.

The easiest way to get from a godaddy .crt cert to a pfx is to go to the machine where you originally requested the cert, go into IIS and complete the certificate request pointing it to the crt file.

Since that machine has the private key, once you have it in IIS, its a simple matter to just export it, which exports as a pfx.

If you don't still have the original requesting machine (or at least the private key somewhere else), you'll have to re-request your cert from godaddy using a different CSR.

Linq to JDE and composite keys

So I ran into an error:

'Both the operands in a predicate cannot be parameter markers' and a bunch of other words, but that seemed to be the main magic doing code first to a view over a linked server an AS/400.

The view didn't have a unique column, so I tagged 2 columns as key and gave them orders to treat them like composite keys.

Seems JDE didn't like that, the end solution was to just add a newid() as Id column to the view, tag that as key in code first and call it done.

Generic Cache Manager

I don't remember where I got the original idea, but I have used this enough I thought I would write it down. You'll need to reference System.Runtime.Caching

    public static class CacheManager {
        public static T GetObject<T>(string key) {
            if (MemoryCache.Default.Get(key) != null) return (T)MemoryCache.Default.Get(key);
            return default(T);
        }

        public static void AddObject<T>(T customObject, string key) {
            AddObject(customObject, key, TimeSpan.FromDays(2));
        }

        public static void AddObject<T>(T customObject, string key, TimeSpan duration) {
            var c = new CacheItemPolicy();
            c.SlidingExpiration = duration;
            MemoryCache.Default.AddOrGetExisting(key, customObject, c);
        }
    }

No available connection to selected VM Network can be found

I ran into an issue migrating me virtuals from my old Windows 2008 R2 box to my 2012 R2 boxes with the error 'No available connection to selected VM Network can be found'

Found the answer on technet here:

Copy and pasted it below so I could find it later when I need it. The only difference I did was selecting the destination network in the migration wizard.

  1. Shut down the virtual machine you want to migrate.
  2. In VMM 2012 > 'VM's and Services' Right click on the virtual machine, click properties.
  3. Click "Hardware Configuration"
  4. Scroll down to Network Adapters and choose, you network adapter.
  5. Under connectivity, choose "Not Connected". Click ok.
  6. You should then be able to migrate the virtual machine.
  7. Once the migration is complete, go back into the Network Adapter properties.
  8. Click "Connected to a VM network"
  9. And choose a VM network available. I didn't worry about the VM Subnet section and just left it blank. Click ok
  10. Turn on the virtual machine. Complete.

Tessel

These little devices look pretty awesome, and I love their concept of doing embedded controller work in javascript as more and more 'things' become always on and connected.

http://tessel.io/

http://creativejs.com/2013/08/tessel-a-javascript-programmable-micro-controller-board/

http://www.slideshare.net/TechnicalMachine/tessel-the-end-of-web-development-as-we-know-it

 

Their trigger model for handling events looks very similar to everything else we are seeing from node/azure notifications etc. One of the commenters says everything being written with javascript is a fad and he might be right, but it sure is awesome for the now.

XCode 5 and TFS 2013 RC Access Denied

So we recently started moving some of our source code to TFS 2013, especially for our apps that have iOS clients, since using git with XCode works so much better than the SVN hack we were using over TFS 2012.

As we switched over to XCode 5, we suddenly found ourselves unable to connect. From the GUI, it was basically just hanging, in the command line, it was telling us it was getting access denied. (The GUI was saying the same thing in a Fiddler trace).

From what I can tell the issue is with XCode, but the work around ends up being pretty straight forward. If you open TFS in Safari (http://server:8080/tfs) and let it keychain your credentials, you can then open it in XCode 5 as well. Ours still asked us for username and password when we set up the repository, but it did work at that point.

Video of the Day

Using Elmah from a Console App (etc)

So, while Elmah isnt really a good fit, since it is designed to work with all of the magic of the web, you may want to use it from winform/console etc just to continue to log to a consistent place, and in a consistent format. There are a few oddities, but all in all it is pretty straight forward.

Add these items to your app.config, just like you would your web.config.

<configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>
  </configSections>
  
  <connectionStrings>
    <add name="elmah-sqlserver" connectionString="Data Source=DatabaseOfAwesome;Initial Catalog=CatalogOfAwesome;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  
  <elmah>
    <errorLog type="Elmah.SqlErrorLog, Elmah" applicationName="App of Awesome" connectionStringName="elmah-sqlserver" />
  </elmah>
 
You'll need to add a reference to System.Web (ick).
Then your code just looks like this:
try 
{
    throw new NotImplementedException();
} 
catch (Exception ex) 
{
    ErrorLog errorLog = ErrorLog.GetDefault(null);
    errorLog.Log(new Error(ex));
}
BAM!

Adding an existing XCode project to git and tfs

We've been using a subversion hack with TFS for our iOS development, and while it has allowed us to keep our source code all in one place, the experience has been...less than optimal.

Now that we have the fancy new shiny TFS set up, we can work directly in TFS through a git project, but being new to git it took a bit to sort out how to get our existing code into this new unicorn dust.

I wanted to document the flow of that here because I am sure I will forget before the next time I have to do it... 1 and 2 are only needed if you are using SVN currently.

1) If you don'y have hidden files turned on, you need to do that.
2) Go into all the folders in Finder and delete the SVN folders 
3) Open terminal
4) CD to your project directory
5) git init
6) git add.
7) git remote add origin http://yourtfs:8080/tfs/yourcollection/_git/yourproject
8) git push commit -m "Initial commit to git"
9) git push origin master

Step 7 assumed you have already created the appropriate git repo in TFS, step 9 actually pushes the files up to TFS

Add your repo to XCode, I tend to delete everything and Clone from TFS at this point, but that is probably just my silliness.

If you are used to TFS etc instead of git, it will be important to know that as you commit your changes in XCode, it is only saving to your local copy of the repo. To push to your remote repo, you'll need to open terminal, cd to your project folder and run git push

Parsing MVC Web Api Dates in Objective C

There is a lot of weird information on the web about this problem, so I wanted to put this down somewhere I wouldn't lose it.

NSDateFormatter *webAPIFormatter = [[NSDateFormatter alloc] init];
[webAPIFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[webAPIFormattersetDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS"]; NSDate *date = nil; NSError *error = nil; [webAPIFormatter getObjectValue:&date forString:"2013-07-25 04:32:20.08" range:nil error:&error];

If you are returning .ToUniversalTime() from your APIs, you would want to change the date format line to:

[webAPIFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSZ"];

and of course change the time zone if you aren't using UTC.

Random Link Post

http://devdocs.io/
http://www.vickiwenderlich.com/
http://docs.nuget.org/docs/creating-packages/hosting-your-own-nuget-feeds
http://blogs.msdn.com/b/uk_faculty_connection/archive/2013/07/08/learn-how-to-write-a-3d-software-engine-from-scratch-in-c-winrt-amp-in-html5-using-typescript-or-javascript.aspx
http://trianglecocoa.com/
http://conceptnet5.media.mit.edu/