<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Wesley Bakker</title><link>https://weblogs.asp.net:443/wesleybakker/</link><description>Interesting things I encounter doing my job...</description><item><title>Redux</title><link>https://weblogs.asp.net:443/wesleybakker/redux</link><description>&lt;p&gt;A friend of mine told me to have a look at Redux as it is such an awesome and popular "framework". I had a look and I&amp;rsquo;m not convinced. This post describes my view on Redux. I've also written, my own predictable state container using TypeScript and standard design patterns, which I'll share.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://mertarauh.com/2016/10/23/redux/"&gt;Read full post.&lt;/a&gt;&lt;/p&gt;</description><pubDate>Mon, 24 Oct 2016 08:18:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/redux</guid><category>Redux</category><category>TypeScript</category><category>Design Patterns</category></item><item><title>Free SSL for multiple domains with Letsencrypt and Nginx on a Raspberry PI</title><link>https://weblogs.asp.net:443/wesleybakker/free-ssl-for-multiple-domains-with-letsencrypt-and-nginx-on-a-raspberry-pi</link><description>&lt;p&gt;In the Netherlands we have some amazing bandwith (300Mbit/30Mbit) at our homes.&amp;nbsp;Combined with these dead cheap but very capable&amp;nbsp;Raspberry Pi's readily available,&amp;nbsp;I figured that I could easily run a couple of web servers at home.&amp;nbsp;It's no problem to&amp;nbsp;run Wordpress&amp;nbsp;or a .Net Core web site (&lt;a title="Scott Hanselman" href="http://www.hanselman.com/blog/HowToRunASPNET5Beta3OrGoLangOnARaspberryPi2.aspx" target="_blank"&gt;Scott Hanselman&lt;/a&gt;) on a Pi. The only issue I faced is that I have&amp;nbsp;single public ip-address, but multiple sites to host.&amp;nbsp;The other thing is that I wanted the traffic to these site encrypted with an SSL certificate. I don't want to log in with forms authentication over an unencrypted wire.&lt;/p&gt;
&lt;p&gt;I've had been working on a Raspberry Pi Wordpress site before and back then noticed that Nginx is not just a web server, but a proxy server as well. Hmmm... let's combine everything and let's see if we can get this to work. The goal here is to host multiple web sites on multiple Raspberry Pi's behind a proxy. I have a domain name &lt;a title="mertarauh.com" href="https://mertarauh.com" target="_blank"&gt;mertarauh.com&lt;/a&gt;, where I want to host a Wordpress site at the root,&amp;nbsp;and my&amp;nbsp;SmartPortal (energie consumption monitor)&amp;nbsp;at a sub domain &lt;a title="smartportal.mertarauh.com" href="https://smartportal.mertarauh.com" target="_blank"&gt;smartportal.mertarauh.com&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So let's get started with these 3 basic steps:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Setup the DNS at the domain registar for both the root and sub domain to point to the &lt;a title="What is my ip" href="https://www.whatismyip.com/" target="_blank"&gt;external ip&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a title="Install Nginx" href="https://getgrav.org/blog/raspberrypi-nginx-php7-dev" target="_blank"&gt;Install Nginx&lt;/a&gt; (not the php part) on a clean &lt;a title="Raspbian Jessie Light " href="https://www.raspberrypi.org/downloads/raspbian/" target="_blank"&gt;Raspbian Jessie Light&lt;/a&gt; and &lt;a title="Asign a static ip address" href="http://sizious.com/2015/08/28/setting-a-static-ip-on-raspberry-pi-on-raspbian-20150505/" target="_blank"&gt;assign a static internal ip address&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Configure your router to forward all request at port 80 and 443 to the configured internal ip address.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;All traffic will now be forwarded to my Nginx service running at the Raspberry Pi.&lt;/p&gt;
&lt;p&gt;Let's get some SSL certificates. There is an&amp;nbsp;&lt;a title="Installation and configuration of Letsencrypt on Debian" href="https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04" target="_blank"&gt;almost perfect blog post&lt;/a&gt; on how to install and configure Letsencrypt on a Debian ditribution (like Raspbian). So just follow that one while you replace the domain names and add yours. We can now make a secure connection to our Nginx service, it is just that the service doesn't know what to do with it. Besides that there is a minor mistake in the configuration which prevents succesfull renewal of your certificates. So how should your Nginx config look?&lt;/p&gt;
&lt;pre&gt;upstream smartportal {
        server 192.168.24.65;
}

upstream wordpress {
        server 192.168.24.70;
}

server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;
        root /var/www/mertarauh.com;

        location / {
                return 301 https://$host$request_uri;
        }

        #letsencrypt
        location ^~ /.well-known/ {
                allow all;
        }
}

server {
        listen 443 ssl http2 default_server;
        listen [::]:443 ssl http2 default_server;
        include snippets/ssl-mertarauh.com.conf;
        include snippets/ssl-params.conf;
}

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name mertarauh.com;
        include snippets/ssl-mertarauh.com.conf;
        include snippets/ssl-params.conf;
        proxy_buffering off;

        location / {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://wordpress;
        }
}

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name smartportal.mertarauh.com;
        include snippets/ssl-mertarauh.com.conf;
        include snippets/ssl-params.conf;
        proxy_buffering off;

        location / {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://smartportal;
        }
}
&lt;/pre&gt;
&lt;p&gt;Let me explain what is going on here. First I define my two up stream applications.&lt;/p&gt;
&lt;p&gt;Then I configured a catch all default_server&amp;nbsp;on port 80 which will redirect all requests to the https equivillent &lt;strong&gt;except&lt;/strong&gt; for requests to the /.well-known/ directory. This is required for autorenewal of your SSL certificates (&amp;lt;- this is missing in the blog post).&lt;/p&gt;
&lt;p&gt;Then I have a default_server without a server_name on port 443. This is purely for the&amp;nbsp;SSL hand shake to succeed. The hand shake takes place before the host name is&amp;nbsp;known.&lt;/p&gt;
&lt;p&gt;And finally I configured the two servers for which I like to do SSL termination. I simply forward the requests.&lt;/p&gt;
&lt;p&gt;DONE!&amp;nbsp;&lt;/p&gt;</description><pubDate>Sat, 21 May 2016 17:35:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/free-ssl-for-multiple-domains-with-letsencrypt-and-nginx-on-a-raspberry-pi</guid><category>Nginx</category><category>Letsencrypt</category><category>Proxy</category><category>SSL</category><category>.Net</category><category>Core</category><category>Wordpress</category></item><item><title>Finding out if a delimited string contains a specific value the easy way</title><link>https://weblogs.asp.net:443/wesleybakker/finding-out-if-a-delimited-string-contains-a-specific-value-the-easy-way</link><description>&lt;p&gt;One of the things I do on a regular basis is to read somebody else's code in order to learn from it. And just this week I was reading some code of which I at first did not understand what was happening and then it struck me:&lt;/p&gt;
&lt;pre&gt;var searchString = " " + inputString + " ";
if(searchString.Contains(" " + searchValue + " ")){
  // do something
}
&lt;/pre&gt;
&lt;p&gt;The inputString here contains a space("&amp;nbsp;") delimited list of values. What I used to do to find out if a delimited string contains a specific value is to call string.Split("&amp;lt;separator&amp;gt;") to create an array and then use Linq or a loop to iterate through the array and verify if this array contains the value. This is however very inefficient. Just prepending en postpending the string value with the separator and then call string.Contains("&amp;lt;separator&amp;gt;" + searchValue + "&amp;lt;separator&amp;gt;") works perfectly fine and is much more optimized.&lt;/p&gt;
&lt;p&gt;Prepending and postpending is required to prevent you from finding false positives. Imagine an inputString like this: "12 126 123" while searching for a value of "26".&lt;/p&gt;</description><pubDate>Mon, 04 Jan 2016 11:43:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/finding-out-if-a-delimited-string-contains-a-specific-value-the-easy-way</guid><category>C#; .Net</category></item><item><title>Combine a Raspberry Pi, Smart Meter (Slimme Energiemeter), Python, Rest, TypeScript, AngularJS and some libraries and you've got your own Energie Consumption Portal</title><link>https://weblogs.asp.net:443/wesleybakker/combine-a-raspberry-pi-smart-meter-slimme-energiemeter-python-rest-typescript-angularjs-and-some-libraries-and-you-ve-got-your-own-energie-consumption-portal</link><description>&lt;p&gt;Almost a year ago I created my own&amp;nbsp;solution to view both power and natural gas consumption in my home.&amp;nbsp;I'm thinking about&amp;nbsp;creating a blog post series on how you can create one yourself. But....&amp;nbsp;this will be a long, multipart, time consuming blog post series.&amp;nbsp;&amp;nbsp;Before I start this adventure I first want to find out if there is anybody out there that is actually interested in such a blog post series. In this first post I will just tell you what I did, and if I get enough comments in which readers express their interest in the full series, I'll continue explaining how I did it.&lt;/p&gt;
&lt;h2&gt;What I did&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;I hooked up a Raspberry Pi to my Smart Meter (Slimme Energiemeter) by using an FTDI cable&lt;/li&gt;
&lt;li&gt;I wrote a Python service that listens to the 'virtual' COM port and writes values to a Round Robin Database&lt;/li&gt;
&lt;li&gt;I wrote a Python web service that exposes a REST api which returns data from this RRDB&lt;/li&gt;
&lt;li&gt;I wrote some static HTML, TypeScript, CSS and combined that with some libraries to create my responsive &lt;a title="Smart Portal" href="https://smartportal.mertarauh.com" target="_blank"&gt;Smart Portal&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The results look like this.&lt;/p&gt;
&lt;p&gt;&lt;img width="715" height="747" alt="" src="https://aspblogs.blob.core.windows.net:443/media/wesleybakker/SmartPortal/SmartPortal.PNG" /&gt;&lt;/p&gt;
&lt;p&gt;If you would like to know how, please just drop me a comment and I'll find some time to start the blog post series.&lt;/p&gt;
&lt;p&gt;Regards,&lt;/p&gt;
&lt;p&gt;Wesley&lt;/p&gt;</description><pubDate>Wed, 25 Nov 2015 22:03:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/combine-a-raspberry-pi-smart-meter-slimme-energiemeter-python-rest-typescript-angularjs-and-some-libraries-and-you-ve-got-your-own-energie-consumption-portal</guid><category>Raspberry Pi</category><category>Smart Meter</category><category>Slimme Energiemeter</category><category>Python</category><category>Rest</category><category>TypeScript</category><category>AngularJS</category><category>JSON</category></item><item><title>Leverage browser cache in MVC using an action filter</title><link>https://weblogs.asp.net:443/wesleybakker/leverage-browser-cache-in-mvc-using-an-action-filter</link><description>&lt;p&gt;Along the lines of my&amp;nbsp;&lt;a href="https://weblogs.asp.net/wesleybakker/leverage-browser-cache-in-mvc-web-api-using-an-action-filter"&gt;previous post&lt;/a&gt; I wanted an easy way to implement client cache in a standard MVC web application. The OutputCache attribute does not allow us to dynamically change the cache settings for the current request. As MVC and Web API both rely on different libraries I could not reuse the&amp;nbsp;Web API&amp;nbsp;action filter in MVC&amp;nbsp;so I&amp;nbsp;had to come up with a new solution. This again resulted in two simple classes.&lt;/p&gt;
&lt;pre&gt;public class ClientCacheAttribute : ActionFilterAttribute {
    public override void OnActionExecuted(ActionExecutedContext filterContext) {
        base.OnActionExecuted(filterContext);

        var clientCache = ClientCache.Current;

        if (clientCache.IsValid) {
            filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.NotModified);
        }
    }
}

public class ClientCache : HttpCachePolicyWrapper {
    private const string ItemsKey = "C653F02F-14F9-4E8C-9E74-D22F7E7230A4";
    private const string IfModifiedSinceHeaderKey = "If-Modified-Since";

    protected ClientCache()
        : base(HttpContext.Current.Response.Cache) {        
        var request = HttpContext.Current.Request;
        if (request.Headers.AllKeys.Contains(IfModifiedSinceHeaderKey)) {
            string modifiedSinceHeaderValue = request.Headers.GetValues(IfModifiedSinceHeaderKey).First();

            DateTimeOffset modifiedSince;
            if (DateTimeOffset.TryParse(modifiedSinceHeaderValue, out modifiedSince)) {
                this.IfModifiedSince = modifiedSince;
            }
        }
    }

        
    public static ClientCache Current {
        get {
            var currentContext = HttpContext.Current;

            if (!currentContext.Items.Contains(ItemsKey)) {
                lock (currentContext.Items) {
                    if (!currentContext.Items.Contains(ItemsKey)) {
                        currentContext.Items.Add(ItemsKey, new ClientCache());
                    }
                }
            }

            return currentContext.Items[ItemsKey] as ClientCache;
        }
    }

    public DateTimeOffset? IfModifiedSince {
        get;
        private set;
    }


    public DateTimeOffset? LastModified {
        get;
        private set;
    }


    public override void SetLastModified(DateTime date) {
        this.LastModified = new DateTimeOffset(date);
        this.IsValid = (this.IfModifiedSince.HasValue &amp;amp;&amp;amp; this.LastModified.Value.Equals(IfModifiedSince.Value));
        base.SetLastModified(date);
    }

    public bool IsValid {
        get;
        private set;
    }
}&lt;/pre&gt;
&lt;p&gt;These classes again give easy access to the cache headers. This&amp;nbsp;allows us&amp;nbsp;to not do any work at all based on the If-Modified-Since&amp;nbsp;or&amp;nbsp;set appropriate cache headers. The code below shows how the&amp;nbsp;ClientCacheAttribute and ClientCache class can be put to use.&lt;/p&gt;
&lt;pre&gt;[ClientCache]
public ActionResult Index() {
    var clientCache = ClientCache.Current;
    clientCache.SetLastModified(DateTime.Today);
    clientCache.SetExpires(DateTime.Today.AddDays(1));
    clientCache.SetCacheability(HttpCacheability.Private);

    if (clientCache.IsValid) {
        //don't do work if the client cache is still valid...
        return null;
    }

    return View();
}
&lt;/pre&gt;
&lt;p&gt;The net result is that the ActionResult that is returned from the action might not even be executed based on these settings.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Regards,&lt;/p&gt;
&lt;p&gt;Wesley&lt;/p&gt;</description><pubDate>Thu, 12 Nov 2015 12:26:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/leverage-browser-cache-in-mvc-using-an-action-filter</guid><category>MVC</category><category>if-modified-since</category><category>last-modified</category><category>action filter</category></item><item><title>Leverage browser cache in MVC Web API using an action filter</title><link>https://weblogs.asp.net:443/wesleybakker/leverage-browser-cache-in-mvc-web-api-using-an-action-filter</link><description>&lt;p&gt;Last week I was working on some sample application that uses MVC Web API to return results to a client framework.&amp;nbsp;While doing so&amp;nbsp;I noticed that the standard Web API&amp;nbsp;framework does not implement client caching in an easy to use way. Of course we can&amp;nbsp;work with&amp;nbsp;headers inside our controller actions, but as a big fan of DRY I decided to find out if I can use a different route.&amp;nbsp;As&amp;nbsp;a result I&amp;nbsp;show you the&amp;nbsp;ClientCacheAttribute together with its&amp;nbsp;ClientCache.&lt;/p&gt;
&lt;h2&gt;ClientCacheAttribute and ClientCache code&amp;nbsp;&lt;/h2&gt;
&lt;pre&gt;public class ClientCacheAttribute : ActionFilterAttribute {
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
        base.OnActionExecuted(actionExecutedContext);

        var clientCache = ClientCache.Current;
        var response = actionExecutedContext.Response;

        if (clientCache.IsValid) {
                response.StatusCode = HttpStatusCode.NotModified;
                response.Content = new StringContent("");
                response.Content.Headers.ContentType = null;                    
        }

        response.Content.Headers.LastModified = clientCache.LastModified;
        response.Content.Headers.Expires = clientCache.Expires;

        response.Headers.CacheControl = clientCache;
    }
}

public class ClientCache : CacheControlHeaderValue {
    private const string ItemsKey = "C653F02F-14F9-4E8C-9E74-D22F7E7230A4";
    private const string IfModifiedSinceHeaderKey = "If-Modified-Since";

    protected ClientCache()
        : base() {
        var request = HttpContext.Current.Request;

        if (request.Headers.AllKeys.Contains(IfModifiedSinceHeaderKey)) {
            string modifiedSinceHeaderValue = request.Headers.GetValues(IfModifiedSinceHeaderKey).First();

            DateTimeOffset modifiedSince;
            if (DateTimeOffset.TryParse(modifiedSinceHeaderValue, out modifiedSince)) {
                this.IfModifiedSince = modifiedSince;
            }
        }
    }

    public static ClientCache Current {
        get {
            var currentContext = HttpContext.Current;

            if (!currentContext.Items.Contains(ItemsKey)) {
                lock (currentContext.Items) {
                    if (!currentContext.Items.Contains(ItemsKey)) {
                        currentContext.Items.Add(ItemsKey, new ClientCache());
                    }
                }
            }

            return currentContext.Items[ItemsKey] as ClientCache;
        }
    }

    public DateTimeOffset? IfModifiedSince { get; private set; }

    private DateTimeOffset? lastModified = null;
    public DateTimeOffset? LastModified {
        get {
            return lastModified;
        }
        set {
            this.lastModified = value;
            this.IsValid = (this.IfModifiedSince.HasValue &amp;amp;&amp;amp; this.LastModified.HasValue
                            &amp;amp;&amp;amp; this.LastModified.Value.Equals(IfModifiedSince.Value));
        }
    }
    public DateTimeOffset? Expires { get; set; }

    public bool IsValid {
        get;
        private set;
    }
}&lt;/pre&gt;
&lt;h3&gt;The ClientCache&lt;/h3&gt;
&lt;p&gt;The ClientCache.Current returns an instance per request which allows for easy access to the IfModifiedSince request header value and allows for setting the ClientCache response headers in a much easier way than messing around with headers yourself.&lt;/p&gt;
&lt;h3&gt;The ClientCacheAttribute&lt;/h3&gt;
&lt;p&gt;The ClientCacheAttribute inherits the &lt;a href="https://msdn.microsoft.com/en-us/library/system.web.http.filters.actionfilterattribute(v=vs.118).aspx" target="_blank"&gt;ActionFilterAttribute&lt;/a&gt;&amp;nbsp;and overides the OnActionExecuted.&lt;/p&gt;
&lt;p&gt;In the OnActionExecuted it gets the current ClientCache instance to modify the response. If the ClientCache is still valid the StatusCode is set to HttpStatusCode.NotModified(304). It also changes the Content property&amp;nbsp;of the response to an empty StringContent instance which prevents the execution of any database queries if a non null result was returned from the action method. Since a 304 response does not have a body, it also sets the content-type header to null.&lt;/p&gt;
&lt;p&gt;It finally sets the cache control header and done we are.&lt;/p&gt;
&lt;h2&gt;How to use this?&lt;/h2&gt;
&lt;p&gt;The most obvious place to use this is on any of the Web Api GET actions.&lt;/p&gt;
&lt;pre&gt;// GET: odata/Customers
[EnableQuery(PageSize = 100)]
[ClientCache]
public IQueryable&amp;lt;Customer&amp;gt; GetCustomers() {
    var clientCache = ClientCache.Current;
    // get the last modified date from:
    //  the db
    //  some setting (data warehouse last load date)
    // as an example I use DateTime.Today
    clientCache.LastModified = DateTime.Today;


    // set any caching options to your requirements
    clientCache.Private = true;
    clientCache.Expires = DateTime.Today.AddDays(1);

    if (clientCache.IsValid) {
        //don't do work if the client cache is still valid...
        return null;
    }


    return db.Customers;
}

// GET: odata/Customers(5)
[EnableQuery]
[ClientCache]
public SingleResult&amp;lt;Customer&amp;gt; GetCustomer([FromODataUri] int key) {
    var clientCache = ClientCache.Current;
    // get the last modified date from:
    //  the db
    //  some setting (data warehouse last load date)
    // as an example I use DateTime.Today
    clientCache.LastModified = DateTime.Today;


    // set any caching options to your requirements
    clientCache.Private = true;
    clientCache.Expires = DateTime.Today.AddDays(1);

    if (clientCache.IsValid) {
        //don't do work if the client cache is still valid...
        return null;
    }

    return SingleResult.Create(db.Customers.Where(customer =&amp;gt; customer.Id == key));
}
&lt;/pre&gt;
&lt;p&gt;The result of the above sample&amp;nbsp;is that on the first request of the day, the client will receive fresh data from the database. Until tomorrow, the client won't even hit the server as we did set the Expires header to tomorrow. If we do force the client to go to the server (F5) it wil pass along the IfModifiedSince header and as a result we can simply return a 304 result, without hitting the database again.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Regards,&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Wesley&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;</description><pubDate>Tue, 10 Nov 2015 17:47:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/leverage-browser-cache-in-mvc-web-api-using-an-action-filter</guid><category>MVC</category><category>Web Api</category><category>if-modified-since</category><category>last-modified</category><category>action filter</category></item><item><title>TypeScript Design Patterns and Mine Sweeper</title><link>https://weblogs.asp.net:443/wesleybakker/typescript-design-patterns-and-mine-sweeper</link><description>&lt;p&gt;Every now and then when I have to learn a new language I try to implement the&amp;nbsp;Gang of Four design patterns in that langauge to get familiar with it. And so I did for TypeScript. Beside that I was asked to deliver a training on Design Patterns and so I did. Then I was asked to deliver screencasts with some explanation on design patterns and the implementation in TypeScript and so I did. Then I decided to share the result and the result is available over here&amp;nbsp;&lt;a title="TypeScript Design Patterns" href="https://mertarauh.com/tutorials/typescript-design-patterns"&gt;TypeScript Design Patterns&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Enjoy,&lt;/p&gt;
&lt;p&gt;Wesley&lt;br /&gt;P.S. One other practice lab I like to take to get familiar with a new language is to create the good old MineSweeper game with it. The result of that, including the downloadable source, is over &lt;a title="Mine Sweeper" href="https://aspblogs.blob.core.windows.net/media/wesleybakker/MS/Index.htm"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;</description><pubDate>Fri, 17 Jul 2015 10:04:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/typescript-design-patterns-and-mine-sweeper</guid><category>TypeScript</category><category>Design Patterns</category><category>OO</category><category>GoF</category><category>Training</category><category>Screencast</category><category>Webcast</category><category>Samples</category><category>Explained</category><category>Source code</category><category>Mine Sweeper</category></item><item><title>Getting Secure Store Credentials in SharePoint 2013</title><link>https://weblogs.asp.net:443/wesleybakker/getting-secure-store-credentials-in-sharepoint-2013</link><description>&lt;p&gt;Last week I reviewed some code that contains memory leaks and I noticed that they fetched some credentials from the Secure Store Service in a way that just didn't seem right to me. If you look at &lt;a href="https://msdn.microsoft.com/en-us/library/office/ff394459(v=office.14).aspx" target="_blank"&gt;this code sample on MSDN&lt;/a&gt; you should be able to see what I mean.&lt;/p&gt;
&lt;p&gt;They created a new SPServiceContext by first fetching a SPSite object of the Central Admin site. While this might (don't know) be required for the code sample, this doesn't make sense if we are inside a SharePoint context. I do know however&amp;nbsp;why they thought they needed to go with this approach. They were creating a custom claims provider and the code for this custom claims provider does not run within a site context, but&amp;nbsp;inside the Secure Token Service.&amp;nbsp;They could however use a much easier approach to fetch the default secure store provider. Below you'll find the three classes I create for them that solved the memory issue.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SecureStoreCredentials {
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Pin { get; set; }
}

static class SecureStringUtility {
    public static string ConvertToString(this SecureString secureString) {
        string retVal = null;

        if (secureString != null) {
            IntPtr pPlainText = IntPtr.Zero;
            try {
                pPlainText = Marshal.SecureStringToBSTR(secureString);
                retVal = Marshal.PtrToStringBSTR(pPlainText);
            } finally {
                if (pPlainText != IntPtr.Zero) {
                    Marshal.FreeBSTR(pPlainText);
                }
            }
        }

        return retVal;
    }
}

class SecureStoreUtility {
    public static SecureStoreCredentials GetCredentials(string applicationId) {
        if (string.IsNullOrEmpty(applicationId)) {
            throw new ArgumentNullException("applicationId");
        }

        var retVal = new SecureStoreCredentials();

        SPServiceContext context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
        SecureStoreServiceProxy ssp = new SecureStoreServiceProxy();
        ISecureStore iss = ssp.GetSecureStore(context);
            
        SecureStoreCredentialCollection credentials = null;

        try {
            credentials = iss.GetCredentials(applicationId);
            if (credentials != null) {
                foreach (SecureStoreCredential credential in credentials) {
                    if (credential == null) {
                        continue;
                    }

                    switch (credential.CredentialType) {
                        case SecureStoreCredentialType.WindowsUserName:
                        case SecureStoreCredentialType.UserName:
                            retVal.UserName = credential.Credential.ConvertToString();
                            break;

                        case SecureStoreCredentialType.WindowsPassword:
                        case SecureStoreCredentialType.Password:
                            retVal.Password = credential.Credential.ConvertToString();
                            break;

                        case SecureStoreCredentialType.Pin:
                            retVal.Pin = credential.Credential.ConvertToString();
                            break;
                    }
                }
            }
        } catch (Exception ex) {
            Debug.WriteLine(ex.ToString());                
        } finally {
            if (credentials != null) {
                credentials.Dispose();
            }
        }

        return retVal;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The important line here is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SPServiceContext context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which fetches a SPServiceContext without the need of a SPSite object.&lt;/p&gt;
&lt;p&gt;Have fun with it!&lt;/p&gt;
&lt;p&gt;Wesley&lt;/p&gt;</description><pubDate>Tue, 19 May 2015 15:22:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/getting-secure-store-credentials-in-sharepoint-2013</guid><category>Secure Store</category><category>SharePoint 2013</category><category>SPServiceContext</category><category>C#</category><category>GetCredentials</category></item><item><title>Asynchronous programming with Python using Promises</title><link>https://weblogs.asp.net:443/wesleybakker/asynchronous-programming-with-python-using-promises</link><description>&lt;p&gt;While I was working on a Python project, I needed asynchronous programming and noticed that I couldn't find a lightweight library to do so. So I made myself a promise...&lt;/p&gt;
&lt;pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"&gt;&lt;span style="color: blue;"&gt;from&lt;/span&gt;&amp;nbsp;&lt;span style="color: #6f008a;"&gt;threading&lt;/span&gt;&amp;nbsp;&lt;span style="color: blue;"&gt;import&lt;/span&gt;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Thread&lt;/span&gt;
&lt;span style="color: blue;"&gt;from&lt;/span&gt;&amp;nbsp;&lt;span style="color: #6f008a;"&gt;threading&lt;/span&gt;&amp;nbsp;&lt;span style="color: blue;"&gt;import&lt;/span&gt;&amp;nbsp;Event
 
&lt;span style="color: blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Deferred&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;object&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;__init__(&lt;span style="color: gray;"&gt;self&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._event&amp;nbsp;=&amp;nbsp;Event()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._rejected&amp;nbsp;=&amp;nbsp;False
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._result&amp;nbsp;=&amp;nbsp;None
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;resolve(&lt;span style="color: gray;"&gt;self&lt;/span&gt;,&amp;nbsp;&lt;span style="color: gray;"&gt;value&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._rejected&amp;nbsp;=&amp;nbsp;False
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._result&amp;nbsp;=&amp;nbsp;&lt;span style="color: gray;"&gt;value&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._event.set()
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;reject(&lt;span style="color: gray;"&gt;self&lt;/span&gt;,&amp;nbsp;&lt;span style="color: gray;"&gt;reason&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._rejected&amp;nbsp;=&amp;nbsp;True
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._result&amp;nbsp;=&amp;nbsp;&lt;span style="color: gray;"&gt;reason&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._event.set()
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;promise(&lt;span style="color: gray;"&gt;self&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;promise&amp;nbsp;=&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Promise&lt;/span&gt;(&lt;span style="color: gray;"&gt;self&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;return&lt;/span&gt;&amp;nbsp;promise
 
 
&lt;span style="color: blue;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Promise&lt;/span&gt;(&lt;span style="color: #2b91af;"&gt;object&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;__init__(&lt;span style="color: gray;"&gt;self&lt;/span&gt;,&amp;nbsp;&lt;span style="color: gray;"&gt;deferred&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred&amp;nbsp;=&amp;nbsp;&lt;span style="color: gray;"&gt;deferred&lt;/span&gt;
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;then(&lt;span style="color: gray;"&gt;self&lt;/span&gt;,&amp;nbsp;&lt;span style="color: gray;"&gt;resolved&lt;/span&gt;&amp;nbsp;=&amp;nbsp;None,&amp;nbsp;&lt;span style="color: gray;"&gt;rejected&lt;/span&gt;=None):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;defer&amp;nbsp;=&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Deferred&lt;/span&gt;()
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;task():
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;try&lt;/span&gt;:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred._event.wait()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;if&lt;/span&gt;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred._rejected:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;result&amp;nbsp;=&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred._result
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;if&lt;/span&gt;&amp;nbsp;&lt;span style="color: gray;"&gt;rejected&lt;/span&gt;:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;result&amp;nbsp;=&amp;nbsp;&lt;span style="color: gray;"&gt;rejected&lt;/span&gt;(&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred._result)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;defer.reject(result)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;else&lt;/span&gt;:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;result&amp;nbsp;=&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred._result
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;if&lt;/span&gt;&amp;nbsp;&lt;span style="color: gray;"&gt;resolved&lt;/span&gt;:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;result&amp;nbsp;=&amp;nbsp;&lt;span style="color: gray;"&gt;resolved&lt;/span&gt;(&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred._result)
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;defer.resolve(result)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;except&lt;/span&gt;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Exception&lt;/span&gt;&amp;nbsp;&lt;span style="color: blue;"&gt;as&lt;/span&gt;&amp;nbsp;ex:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;defer.reject(ex.message)
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Thread&lt;/span&gt;(target=task).start()
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;return&lt;/span&gt;&amp;nbsp;defer.promise()
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;wait(&lt;span style="color: gray;"&gt;self&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: gray;"&gt;self&lt;/span&gt;._deferred._event.wait()
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@&lt;span style="color: #2b91af;"&gt;staticmethod&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;def&lt;/span&gt;&amp;nbsp;wait_all(*&lt;span style="color: gray;"&gt;args&lt;/span&gt;):
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;for&lt;/span&gt;&amp;nbsp;promise&amp;nbsp;&lt;span style="color: blue;"&gt;in&lt;/span&gt;&amp;nbsp;&lt;span style="color: gray;"&gt;args&lt;/span&gt;:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;promise.wait()&lt;/pre&gt;
&lt;p&gt;------------------------------------------------------------------------------&lt;/p&gt;
&lt;p&gt;And with that in place I can now write code like this:&lt;/p&gt;
&lt;p&gt;------------------------------------------------------------------------------&lt;/p&gt;
&lt;pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"&gt;controller&amp;nbsp;=&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Controller&lt;/span&gt;(&lt;span style="color: #a31515;"&gt;"COM7"&lt;/span&gt;)
controller.start()
 
message1&amp;nbsp;=&amp;nbsp;&lt;span style="color: #2b91af;"&gt;DiscoveryRequest&lt;/span&gt;()
promise1&amp;nbsp;=&amp;nbsp;controller.send(message1).then(on_ready,&amp;nbsp;on_error)
 
message2&amp;nbsp;=&amp;nbsp;&lt;span style="color: #2b91af;"&gt;RequestNodeInfoRequest&lt;/span&gt;(1)
promise2&amp;nbsp;=&amp;nbsp;controller.send(message1).then(on_ready,&amp;nbsp;on_error)
 
&lt;span style="color: #2b91af;"&gt;Promise&lt;/span&gt;.wait_all(promise1,&amp;nbsp;promise2)
 
controller.stop()&lt;/pre&gt;
&lt;p&gt;------------------------------------------------------------------------------&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;</description><pubDate>Mon, 20 Apr 2015 16:37:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/asynchronous-programming-with-python-using-promises</guid><category>python</category><category>asynchronous programming</category><category>promise</category></item><item><title>Changing the autogrowth settings for a set of databases</title><link>https://weblogs.asp.net:443/wesleybakker/changing-the-autogrowth-settings-for-a-set-of-databases</link><description>&lt;p&gt;SharePoint simply ignores the autogrowth settings of your model database and as such you need to make changes to the autogrowth settings of a lot of databases after installation or after adding new content databases. The script below can be used to create a batch script to save you from the tedious task of going over each and every database.&lt;/p&gt;
&lt;p&gt;Have fun with it!&lt;/p&gt;
&lt;pre&gt;-- begin settings
DECLARE @data_FILEGROWTH nvarchar(50) = '10GB'
DECLARE @data_MAXSIZE nvarchar(50) = '200GB'

DECLARE @log_FILEGROWTH nvarchar(50) = '128MB'
DECLARE @log_MAXSIZE nvarchar(50) = '1GB'

DECLARE @database_name_inclusion_filter nvarchar(max) = '%'
DECLARE @database_name_exclusion_filter nvarchar(max) = ''
-- end settings

USE master

DECLARE @database_name nvarchar(max)
DECLARE @database_id int
DECLARE @file_name nvarchar(max)
DECLARE @file_type int

DECLARE databases_cursor CURSOR for
	SELECT database_id, name FROM sys.databases
	WHERE owner_sid != 0x01

OPEN databases_cursor

FETCH NEXT FROM databases_cursor 
INTO @database_id, @database_name

WHILE @@FETCH_STATUS = 0
BEGIN
	IF @database_name like @database_name_inclusion_filter AND @database_name not like @database_name_exclusion_filter
	BEGIN
		PRINT '--Database ' +  @database_name

		DECLARE files_cursor CURSOR for
			SELECT name, [type] FROM sys.master_files
			WHERE database_id = @database_id

		OPEN files_cursor

		FETCH NEXT FROM files_cursor 
		INTO @file_name, @file_type
	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @file_type = 0
			BEGIN
				print 'ALTER DATABASE ' + @database_name +
					' MODIFY FILE (NAME=' + @file_name + ',MAXSIZE=' + @data_MAXSIZE + ',FILEGROWTH=' + @data_FILEGROWTH + ');'
			END

			IF @file_type = 1
			BEGIN
				print 'ALTER DATABASE ' + @database_name +
					' MODIFY FILE (NAME=' + @file_name + ',MAXSIZE=' + @log_MAXSIZE + ',FILEGROWTH=' + @log_FILEGROWTH + ');'
			END

			FETCH NEXT FROM files_cursor 
			INTO @file_name, @file_type
		END

		CLOSE files_cursor;
		DEALLOCATE files_cursor;
	END


	FETCH NEXT FROM databases_cursor 
	INTO @database_id, @database_name
END

CLOSE databases_cursor;
DEALLOCATE databases_cursor;
&lt;/pre&gt;</description><pubDate>Mon, 30 Mar 2015 08:51:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/changing-the-autogrowth-settings-for-a-set-of-databases</guid><category>SQL Server; autogrowth; filegrowth; maxfilesize;</category></item><item><title>Using the Claims to Windows Token Service to run code with different credentials</title><link>https://weblogs.asp.net:443/wesleybakker/using-the-claims-to-windows-token-service-to-run-code-with-different-credentials</link><description>&lt;p&gt;Every now and then you need to run code with specific credentials. If you have the C2WTS service running you can use that to get an identity and then use impersonation to run code with the credentials of the given identity. I created myself a helper method to&amp;nbsp;make this a bit easier:&lt;/p&gt;
&lt;pre&gt;    public static class SecurityHelper {
        public static void RunAs(string upn, Action action) {
            using (var identity = S4UClient.UpnLogon(upn))
            using (var context = identity.Impersonate())
            {
                try {
                    action();
                } finally {
                    if (context != null) {
                        context.Undo();
                    }
                }
            }
        }
    }
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;You can use this helper class&amp;nbsp;in the following way:&lt;/p&gt;
&lt;pre&gt;    SecurityHelper.RunAs(upn, () =&amp;gt; {
        using (var connection = new SqlConnection("Server=.;Database=DatabaseName;Integrated Security=True"))
        using (var command = new SqlCommand("SomeStoredProcedure", connection)) {
            command.CommandType = CommandType.StoredProcedure;

            try {
                connection.Open();
                customClaimValue = command.ExecuteScalar();
            } catch (Exception ex) {
                customClaimValue = ex.ToString();
            }
        }
    });
&lt;/pre&gt;
&lt;p&gt;The above code will connect to SQL server with the identity of the given UPN.&lt;/p&gt;
&lt;p&gt;Cheers,&lt;/p&gt;
&lt;p&gt;Wesley&lt;/p&gt;</description><pubDate>Wed, 09 Jul 2014 12:19:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/using-the-claims-to-windows-token-service-to-run-code-with-different-credentials</guid><category>C2WTS</category><category>Impersonation</category><category>RunAs</category><category>SharePoint</category><category>S4UClient</category><category>UpnLogon</category></item><item><title>Solving WmiApRpl and BITS errors with SharePoint 2013 on Windows Server 2012</title><link>https://weblogs.asp.net:443/wesleybakker/Solving-WmiApRpl-and-BITS-errors-with-SharePoint-2013-on-Windows-Server-2012</link><description>&lt;p mce_keep="true"&gt;I have been searching for a way to get rid of some performance counter errors (WmiApRpl and BITS)&amp;nbsp;on my SharePoint 2013 installation for a while but couldn't find the answer. Today I decided to have a look with Process Monitor and finally found a solution.&lt;/p&gt;
&lt;p mce_keep="true"&gt;The w3wp process tries to access to registry keys but does not have the permissions.&lt;/p&gt;
&lt;p mce_keep="true"&gt;After&amp;nbsp;granting the WSS_WPG group full control(you probable can get away with a little less)&amp;nbsp;to the following registry keys, the errors went away.&lt;/p&gt;
&lt;p mce_keep="true"&gt;HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\BITS\Performance&lt;br /&gt;HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WmiApRpl\Performance&lt;/p&gt;
&lt;p mce_keep="true"&gt;And that's it!&lt;/p&gt;
&lt;p mce_keep="true"&gt;Cheers,&lt;/p&gt;
&lt;p mce_keep="true"&gt;Wesley&lt;/p&gt;</description><pubDate>Fri, 03 May 2013 13:32:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/Solving-WmiApRpl-and-BITS-errors-with-SharePoint-2013-on-Windows-Server-2012</guid><category>Sharepoint</category><category>SharePoint 2013</category></item><item><title>SPItemEventReceiver Bug</title><link>https://weblogs.asp.net:443/wesleybakker/spitemeventreceiver-bug</link><description>&lt;p&gt;Normally when you inherit a class, and override any of the methods, you call the base method, just to be sure you do not interfere with the inner workings of the class. There is a bug however in the SPItemEventReceiver class that always changes the Status to Continue, even if I decided it should stop and cancel. TMHI this is simply a bug. Especially since the SPEventReceiverStatus.Continue enum value is 0 and thus the default value. &lt;/p&gt;  &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/SPItemEventReceiver_1CAAEBE2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="SPItemEventReceiver" border="0" alt="SPItemEventReceiver" src="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/SPItemEventReceiver_thumb_61E3430B.png" width="526" height="484" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h5&gt;Conclusion&lt;/h5&gt;  &lt;p&gt;If you decide to Cancel the action do not call the base implementation.&lt;/p&gt;  &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/SPItemEventReceiver2_5BF879A5.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="SPItemEventReceiver2" border="0" alt="SPItemEventReceiver2" src="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/SPItemEventReceiver2_thumb_1DAFAF34.png" width="644" height="211" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Cheers,&lt;/p&gt;  &lt;p&gt;Wes&lt;/p&gt;</description><pubDate>Wed, 15 Jun 2011 08:47:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/spitemeventreceiver-bug</guid><category>Sharepoint</category><category>SharePoint 2010</category></item><item><title>WebDAV slow with “Automatically detect settings”</title><link>https://weblogs.asp.net:443/wesleybakker/webdav-slow-with-automatically-detect-settings</link><description>&lt;p&gt;Just a short note to self. A lot of Microsoft applications use WebDAV.&amp;#160; If you encounter some very slow WebDAV performance, just disable the “Automatically detect settings” in IE.&lt;/p&gt;  &lt;p&gt;Tools –&amp;gt; Internet options –&amp;gt; Connections –&amp;gt; LAN Settings&lt;/p&gt;  &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/SNAGHTML19bf2a_4B727970.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="SNAGHTML19bf2a" border="0" alt="SNAGHTML19bf2a" src="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/SNAGHTML19bf2a_thumb_6329B0D6.png" width="379" height="484" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Speeds up performance 10 times in my case.&lt;/p&gt;  &lt;p&gt;Regards,&lt;/p&gt;  &lt;p&gt;Wesley&lt;/p&gt;</description><pubDate>Fri, 10 Jun 2011 07:47:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/webdav-slow-with-automatically-detect-settings</guid><category>Sharepoint</category><category>SharePoint 2010</category><category>WebDAV</category></item><item><title>Microsoft Certified Master SharePoint 2010</title><link>https://weblogs.asp.net:443/wesleybakker/microsoft-certified-master-sharepoint-2010</link><description>&lt;p&gt;Yesterday I've received the news that I've successfully completed all four exams that come with the MCM program. This actually makes me an MCM as of now which is&amp;nbsp;still somewhat unreal to me. I've had to spent three weeks away from home strugling through the massive amount of information. The lectures were awesome, and I really learned to know a lot of good SharePoint specialists.&lt;/p&gt;&lt;p&gt;I would&amp;nbsp;like to thank all the other attendees, the teachers&amp;nbsp;and&amp;nbsp;Brett Geoffroy for getting me through these three weeks. If you ever get the chance to attend the MCM program, go for it. It is an awesome experience you will not likely ever forget, but... just be sure to:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;read&amp;nbsp;the prereads&lt;/li&gt;&lt;li&gt;keep&amp;nbsp;focussed on the next(not the previous!) exam&lt;/li&gt;&lt;li&gt;read the prereads&lt;/li&gt;&lt;li&gt;arrive two days&amp;nbsp;before the start, as you cannot use a jetlag when you are in class/studying&amp;nbsp;from 8am till 11pm every single day for three weeks on end&lt;/li&gt;&lt;li&gt;read the prereads&lt;/li&gt;&lt;li&gt;rest well and do some physical&amp;nbsp;exercises in the few moments you have, to digest the massive amount of&amp;nbsp;information you receive every day&lt;/li&gt;&lt;li&gt;read the prereads&lt;/li&gt;&lt;li&gt;enjoy the whole experience!&lt;/li&gt;&lt;li&gt;did I mention to read the prereads?&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Cheers,&lt;/p&gt;&lt;p&gt;Wesley&lt;br&gt;&lt;/p&gt;</description><pubDate>Thu, 26 May 2011 14:29:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/microsoft-certified-master-sharepoint-2010</guid><category>MCM</category><category>Sharepoint</category></item><item><title>Dynamics CRM 2011 and SharePoint 2010</title><link>https://weblogs.asp.net:443/wesleybakker/dynamics-crm-2011-and-sharepoint-2010</link><description>&lt;p&gt;Here’s just a life saving tip for all you SharePoint developers, thinking about integrating with Dynamics CRM 2011 through BCS.&lt;/p&gt;
&lt;p&gt;The new CRM SDK is built with .NET Framework &lt;strong&gt;4.0&lt;/strong&gt;! SharePoint 2010 runs in &lt;strong&gt;3.5&lt;/strong&gt;! So you cannot use the&amp;nbsp;new CRM 2011 SDK if you would like to create an External Content Type.&lt;/p&gt;
&lt;p&gt;I do have some good new for you though. Stick to the CRM 4.0 SDK. As CRM 2011 is backward compatible, your code will run just fine when you use the “old” SDK to connect to the “new” CRM. &lt;/p&gt;</description><pubDate>Fri, 11 Mar 2011 09:47:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/dynamics-crm-2011-and-sharepoint-2010</guid><category>BCS</category><category>Dynamics CRM</category><category>SharePoint 2010</category></item><item><title>Get Datepart in SharePoint Designer Workflow</title><link>https://weblogs.asp.net:443/wesleybakker/get-datepart-in-sharepoint-designer-workflow</link><description>&lt;P mce_keep="true"&gt;Yesterday someone asked me how to get the datepart (f.e. the year of a date)&amp;nbsp;inside a SharePoint designer workflow. I thought it would be some default action in the "Utility Actions" group, but I thought wrong. There is no such pretty common action. This post however shows&amp;nbsp;a simple technique to get datepart Year, Month and Day.&lt;/P&gt;
&lt;H4&gt;How to&amp;nbsp;&lt;/H4&gt;
&lt;P mce_keep="true"&gt;First you have to start by asigning a new workflow &lt;STRONG&gt;string&lt;/STRONG&gt;&amp;nbsp;variable to a &lt;STRONG&gt;date&lt;/STRONG&gt; value, and make sure to select the &lt;STRONG&gt;ISO Formatted&lt;/STRONG&gt; option&amp;nbsp;for the &lt;STRONG&gt;return field as&lt;/STRONG&gt; parameter. This will set the string variable to something like 2010-12-28 according to the ISO format(yyyy-mm-dd).&lt;/P&gt;
&lt;P mce_keep="true"&gt;We can now use the Utility Actions for string variables&amp;nbsp;to extract our Year, Month and Day.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&lt;IMG style="MARGIN-TOP: 10px; WIDTH: 617px; HEIGHT: 451px; MARGING-BOTTOM: 10px" title=Screenshot alt=Screenshot src="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/WorkflowDatePart.png" width=617 height=451 mce_src="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/WorkflowDatePart.png"&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;Cheers,&lt;/P&gt;
&lt;P mce_keep="true"&gt;Wes&lt;/P&gt;</description><pubDate>Tue, 28 Dec 2010 07:51:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/get-datepart-in-sharepoint-designer-workflow</guid><category>Datepart</category><category>Sharepoint</category><category>SharePoint 2010</category><category>Workflow</category></item><item><title>Framed Office Web Apps SharePoint 2010</title><link>https://weblogs.asp.net:443/wesleybakker/framed-office-web-apps-sharepoint-2010</link><description>&lt;P mce_keep="true"&gt;In a project I'm working on we wanted to use Office Web Apps in SP2010 to preview selected documents in the browser. To do so we've created a very simple web part that renders an I-Frame with the URL set to one of the Office Web Apps urls depending on the document extension. Unfortunately the X-Frame header, that is added by the Office Web Apps service, prevents&amp;nbsp;Internet Explorer to render the documents in an I-Frame! To solve this we've create a very simple HttpModule that checks for the header and changes the value from "DENY" to "SAMEORIGIN". This post simply shows the code for such a module that enables previewing of documents with Office Web Apps inside an I-Frame&lt;/P&gt;
&lt;H3&gt;The code&lt;/H3&gt;
&lt;DIV style="OVERFLOW-X: auto; BACKGROUND-COLOR: #ddd"&gt;&lt;PRE&gt;&lt;CODE&gt;/// &amp;lt;summary&amp;gt;
/// The XFrameOptionsModule loosens the x-frame policy from DENY to SAMEORIGIN
/// &amp;lt;/summary&amp;gt;
public class XFrameOptionsModule : IHttpModule
{
    private const string XFrameOptionsHeaderName = "X-FRAME-OPTIONS";

    /// &amp;lt;summary&amp;gt;
    /// Initializes a new instance of the &amp;lt;see cref="XFrameOptionsModule"/&amp;gt; class.
    /// &amp;lt;/summary&amp;gt;
    public XFrameOptionsModule()
    {
    }

    /// &amp;lt;summary&amp;gt;
    /// Disposes of the resources (other than memory) used by the module that implements &amp;lt;see cref="T:System.Web.IHttpModule"/&amp;gt;.
    /// &amp;lt;/summary&amp;gt;
    public void Dispose()
    {
    }

    /// &amp;lt;summary&amp;gt;
    /// Initializes a module and prepares it to handle requests.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="context"&amp;gt;An &amp;lt;see cref="T:System.Web.HttpApplication"/&amp;gt; that provides access to the methods, properties, and events common to all application objects within an ASP.NET application&amp;lt;/param&amp;gt;
    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += ChangeXFrameOptionsHeaderToSameOrigin;
    }

    /// &amp;lt;summary&amp;gt;
    /// Changes the X-Frame-Options "DENY" header to "SAMEORIGIN".
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="sender"&amp;gt;The HttpApplication that triggers the event.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="e"&amp;gt;The &amp;lt;see cref="System.EventArgs"/&amp;gt; instance containing the event data.&amp;lt;/param&amp;gt;
    private void ChangeXFrameOptionsHeaderToSameOrigin(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;            
        HttpResponse response = application.Response;
            
        string headerValue = response.Headers[XFrameOptionsHeaderName];
        if (headerValue != null &amp;amp;&amp;amp; headerValue.Equals("DENY", StringComparison.OrdinalIgnoreCase))
        {
            response.Headers[XFrameOptionsHeaderName] = "SAMEORIGIN";
        }
    }
}&lt;/CODE&gt;&lt;/PRE&gt;&lt;/DIV&gt;
&lt;P&gt;All you have to do now is&amp;nbsp;to add this module to the web.config using a SPWebConfigModification inside a feature receiver.&lt;/P&gt;
&lt;P&gt;Cheers,&lt;/P&gt;
&lt;P&gt;Wes&lt;/P&gt;</description><pubDate>Mon, 13 Dec 2010 12:20:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/framed-office-web-apps-sharepoint-2010</guid><category>2010</category><category>Office Web Apps</category><category>Sharepoint</category><category>SharePoint 2010</category></item><item><title>Missing server reference in SharePoint 2010</title><link>https://weblogs.asp.net:443/wesleybakker/missing-server-reference-in-sharepoint-2010</link><description>&lt;P mce_keep="true"&gt;Unfortunately&amp;nbsp;the "missing server references" health rule&amp;nbsp;in Central Admin Health Monitoring does not display the URL were these uninstalled web parts reside. So to get these pages you'll have to execute some SQL against the mentioned content database. Because this is something that tents to come back regularly on development machines I've created a little SQL script to speed up the process of finding the url's you'll need to delete the web parts.&lt;/P&gt;
&lt;DIV style="BACKGROUND-COLOR: #ddd"&gt;&lt;CODE&gt;&lt;PRE&gt;-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.


USE &lt;CONTENTDBNAME, ,&gt;

DECLARE @className nvarchar = '&lt;CLASSNAME, ,&gt;'
DECLARE @assemblyName nvarchar = '&lt;ASSEMBLYNAME, ,&gt;'


SELECT DISTINCT pages.DirName + '/' + pages.LeafName + '?contents=1' as Page
FROM
	dbo.AllWebParts wp
	JOIN dbo.AllDocs pages on pages.SiteId = wp.tp_SiteId
						AND pages.Id = wp.tp_PageUrlID
WHERE
	wp.tp_Assembly like '%' + @assemblyName + '%' AND
	wp.tp_Class	 like '%' + @className + '%'
&lt;/PRE&gt;&lt;/CODE&gt;&lt;/DIV&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P mce_keep="true"&gt;Cheers,&lt;/P&gt;
&lt;P mce_keep="true"&gt;Wes&lt;/P&gt;</description><pubDate>Tue, 30 Nov 2010 09:47:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/missing-server-reference-in-sharepoint-2010</guid><category>Missing Reference</category><category>Sharepoint</category><category>T-SQL</category></item><item><title>WorkflowAction and the Secure Store</title><link>https://weblogs.asp.net:443/wesleybakker/workflowaction-and-the-secure-store</link><description>&lt;P&gt;&lt;A href="http://weblogs.asp.net/blogs/wesleybakker/CallWebServiceWorkFlowAction_572E74A0.png" mce_href="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/CallWebServiceWorkFlowAction_572E74A0.png"&gt;&lt;IMG style="BACKGROUND-IMAGE: none; BORDER-RIGHT-WIDTH: 0px; MARGIN: 0px 5px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; DISPLAY: inline; FLOAT: right; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; PADDING-TOP: 0px" title=CallWebServiceWorkFlowAction border=0 alt=CallWebServiceWorkFlowAction align=right src="http://weblogs.asp.net/blogs/wesleybakker/CallWebServiceWorkFlowAction_thumb_43A114FF.png" width=240 height=156 mce_src="https://aspblogs.blob.core.windows.net/media/wesleybakker/Media/CallWebServiceWorkFlowAction_thumb_43A114FF.png"&gt;&lt;/A&gt;I have been working on this custom workflow action which allows you to post data to another servicer. This can be used to send messages to a web service for example. One thing I really wanted to have in there is security. And with security I mean the Secure Store. It is however very difficult to use the Secure Store from inside a workflow action.&lt;/P&gt;
&lt;H3&gt;Impersonation&lt;/H3&gt;
&lt;P&gt;Although SharePoint actions are so called “impersonated” to the initiator of the user, the process really runs under its own account. Depending on how busy your server is, and the type of workflow is executed by the SPUserCodeHost, OWSTimer or W3WP process. And your code actually runs under the account of that process. The so called “impersonation” is for SharePoint actions only. This is accomplished by handing out the SPContext of the initiating step to the workflow.&lt;/P&gt;
&lt;H3&gt;Secure Store&lt;/H3&gt;
&lt;P&gt;Secure Store stores the credentials for users or groups and only while running under the user, or group account, can you get these credentials out of the secure store and that’s great of course, but that’s also where the trouble starts. We have no way of impersonating the actual initiator of the workflow and thus no way to get the credentials per user. One option would be to get a ticket in the Initialize method and use that ticket during the Execute method to retrieve the user credentials and yes this does work, most of the time. Because most of the time, the Initialize method will run inside the W3WP process which has a HttpContext which in turn has a WindowsIdentity we can use to impersonate. Unfortunately, if the server gets busy, the Initialize method might just as well run inside the OWSTimer process. Another problem with the ticketing system is that tickets are valid for a specified amount of time only. You should think in minutes instead of hours, but workflows well… they sometimes take a few days or weeks before they finally arrive at your workflow action.&lt;/P&gt;
&lt;DIV style="OVERFLOW-X: auto; OVERFLOW-Y: auto"&gt;&lt;PRE class=csharpcode&gt;&lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;static&lt;/SPAN&gt; ICredentials GetSecureStoreCredentials(&lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; applicationId, SPServiceContext context) {
    &lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; username = String.Empty;
    &lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; password = String.Empty;

    ISecureStoreProvider provider = SecureStoreProviderFactory.Create();
    &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (provider == &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;) {
        &lt;SPAN class=kwrd&gt;throw&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; InvalidOperationException(&lt;SPAN class=str&gt;"Unable to get an ISecureStoreProvider"&lt;/SPAN&gt;);
    }

    ISecureStoreServiceContext providerContext = provider &lt;SPAN class=kwrd&gt;as&lt;/SPAN&gt; ISecureStoreServiceContext;
    providerContext.Context = context;

    &lt;SPAN class=kwrd&gt;using&lt;/SPAN&gt; (var credentials = provider.GetCredentials(applicationId)) {
        &lt;SPAN class=kwrd&gt;foreach&lt;/SPAN&gt; (var credential &lt;SPAN class=kwrd&gt;in&lt;/SPAN&gt; credentials) {
            &lt;SPAN class=kwrd&gt;switch&lt;/SPAN&gt; (credential.CredentialType) {
                &lt;SPAN class=kwrd&gt;case&lt;/SPAN&gt; SecureStoreCredentialType.UserName:
                &lt;SPAN class=kwrd&gt;case&lt;/SPAN&gt; SecureStoreCredentialType.WindowsUserName:
                    username = credential.Credential.ToClrString();
                    &lt;SPAN class=kwrd&gt;break&lt;/SPAN&gt;;

                &lt;SPAN class=kwrd&gt;case&lt;/SPAN&gt; SecureStoreCredentialType.Password:
                &lt;SPAN class=kwrd&gt;case&lt;/SPAN&gt; SecureStoreCredentialType.WindowsPassword:
                    password = credential.Credential.ToClrString();
                    &lt;SPAN class=kwrd&gt;break&lt;/SPAN&gt;;
            }
        }
    }

    &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; NetworkCredential(username, password);
}&lt;/PRE&gt;
&lt;STYLE type=text/css&gt;




.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/STYLE&gt;
&lt;/DIV&gt;
&lt;P&gt;&lt;FONT size=1&gt;Sample code for retrieving network credentials from secure store&lt;/FONT&gt;&lt;/P&gt;
&lt;H3&gt;Careful&lt;/H3&gt;
&lt;P&gt;One thing I would really like to stress out is that you really should not store the credentials in workflow variables during Initiate. Workflows can get stored anywhere (depending on the implementation of the WorkflowPersistenceService) and probably not secure. The other problem is that these credentials might not be valid anymore by the time your custom action executes.&lt;/P&gt;
&lt;H3&gt;What’s the solution?&lt;/H3&gt;
&lt;P&gt;There simply is no solution. The only thing you can do is create a so called Application Account (=Group account used by all users) in Secure Store and add the service accounts of the SPUserCodeHost, OWSTimer and W3WP processes in there. Problem is that every workflow action with the same Secure Store ApplicationId has to use the same credentials.&lt;/P&gt;
&lt;P&gt;Cheers,&lt;/P&gt;
&lt;P&gt;Wes &lt;/P&gt;</description><pubDate>Mon, 25 Oct 2010 00:02:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/wesleybakker/workflowaction-and-the-secure-store</guid><category>Secure Store</category><category>Security</category><category>Sharepoint</category></item></channel></rss>