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/

 

Invaders

I made all new graphics for my silly Invaders game using Inkscape and I have to say, its a cool little tool and mighty fine for being free.

I published it to the Windows Phone Store this morning, and Balmer immediately emailed me to tell me he was still mad at me. I don't even remember what we were arguing about anymore.

Nooooooo

http://nooooooooooooooo.com/

Random Link Post

Cocoa is my Girlfriend 

Simple Bank

Google Diff Match Patch 

How to Build a Tardis Replica 

Mr Data Converter 

Project Euler

 

 

 

 

Revisiting Invaders

So a long time ago, I posted code for what basically amounts to a clone of the Atari 2600 version of Space Invaders, rewritten in XNA.

 

I got bored the other day and ported it to Windows Phone. I went with Phone 7 so I could be lazy and continue using XNA, since Microsoft hates us and hasn't/probably isn't porting XNA to Phone 8 ever.

I had to hack around some custom config code I had to dynamically load different 'skins' for the invaders, but for the most part the majority of it went very fast (took about 3 hours).

Screenshot for now, once I clean it up I'll post the code.

I would submit it to the Windows Store, but I can't imagine it going through without someone suing me. There is, however, a version that looks like it is a clone of the arcade version, so who knows, maybe I'll do it and just see what happens. 

Convert NULL to nil

A macro I stole off of the internet, but didn't want to lose.

I found when I was parsing a nullable type from web api -> JSON into my objects in iOS, it really didn't like the NULL values much and this sorted it nicely, converting them to nul inline.

Just wrap whatever you are assigning in NULL_TO_NIL() and you are good to go.

Just add it to the top of the page, or to some common blah blah whatever.

#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })