Tech in the 603, The Granite State Hacker

Rate Limiting Events with the Reactive Extensions Rx

A fun little challenge that came up at work…  we have a stream of events that we publish / subscribe via a Reactive IObservable.   One of the things we’re testing for is swamping the subscribers with events for periods of time.  The tools in System.Reactive.Linq namespace include utilities like .Throttle(…), .Sample(…).  None of these supported our needs.

For our needs in this particular event stream, in this point in our stream, we can’t afford to drop events.  

Sample(…) picks off an item at various intervals, dropping the rest.  Throttle(…) sets up a window of time. It won’t release any object until there’s been a case where only one object was buffered in the given time window.  If you get another while the window’s open, the window widens to the original timespan.

Then there’s .Buffer(…) which can store event objects for a window, and then release them.  That amounts to releasing all the events in periodic bursts, but it’s not a rate limit.

Finally there’s the .Delay(…) method… which, ironically, delays publishing objects by an offset amount…  but that delays all objects by the same time offset.  If you have three events come in, 1 millisecond apart each, and put a 1 minute delay on them, they’ll enter the collection, and one minute later, will be published out… in a three-millisecond burst.

I want to be able to constrain my publisher such that I only want n number of entities per second. 

My solution separates the pub/sub.  It loads a queue with incoming events, and emits them immediately, up to the limit on the subscriber side. On the publisher side, it resets the counter and emits any overflow objects in the queue, also up to the limit.   

Yes, this model has problems, so address your risks appropriately… (“use at your own risk”).    You can run out of memory if the origin provides more items than the limiter is allowed to emit over long periods of time.

Anyway, here’s a Program.cs with the RxHelper extension RateLimit(…).  The program has a decent little before/after RateLimit(…).



using System;
using System.Collections.Concurrent;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;

using System.Reactive.Linq;

 
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
 
            // simulate very fast (no delay) data feed
            var unThrottledFeed = GetFastObservableSequence();
 

            unThrottledFeed.Subscribe(Console.WriteLine);

            Console.WriteLine("That was an example of an event stream (with 100 events) only constrained by system resources.");

            Console.WriteLine();


            Console.WriteLine("Now rate-limiting at 10 items per second...\n");


            const int itemsPerSecond = 10;
 
            var throttledFeed = GetFastObservableSequence()
                    .RateLimit(itemsPerSecond);
 
 
            throttledFeed.Subscribe(Console.WriteLine);
 
            Console.WriteLine("END OF LINE");
            Console.WriteLine("Note that the Main() method would be done here, were it not for the ReadKey(), the RateLimit subscriber is scheduled.");
            Console.WriteLine();
            Console.WriteLine("Rate limited events will appear here:");
            Console.ReadKey(true);
 
 
        }
 
        #region Example Artifacts
        private static IObservable<TestClass> GetFastObservableSequence()
        {
            var counter = 0;
            var rnd = new Random();
            return Observable.Defer(() =>
                Observable.Return(0)
                    .Select(p =>;
                    {
                        counter++;
                        var x = new TestClass(30.0, counter);
                        x.Value += Math.Round(rnd.NextDouble(), 2);
                        return x;
                    })
                    .Repeat(100));
        }
 
        private class TestClass
        {
            public TestClass(double value, int instance)
            {
                Value = value;
                Instance = instance;
            }
            private int Instance { get; set; }
            public double Value { get; set; }
            public override string ToString()
            {
                return $"{Instance}: {Value}";
            }
        }
        #endregion
    }
 
 
   

    internal static class RxHelper
    {
        public static IObservable<TSource> RateLimit<TSource>(
            this IObservable<TSource> source,
            int itemsPerSecond,
            ISchedulerscheduler = null)
        {
            scheduler = scheduler ?? Scheduler.Default;
            var timeSpan = TimeSpan.FromSeconds(1);
            var itemsEmitted = 0L;
            return Observable.Create<TSource>(
                observer =>
                {
                    var buffer = new ConcurrentQueue<TSource>();
                    Action emit = delegate()
                    {
                        while (Interlocked.Read(ref itemsEmitted) < itemsPerSecond)
                        {
                            TSourceitem;
                            if (!buffer.TryDequeue(out item))
                                break;
                            observer.OnNext(item);
                            Interlocked.Increment(ref itemsEmitted);
                        }
                    };
                   
                    var sourceSub = source
                        .Subscribe(x =>
                        {
                            buffer.Enqueue(x);
                            emit();
                        });
                    var timer = Observable.Interval(timeSpan, scheduler)
                        .Subscribe(x =>
                        {
                            Interlocked.Exchange(ref itemsEmitted, 0);
                            emit();
                        }, observer.OnError, observer.OnCompleted);
                    return new CompositeDisposable(sourceSub, timer);
                });
        }
    }


}
 
 

Edit 1/27/2016:  Had to tweak RateLimiter(…) to immediately emit objects as long as it hadn’t hit it’s limit for the time span.  It always queues, just in case, to maintain order.

Tech in the 603, The Granite State Hacker

Live Process Migration

For years now, I’ve been watching Microsoft Windows evolve.  From a bit of a distance I’ve been watching the bigger picture unfold, and a number of details have led me to speculate on a particular feature that I think could be the next big thing in technology….   Live process migration.  

This is not the first time I’ve mused about the possibility… [A big feature I’d love to see in Windows 11] it’s just that as I work with tools across the spectrum of Microsoft’s tool chest, I’ve realized there are a few pieces I hadn’t really connected before, but they’re definitely a part of it.

What is live process migration?  Folks who work with virtual machines on a regular basis are often familiar with a fancy feature / operation known as live virtual machine migration….  VMWare’s vSphere product refers to the capability as vMotion.  It’s the ability to re-target a virtual machine instance, while it’s running… to move it from one host to another.

In sci-fi pseudo psycho-babble meta physio-medical terms, this might be akin to transitioning a person’s consciousness from one body to another, while they’re awake…  kinda wild stuff.

As you can imagine, live VM migration is a heavy duty operation… the guest machine must stay in sync across two host computers during the transition in order to seamlessly operate. For the average user, it’s hard to imagine practical applications. 

That said, live process migration is no small feat either.  A lot of things have to be put in place in order for it to work… but the practical applications are much easier to spot. 

Imagine watching a movie on Netflix on your Xbox (or maybe even your Hololens), but it’s time to roll.   No problem, with a simple flick gesture, and without missing a beat, the running Netflix app transitions to your tablet (or your phone), and you’re off.   Then you get to your vehicle, and your vehicle has a smart technology based media system in it that your tablet hands off the process to.   It could work for any process, but live streaming media is an easy scenario.

From a technical perspective, there’s a bunch of things required to make this work, especially across whole different classes of hardware…  but these problems are rapidly being solved by the universal nature of Windows 10 and Azure.

Commonality required:

  • Global Identity (e.g. Windows Live)
  • Centralized Application Configuration
    • Windows 10 apps natively and seamlessly store configuration data in the cloud
  • Binary compatibility
    • Universal apps are one deployable package that runs on everything from embedded devices to large desktops and everything in between.
  • Inter-nodal process synchronization
    • Nothing exemplifies this better than the 1st class remote debugging operation  in Visual Studio.  You can run an app on a phone or device from your laptop, hit breakpoints, and manipulate runtime state (local variables) from the laptop and watch the device react in real time.
  • Handoff protocol
    • I’m sure it exists, but I don’t have a good word to describe this, but it’s probably based on something like SIP
  • Runtime device capability checking (the part that sparked this blog post).
Over the years, there have been a lot of “write once, run anywhere” coding schemes.  Most involve writing a program and having the compiler sort out what works on each type of hardware…. what you get is a different flavor of the program for different kinds of hardware.  In Windows 10, it’s different.  In Windows 10, the developer codes for different device capabilities, and the application checks for the required hardware at run time.  
While the UWP does an amazing job of abstracting away the details, it puts some burden on the hardware at runtime…  the app developer has to write code to check, anyway: hey, is there a hardware camera shutter button in this machine?  If yes, don’t put a soft camera shutter button on the screen, but now the app has to check the hardware every time it runs.
I struggled a bit trying to understand this latter point…  why would Microsoft want it to work that way?  Except for a few plug & play scenarios, it could be optimized away at application install time…  unless your process can move to a different host computer/phone/console/tablet/VR gear.
While I am (more recently) a Microsoft V/TSP working for BlueMetal, an Insight company, I have no inside information on this topic.  I’m just looking at what’s on the table right now.   We’re almost there already.  Yesterday, I showed my son how to save a document to OneDrive, and within moments, pick up his Windows 10 phone and start editing the same document on it.
In my mind, there’s little doubt that Microsoft has been working its way up to this since Windows Phone 7… the only question in my mind is how many of these tri-annual Windows 10 updates will it be before “App-V Motion”-style live process migration is a practical reality.
Tech in the 603, The Granite State Hacker

Visual Studio 2015: An Insider’s Review

I apologize I’ve been pretty wrapped up in a little bit of everything, but I wanted to share a piece my colleague, Dave Davis, Architect at BlueMetal Architects wrote for SD Times:

https://www.bluemetal.com/News/Dave-Davis-Published-in-SDTimes

Well worth the read.

Tech in the 603, The Granite State Hacker

Apache Cordova and SharePoint Online / Office 365

The concept came from a good place, but at this point, the story is best described as “science experiment”, as I mentioned at SharePoint Saturday Boston 2015.  I was working on a cross-platform Apache Cordova project for Windows, Windows Phone and Android when the call for speakers hit.  I said “why not?” and I signed myself up to present it…

The good news is that the story’s not without some worth to someone exploring the idea of hooking into SharePoint from an Apache Cordova-based app. Tools that exist today at least assist in the process.

[office src=”https://onedrive.live.com/embed?cid=90A564D76FC99F8F&resid=90A564D76FC99F8F%21470742&authkey=AF2UYViSqPU21mw&em=2″ width=”402″ height=”327″]

The demo code is mostly about accessing files from your personal SharePoint profile document library (A.K.A. OneDrive for business) and indeed, the code is using file access code in addition to SharePoint connection.  The hardest work in a browser based app is to authenticate with Office 365, and this code does that, and then opens up to the rest of SharePoint…

[office src=”https://onedrive.live.com/embed?cid=90A564D76FC99F8F&resid=90A564D76FC99F8F%21470744&authkey=ABWELP8Z5xOqUSY” width=”98″ height=”120″]

Tech in the 603, The Granite State Hacker

A big feature I’d love to see in Windows 11

With all the announcements coming out of //Build, I’m pretty jazzed about what’s coming in Windows 10.   That doesn’t stop me from wishing there were one or two other scenarios Microsoft would get to… and at this point, I’ll have to hope to see them in something after Windows 10.

“App-V-Motion” running apps, migrating them across devices. 

Enable an app running on the phone or tablet or laptop or desktop to seamlessly transition from device to device.

Imagine it’s getting late in the day…  you have a long running process on your desktop that you need to babysit.  Poor timing, sure, but it happens far too often.   Now, rather than being tethered to your desk, you can transition the process to a mobile device, and simply take it with you.   Perhaps it’ll take longer to complete on the mobile device, so when you get home, you hand it back off to bigger iron. 

or, my other favorite scenario…  you’re watching your favorite movie, but it’s time to roll…. so you hand off the movie player app to your phone, and keep watching while you’re on the go, without missing a beat.

With cloud configuration & storage, this scenario is getting more and more feasible, but given where I’m seeing Windows 10, now, this could potentially be a 10.1 or 10.2 feature.

Tech in the 603, The Granite State Hacker

Apache Cordova and Windows Universal (8.1)

Thanks to everyone who made it out to the Granite State Windows Platform Users Group last night (April 16, 2015) to see my presentation on using Apache Cordova to create Windows Universal (8.1) “store apps”. 

I walked away feeling like I’d helped inspire everyone who attended…  even as an “intro” level presentation, the demos seemed to keep everyone engaged, asking questions, and prompting me to go “off-roading” to check out various features. 

We really had fun with it!

So while the best part of the presentation was the demos, the slides do have some great links in them.

[office src=”https://onedrive.live.com/embed?cid=90A564D76FC99F8F&resid=90A564D76FC99F8F%21370273&authkey=AKm8AYTLUY1iyG8&em=2&wdAr=1.7777777777777776″ width=”350″ height=”221″]
 
 

If you missed it, don’t worry too much…  I’ll keep this presentation dusted off & ready for upcoming events, as well…  I could imagine it fitting well into a Code Camp event or something akin to it in the coming year.  

Heck, feel free to reach out to me if you think this is something you’d like to know more about… I’m happy to have a chat about it.

Next month’s meeting is already scheduled…  we’re looking forward to Jim O’Neil coming to reprise his Boston Code Camp 23 presentation on Themes in Windows Universal (8.1).   Please join us!

Meetup:  http://www.meetup.com/Granite-State-NH-WPDev 



Tech in the 603, The Granite State Hacker

Getting Display Names from User Names in a hostile SharePoint environment

I recently ran into a nasty situation where I needed a reliable way to get a list of user Full Names (or Display Names) from a list of usernames in a SharePoint process.

The short answer was easy…  The code runs server side so…

SPUser theUser = web.EnsureUser(username);
string DisplayName = theUser.Name;

//Right?

Well, under normal circumstances, sure.  

In this circumstance, I was checking a list of lists of user names, a condition where I might need to check hundreds of items, each of which could have a list of users to check.

No biggie, just add a lookup table and cache the results over multiple calls so that I only ever have to look a user up once in my process.

Now here’s the real kicker.  In my target environment, EnsureUser comes back instantly if the username is a valid, active user in Active Directory.  If the user is not a valid user?   The command takes over 40 seconds per call to fail!

My solution was two-fold.  

1)  use the aforementioned cache strategy, which I have in my sample code below as _nameMap.
2)  Use a simple worker thread.  Give it two seconds to succeed.  Kill the thread if it takes longer than that for any reason.

I initially made the mistake of using SPContext.Current.Web in the thread, but that can *sometimes* produce a threading violation.   The code below creates a whole new instance of SPSite/SPWeb on every pass, but that’s a lot safer and better performing than a lot of alternatives.

private Dictionary _nameMap = new Dictionary();  

private string GetUsersWithTempCacheAndTimeoutEnforcement(string rawUsers)
{
string result = string.Empty;
SPContext.Current.Web.AllowUnsafeUpdates = true;
foreach (string aUser in rawUsers.Split(';'))
{
try
{
string addUser = string.Empty;
string checkUser = aUser.Split('#')[1];
if (checkUser.Contains("\\"))
{
lock (_nameMap)
{
if (_nameMap.ContainsKey(checkUser))
{
addUser = _nameMap[checkUser] + "; ";
}
else
{
SPUser userResult = null;
SPContext context = SPContext.Current;
string webUrl = context.Web.Url;

System.Threading.ThreadStart st = new System.Threading.ThreadStart(
() =>
{
try
{
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb web = site.OpenWeb())
{
userResult = web.EnsureUser(checkUser);
}
}
}
catch (Exception)
{ }
});
System.Threading.Thread workThread = new System.Threading.Thread(st);
workThread.Start();
workThread.Join(2000);
if (workThread.IsAlive)
{
workThread.Abort();

}
if (userResult == null)
{
_nameMap[checkUser] = checkUser;
addUser = checkUser + "; ";
}
else
{
_nameMap[checkUser] = userResult.Name;
addUser = userResult.Name + "; ";
}
}
}
}
result += addUser;
}
catch (IndexOutOfRangeException)
{
}
catch (Exception ex)
{
}
}
return result;
}

Tech in the 603, The Granite State Hacker

Reliving “Revolutionary” with Windows 8

“What do you think of Windows 8?”   I hear this question all the time… everywhere I go.   I hear people talking about it on the bus, in line at coffee shops, and even in odd places like hospital rooms.  It’s the biggest change we’ve had in the PC in well more than a decade.  Everyone knows this is as big as broadband in everyone’s home.

But… more than a decade?   Really? 

Definitely.  How old would a child be if it was born the last time there was a *true*, major version iteration of Windows?   3?  8…? 

How about…  18?   Yeah…  18… old enough to drive.  Old enough to be looking at colleges. The Daytona (Windows NT) / Chicago (Windows 95) user experience, were it a child, would now be looking at an opportunity to suffer the choice between Romney or Obama.  The experience unleashed on IT and the public introduced us to the Start menu, the Desktop, managed application installs, and several other major features that the enterprise and private user alike have now literally grown up on.

Some might argue that Windows XP was a hefty revision that almost qualifies, but I would say not so much.  Improvements abounded, but the core user experience hasn’t changed by more than revision increments in Windows 98, ME, 2000, XP, 2003, 2008, 7… really…  since Windows 95. 

But, with Windows 8, this changes.  Windows 8 brings us a whole new user experience in the “Modern UI” formerly known as “Metro UI”. 

If you recall, Windows 95 still essentially lived on top of DOS, and had enough of the Windows 3.x framework to run all the apps we’d already come to depend on (like Word 6, Excel 5, and Windows AOL 2.5).  While those programs ran in Chicago, there were compatibility issues, and the user interface really started to look crusty on legacy applications.  I was actually a relatively late adopter, waiting until Windows 98 before I finally succumbed to the dark side. (I had discovered IBM OS/2 Warp and become a fan… it actually took a 1-2 punch to Warp to get me to switch.  1:  When Warp was stable, it was unbeatable, but when it crashed it was unrecoverable, (and crash, it inevitably did).  2:   Command & Conquer / Red Alert, which had an improved video mode that was only available when installed in Windows… and it was even more awesome in that improved resolution mode. )

Just like Windows 95, Windows 8 is a transitional OS.

One of the big things I keep hearing about Windows 8 is… what a P.I.T.A. is is to figure out. “Microsoft is taking a huge risk with this… why are they breaking my Windows?”, I hear.  Or…  “I’m open-minded.  I subjected myself to it until the pain became unbearable.  (I can’t wait until Mac OS X takes over.)”

Transition, though?  Yes.  Transition.  Again, this is the first real full version increment of the Windows user experience that we’ve seen in years, and it all comes down to this Modern UI thing.  It does exactly what Windows 95 did to Windows 3.x on DOS.  It wipes the slate clean and re-imagines how we operate our computers from the ground up using modern human interface devices… (HIDs). 

Touch screen, movement, gestures, enhanced 3D graphics… these are things that started to accelerate development not long after the release of 95, but the world was still on the Windows 95 learning curve.  Hardware was too immature & expensive to develop an OS around them then… So, while you were getting comfortable with your desktop, (if you haven’t noticed) your cell phone’s user experience surpassed your desktop.

So on the surface (no pun intended) this is what Windows 8 is…  it’s a full OS-deep refresh that catches home computing back up to what people have gotten used to in their cellphones.

“Common sense” says this all implies a true P.I.T.A. for people and companies that dig in on it. 

Let’s look a little deeper, though, at what else this represents.  Again, this is a transitional OS.  It does everything the old user experience did… if you dig a bit.  It does this to support the old applications with their freshly encrusted-feeling user experience.  People can continue leveraging your old technology investments.  Indeed, you can continue making investments in the old user experience…  just know that the writing’s on the wall. 

It’s only a matter of time before people do what they inevitably did with Daytona/Chicago… adopt, extend, and embrace, or be extinguished.  

Why?  Because… when it comes down to it, the part that people really hate is not the “user experience” part.   It’s the “NEW” part that hurts.  Once the “NEW” wears off, what you’ve got left is a really genuinely cleaner, better, more efficient UI that leverages new hardware in important ways, and puts it years ahead of desktop OS competition, both in terms of capability, and even in terms of price point…  and pushes that same advantage out seamlessly to a myriad of other devices.  So getting past the sharp learning curve on one device means you’ll be rocking the new UI everywhere in no time.

Like the glory days of the Dot-Com boom, the days of Daytona & Chicago, these will be days of learning and technical renovation, even re-invention.  This is what I see coming with Windows 8 in the desktop, with an added benefit of being even more ubiquitous than it was back in the 90’s.  With the coming of Surface, Windows Phone 8, your apps will have more opportunity to run in more places, on more machines, than ever before…. using more “Star Trek” functionality than we’re yet used to. 

Those looking to remodel that kitchen… here’s your wake up call.  Windows 8’s user experience is representative of what made the Dot Com days so great… (and there were some plus sides.)  It was when leveraging any of the revolutionary new technology became a competitive advantage all by itself.  Early adopters will feel the pinch of the initial investment, but… with some planning, will reap the rewards by having that pain behind them by the time Windows 9 rolls around. 

I, for one, look forward to my new OS overlord.

Tech in the 603, The Granite State Hacker

Using Client Certs to Pull Data from WCF in SSIS Data Flow Transform Script

I’ve recently had the opportunity to brush off my SSIS skills and revisit this toolset.   In my most recent usage, I had a requirement to use SSIS to pull data from a WCF web service that was a) using the net.tcp protocol, and b) used transport security with a client X.509 certificate for authentication.

This was fun enough by itself.  Configuring WCF tend typcially to be non-trival even when you don’t have to tweak app.config files for SQL SSIS services.  One of my goals, in fact, was to avoid having to update that, meaning I had to put code in my SSIS Script block in the data flow to configure my channel & security & such.

Luckily, I was able to find examples of doing this with wsHttpBinding’s, so it wasn’t a stretch to tweak it for netTcpBinding with the required changes to support certificate authenticated transport security.

Here’s the code…

using System;
usingSystem.Data;
usingMicrosoft.SqlServer.Dts.Pipeline.Wrapper;
usingMicrosoft.SqlServer.Dts.Runtime.Wrapper;
usingSystem.ServiceModel;
usingSC_13defb16ae45414dbac17137434aeca0.csproj.PaymentSrv;


[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    ChannelFactory<IProfile> channelFactory;
    IProfileclient;
    public override voidPreExecute()
    {
        base.PreExecute();

        boolfireAgain = false;
        this.ComponentMetaData.FireInformation(0, “Pull From Profile Service.PreExecute”, “Service URI: ‘” + this.Variables.varProfileServiceUrl + “‘”, null, 0, ref fireAgain);
        this.ComponentMetaData.FireInformation(0, “Pull From Profile Service.PreExecute”, “Cert Fingerprint: ‘” + this.Variables.varClientCertFingerprint + “‘”, null, 0, ref fireAgain);

        //create the binding
        NetTcpBindingbinding = new NetTcpBinding();
        binding.Security.Mode = SecurityMode.Transport;
        binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
        binding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;

       
        EndpointAddressendpointAddress = new EndpointAddress(this.Variables.varPaymentServiceUrl);
        channelFactory = new ChannelFactory<IProfile>(binding, endpointAddress);

        channelFactory.Credentials.ClientCertificate.SetCertificate(
            System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
            System.Security.Cryptography.X509Certificates.StoreName.My,
            System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint,
            this.Variables.varClientCertFingerprint);
            //” x8 60 66 09 t6 10 60 2d 99 d6 51 f7 5c 3b 25 bt 2e 62 32 79″);

        channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode =
            System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
       
        //create the channel
        client = channelFactory.CreateChannel();

       
        IClientChannel channel = (IClientChannel)client;

       
        channel.Open();
        this.ComponentMetaData.FireInformation(0, “Pull From Profile Service.PreExecute”, “Open Succeeded.”, null, 0, reffireAgain);


    }

    public override voidPostExecute()
    {
        base.PostExecute();

        //close the channel
        IClientChannelchannel = (IClientChannel)client;
        channel.Close();

        //close the ChannelFactory
        channelFactory.Close();

    }

    public override voidInput0_ProcessInputRow(Input0Buffer Row)
    {
        GuidtxGuid = Guid.NewGuid();
        Profileprofile = null;
        try
        {
            profile = client.getProfile(txGuid, Row.ProfileId);
            Row.PSProfileType = GetProfileType(profile);
           
        }
        catch (Exception ex)
        {
            stringmessage = ex.Message();
            Log(message, 0, null);
        }
       
       
    }
    private string GetProfileType(Profileprofile)
    {
        return “x”;
    }
}

So one of the challenges I encountered while using this method had to do with the client certificate.  This error drove me nuts:

The credentials supplied to the package were not recognized.
Server stack trace:
   at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
   at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
   at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)
   at System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32 offset, Int32 count, Byte[]& output)
   at System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32 offset, Int32 count)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
   at System.ServiceModel.Channels.SslStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
   at System.ServiceModel.Channels.StreamSecurityUpgradeInitiatorBase.InitiateUpgrade(Stream stream)
   at System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, IConnection& connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, TimeoutHelper& timeoutHelper)
   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
   at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open()
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at System.ServiceModel.ICommunicationObject.Open()
   at ScriptMain.PreExecute()
   at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PreExecute()

If you look at it, this is an authentication error.  Tracing the code, it happens AFTER the code successfully retrieves the client certificate from the certificate store.  The call to SetServerCertificate succeeds without incident.

The error hits  when the code opens the channel, and tries to use the private key attached to the client certificate to prove to the server that “I’m a valid client.”

I went nuts because I was an administrator on the machine, and had installed the client certificate to the certificate store myself.  It initially worked, and there was no indication that there was a problem getting the certificate from the cert store.

It turns out that when you use the machine store under these circumstances, I needed to give myself explicit permission to the client certificate in order for the SetServerCertificate to get the private key along with the client certificate.  This was counter-intuitive for two *additional* reasons:  1)  I was an administrator on the box, and already should have had this permission by the fact that my login account belonged to the administrators group (which you can see from the pic below, also had access.)  2)   It worked the day before.  When I imported the private key originally to the key store, it appears somewhere in the depths of Windows 7 (and this applied on Server 2008 R2 as well) I still had permission in my active session context.  When I logged out, that login context died, and, coming back the next day, I logged in again, not realizing I wouldn’t be able to access the key.  Giving myself explicit permission as shown below allowed me to run my SSIS package within Visual Studio and from SSMS.

(Sorry, Blogger’s not letting me include this bigger… click it for full size view.)
Tech in the 603, The Granite State Hacker

Microsoft Announces Windows Phone Dev Center

I’ve learned a few things in the past months in working with the SharePoint community.  Namely, if you don’t have something nice to say, don’t say anything at all.  In today’s age of social media meeting business networking, this is more important than ever.  

I hope, however, that Microsoft’s Windows Phone Dev Team forgives me for the tough love I dished out on them back in May.  (I won’t even link to that post.)  

I love developing apps in Silverlight & C# for my phone, and I’m so happy to see an update that directly impacts us App Developers…  

Here’s the Windows Phone Developers Blog:
http://windowsteamblog.com/windows_phone/b/wpdev/archive/2012/08/07/meet-the-windows-phone-dev-center.aspx

Here’s the great looking new app publisher’s experience for Windows Phone Developers:
https://dev.windowsphone.com/

I haven’t fully explored it yet, but at first glance, it looks much more like the excellent developer’s & publishers’ experience I’ve come to take for granted from Microsoft… I can’t wait to explore it more and see how it all came together.