Free Tool: Dynamics CRM User Language Update Tool

Just had an encounter with a user who needed their language updated. The UI Language was set to Korean – I wasn’t able to walk the user through updating it since I don’t read Korean either.

So I whipped up a little tool to do the job for me.

You supply a connection string for the target CRM Organization (Should support everything – CRM Online, On-Premise – just paste everything in the CRM url up to (but not including) the “/main.aspx”)

You can search for the user by Guid, Full Name or DomainName (aka User Name) (all the search fields auto add wildcards)

The tool returns a list of matching users – select the user to update, select the desired values for language code and click Update. Pretty basic and there are instructions for doing it, but I didn’t see anything so simple out there.

You can get the binaries here: Dynamics CRM User Language Update Tool

And the source code here: Dynamics CRM User Language Update Tool Source Code

(Note that you may need to have Windows Identity Foundation installed – this is a prerequisite of the CRM SDK)

This tool works with Dynamics CRM 2011, Dynamics CRM 2013, Dynamics CRM 2015, Dynamics CRM Online, and the forthcoming Dynamics CRM 2016 (ie everything 2011 and later)

windows net user add password with special characters

The command line to add a local windows user called “newuser” with the password “p&ssw^rd”

You try

net user newuser p&ssw^rd /ADD

Uh-oh – it fails!

C:\> net user newuser p&ssw^rd /ADD
The user name could not be found.

More help is available by typing NET HELPMSG 2221.

'sswrd' is not recognized as an internal or external command,
operable program or batch file.

If the password contains certain special characters – like an ampersand “&” or a caret “^”, the password will be garbled, broken, butchered.

One solution is to have it prompt for the password

net user newuser * /ADD

but if you are scripting, this isn’t really helpful.

No, you cannot use quotes.

The solution: All Ampersands must be escaped with a caret “^”, and all carets in the password must be similarly escaped.

UPDATE: turns out in more recent versions of windows, exclamation marks “!” must also be escape with two carets.
See here for a good list of how to escape things.

So, to use the password p&ssw^rd in a command line, you would need to replace it with p^&ssw^^rd

net user newuser p^&ssw^^rd /ADD

This will do what you expect

Note that if you do not escape the carets, the command may succeed, but the password will be wrong.

Dirt simple WCF Routing Service configuration tutorial with authentication

As I’ve said in previous posts, I’m a big fan of WCF in general – recently I have had the opportunity to work with a less popular, but extremely powerful feature: the WCF Routing Service (

The MSDN documentation is confusing. The existing blog articles are confusing or broken. Examples of hosting it in IIS using simplified configuration are pretty much missing…

The routing service allows you to create proxy service endpoints. In my case, I needed to expose some internal web services to the internet through a VPN connection in Azure. Also, I needed to implement security on these publicly exposed endpoints.

The internal web services are hosted by a non-microsoft service bus, use HTTP with no authentication.
The external endpoints need to run over HTTPS (SSL) and require authentication.

Yes, you can do this with the Routing Service. No, it does not require a bunch of code.

The routing service is capable of using xpath matching on the message header or message itself to determine the endpoint routing. You could use the SOAP Action for example. Or… a much simpler approach is to use URL-pattern based routing.

In fact, you can do 95% of it in the web.config only. The only place you will need code is to apply authorization (what users can access the proxy), but it is very simple.

Suppose you have three SOAP endpoints you would like to proxy.

Suppose you want to serve these up through you service as

You want Basic Authentication over SSL, using Windows for credentials. Finally, you want a means of limiting which authenticated users can access the proxy.

So, step by step.

1. Create a WCF Project

1.1 Setup IIS to host your project
Create a site in IIS pointing to the folder containing Service1.svc. Disable anonymous auth, enable basic auth, set it up for SSL.
(I recommend using a real ssl cert with a hosts entry pointing back at localhost. Easier than getting self signed certs working…)

2. Delete the IService1.cs; expand the Service1.svc and delete the code behind (Service1.svc.cs).

3. Rt click the Service1.svc and edit markup. Replace it with the following:

<%@ ServiceHost Language="C#" Debug="true" Service="System.ServiceModel.Routing.RoutingService,System.ServiceModel.Routing, version=, Culture=neutral,PublicKeyToken=31bf3856ad364e35" %>

This will cause your Service1.svc to invoke the routing service. No code required (yet) – you do the rest in the web.config.

4. Update your web.config with the following.

<?xml version="1.0"?>
    <compilation debug="true" targetFramework="4.5"/>
      <!--Define named internal (private-side) endpoints here. Defined like any client endpoint except the contract doesn't need to be specified. Define binding as needed -->
      <endpoint name="ep_sendmail" address="http://mailserver/sendservice" binding="basicHttpBinding" contract="*"/>
      <endpoint name="ep_getcustomer" address="http://customermanagement/customerretrieval" binding="basicHttpBinding" contract="*"/>
      <endpoint name="ep_updatecustomer" address="http://customermanagement/customerupdate" binding="basicHttpBinding" contract="*"/>
        <!--Define named filters that will be applied to requests coming into the (public side of) the router. (hostname is ignored - anything can be used - protocol and path/query strings must match identically)-->
        <filter name="f_sendmail" filterType="EndpointAddress" filterData="https://host/Service1.svc/SendMail"/>
        <filter name="f_getcustomer" filterType="EndpointAddress" filterData="https://host/Service1.svc/GetCustomer"/>
        <filter name="f_updatecustomer" filterType="EndpointAddress" filterData="https://host/Service1.svc/UpdateCustomer"/>
        <filterTable name="filterTable1">
          <!--Define the mapping between the filter match and endpoint. I'm using a 1:1:1 mapping-->
          <add filterName="f_sendmail" endpointName="ep_sendmail"/>
          <add filterName="f_getcustomer" endpointName="ep_getcustomer"/>
          <add filterName="f_updatecustomer" endpointName="ep_updatecustomer"/>
      <service behaviorConfiguration="RoutingBehavior" name="System.ServiceModel.Routing.RoutingService">
        <!--Server endpoint must be defined with the appropriate contract (Most likely IRequestReplyRouter) and associated with its own binding-->
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="externalBinding" name="RouterEndpoint1" contract="System.ServiceModel.Routing.IRequestReplyRouter"/>
        <!--For this example, the default or internal binding are just using the defaults-->
        <binding name="internalBinding"/>
        <!--Binding configuration for the router's "endpoint" - configures it to expect Basic Authentication over SSL.-->
        <binding name="externalBinding">
          <security mode="Transport">
            <transport clientCredentialType="Basic"/>
          <!--These behaviors are likely unused-->
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        <behavior name="RoutingBehavior">
          <!--The behaviors applied specifically to the routing service - must specify the filtertable name -->
          <routing routeOnHeadersOnly="true" filterTableName="filterTable1"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <!--The router's provided metadata is pretty much useless - it is the IRequestReply contract-->
          <serviceMetadata httpGetEnabled="false"/>
          <!--This tells the router to use Windows for establishing identities, and to use our custom class for determining permission-->
          <serviceAuthorization principalPermissionMode="UseWindowsGroups" serviceAuthorizationManagerType="ExampleNamespace.ExampleAuthorizationManager, ExampleAssemblyName"/>
    <!--Very important - there is a bug of sorts in the router when using basicHttpBinding with asp compatibility. Just disable it.-->
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>

If you comment out the serviceAuthorization tag, your project should build and run – so long as you have ssl and basic auth working…

You should update the “ExampleNamespace.ExampleAuthorizationManager, ExampleAssemblyName” with the Namespace, class name and assembly name that you actually use
(often the namespace and assembly name are the same)

If you simply want a router – with no auth and no ssl remove the enternalBinding’s security node AND the serviceAuthorization node

5. Implement the ExampleAuthorizationManager

namespace ExampleNamespace
    public class ExampleAuthorizationManager : ServiceAuthorizationManager
        protected override bool CheckAccessCore(OperationContext operationContext)
            //check that the user is allowed and return true to allow, false to deny
            return true;
            //return base.CheckAccessCore(operationContext);

6. Update clients

Since there is no WSDL, you will need build your clients against the internal endpoints’ WSDLs, then update them to use the external endpoint. Additionally you will need to update the binding configuration to use Transport security with Basic Authentication (unless you have turned this off).

You now have a secure proxy for WCF services without having to reimplement the services in WCF – adding new services requires 3 lines of configuration. I’m not sure if Microsoft could have made this any easier… except perhaps by documenting it better 😛

Installing Windows Identity Foundation 3.5 in Azure Role Startup Task (Server 2012 VM)

The new VMs used by Azure are Server 2012+, and you cannot use the msu installer for WIF (Like you could here:

You must use dism to enable the feature.

I assume you are familiar with creating startup tasks – you need to create a batch file that runs:

Dism /online /Enable-Feature /FeatureName:Windows-Identity-Foundation >> "%TEMP%\WifStartupLog.txt" 2>&1

Here is the error you might be searching for:

Could not load file or assembly ‘Microsoft.IdentityModel Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencie. The system cannot fine the find specified.

Get the SQL Server and database name from Dynamics CRM

As far as I can tell, there is no way to retrieve the SQL Server name using the Organization Service. If you have the Organization Service URL, there really is no good way to get the database connection string.

(You can use the deployment service to get it, but that only works if you happen to be a deployment administrator)

No good way… but there is a way. When you download a dynamic spreadsheet, the database connection string is embedded in the xml. And you can programmatically download that spreadsheet using an entity that all CRM orgs have.

Using some fiddler experimentation, I was able to make a .NET method that will extract the database connection string, given the organization base url (https://crmserver/orgnam)

        /// <summary>
        /// Given a Dynamics CRM Org URL, retrieve the Database Connection string
        /// </summary>
        /// <param name="crmOrgUrlBase"></param>
        /// <returns></returns>
        private static string GetCrmDatabaseConnectionString(string crmOrgUrlBase)
            string cleanurl = crmOrgUrlBase.ToLowerInvariant().Trim().Replace("/xrmservices/2011/organization.svc", "");
                int mainPos = cleanurl.IndexOf("/main.aspx");
                if (mainPos > 0)
                    cleanurl = cleanurl.Substring(0, mainPos);

            string requestPayload = @"xdpi=96&exportType=list&useSqlQuery=1&fetchXml=%3Cfetch+distinct%3D%22false%22+no-lock%3D%22false%22+mapping%3D%22logical%22+page%3D%221%22+count%3D%2250%22+returntotalrecordcount%3D%22true%22%3E%3Centity+name%3D%22systemuser%22%3E%3Cattribute+name%3D%22systemuserid%22%2F%3E%3Cattribute+name%3D%22fullname%22%2F%3E%3Cattribute+name%3D%22fullname%22%2F%3E%3Corder+attribute%3D%22fullname%22+descending%3D%22false%22%2F%3E%3C%2Fentity%3E%3C%2Ffetch%3E%0D%0A&layoutXml=%3Cgrid+name%3D%22excelGrid%22+select%3D%220%22+icon%3D%220%22+preview%3D%220%22%3E%3Crow+name%3D%22result%22+id%3D%22systemuserid%22%3E%3Ccell+name%3D%22fullname%22+width%3D%22100%22%2F%3E%3C%2Frow%3E%3C%2Fgrid%3E%0D%0A";
            string url = cleanurl + "/_grid/print/export_live.aspx";

            string response = null;

            using (var wc = new System.Net.WebClient())
                wc.UseDefaultCredentials = true;
                wc.Headers.Add("Accept-Encoding", "gzip, deflate");
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                wc.Headers.Add("DNT", "1");
                response = wc.UploadString(url, requestPayload);

            var xe = System.Xml.Linq.XElement.Parse(response);

            System.Xml.Linq.XNamespace nn = "urn:schemas-microsoft-com:office:spreadsheet";
            System.Xml.Linq.XNamespace nn2 = "urn:schemas-microsoft-com:office:excel";

            var connectionEl = xe.Element(nn + "Worksheet").Element(nn2 + "QueryTable").Element(nn2 + "QuerySource").Element(nn2 + "Connection");

            string rawString = connectionEl.Value;

            Regex rex = new Regex("SERVER=([^;]+);DATABASE=([^;]+)", RegexOptions.Compiled);

            var m = rex.Match(rawString);

            string server = m.Groups[1].Value;
            string database = m.Groups[2].Value;

            return "DATA SOURCE=" + server +";INITIAL CATALOG=" + database + ";Integrated Security=SSPI";

It is technically unsupported to access export_live.aspx directly, so this may stop working in future releases of CRM.
I have tested this on CRM 2011 UR 11 and UR 17.

Dirt simple method of limiting System.Threading.Task concurrency (max concurrent threads)

Microsoft has an article about creating a Task Scheduler that limits maximum concurrency:
How to: Create a Task Scheduler That Limits the Degree of Concurrency

The provided example class is clunky and kinda hard to grasp. I’ve been searching for a simple way to create a “thread pool” with limited concurrency. I previously experimented with ConcurrentBags of BackgroundWorkers – this worked, but it was also fairy complex and cumbersome.

The solution I came up with uses a Semaphore (or rather the lighter weight SemaphoreSlim type) to manage concurrency.

Simply put – you create a semaphore with a maxCount (and initialCount) equal to the max concurrency you desire. Then when you want to fire off a Task, first call semaphore.Wait(), then call semaphore.Relase() in a ContinueWith().

Contrived example:

    public class LimitedAsync
        private SemaphoreSlim _semaphore;

        public LimitedAsync(int maxConcurrency)
            // Create semaphore with maxConcurrency slots
            _semaphore = new SemaphoreSlim(maxConcurrency, maxConcurrency);

        public void DoSomethingAsync(string param)
            //Wait for semaphore to have availablilty (blocks if semaphore is full)
            //Run DoSomething in a task, then release slot in semaphore
            //ContinueWith is called even if DoSomething faults
            Task.Factory.StartNew(() => DoSomething(param)).ContinueWith((x) => _semaphore.Release());

        public void DoSomething(string param)

Generating a single flattened WSDL from an existing WCF Service

UPDATE 4/12/2013: Tool included
Download WSDL Flattener Tool
I’m not including source because it’s messy (I prefer to cleanup my code before sharing…) but feel free to decompile with ILSpy if you don’t trust me.

UPDATE 8/11/2015: Command line tool included
WSDL Flattener Command Line Utility
Somehow I forgot to save my update – thanks Luke for pointing it out!

WCF is great – its flexible, standards compliant, super easy to work with, and just altogether nice. That is, until you try to use it with, say, Oracle products. WCF generates so-called modular wsdl files, with separate xsd files for types, and even sometimes multiple wsdl files. Not technically in violation of any standards, but kind-of pushing the limits.

There are plenty of articles out there about modifying a WCF service to generate a flat WSDL. Also if you upgrade to .NET 4.5, you can use the URL parameter ?singleWsdl to get a flattened WSDL.

But what if you don’t have control of the web service? What if you cannot upgrade or modify the code?

For some odd reason, Microsoft added the internal ability to generate a single WSDL but only exposed it through the WCF Service implementation. They didn’t add it to svcutil.exe, and they didn’t expose it in the Framework… publicly that is *evil grin*

Turns out, in the System.ServiceModel.Description namespace, there is an internal static class called “WsdlHelper”, and this class has a public static Method called “GetSingleWsdl” that takes a MetadataSet for a parameter, and returns a System.Web.Services.Description.ServiceDescription object representing the Wsdl as a single entity. All you have to do is call .Write(filename) and you have your file.

“But I don’t see any WsdlHelper class!!!!!!”

It’s internal – you have to use reflection to invoke it.
First, you have to load the metadata from the existing WCF service into a MetadataSet using a MetadataExchangeClient. (Hint: you will probably need to use a custom binding). Then you run that set into something like this:

            var asy = System.Reflection.Assembly.GetAssembly(typeof(WsdlExporter));
            Type t = asy.GetType("System.ServiceModel.Description.WsdlHelper", true);
            var method = t.GetMethod("GetSingleWsdl", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

            object retVal = method.Invoke(null, new object[] { metadataSet });
            //cast retVal into System.Web.Services.Description.ServiceDescription, and call the .Write() method. All done

Using this, I was able to create a tool that takes a WCF url, and allows you to save a single .wsdl file. You want the tool? Later perhaps. For now put your thinking cap and Google gloves on, and write your own.

SQL Server Configuration Manager RPC Error

On my Dev VM, I’ve been unable to manage SQL Server Express with SQL Server Configuration Manager – I get an error “The Remote Procedure call failed”.

rpc error

The solution: Updates. I found this article:

Which mentions about things breaking wile installing Sql Server 2012 – I didn’t install that, but I did install Visual Studio 2012 – which includes Server Server 2012 components.

Install sql server 2008 sp3, and sql server 2008 r2 sp2. Problems solved.


Windows RT takes steps toward awesome

As I mentioned in a previous post, Windows RT is essentially Windows on ARM, and arguably that is how it should have been promoted.

Just imagine – a third platform option when downloading applications – x86, x64 and now ARM. Due to Microsoft’s arbitrary (and greed motivated) restrictions, this wasn’t supposed to happen.

Thank goodness for hacker ingenuity: not only did somebody figure out how to disable the signature requirement, somebody else created a script to simplify the unlock, and according to this article: You can jailbreak Windows RT to run desktop apps…or even Mac OS, Putty and 7-Zip have already been ported to ARM.

[Release] RT Jailbreak Tool – xda-developers

The next step is portability. If this article is to be be believed, somebody managed to get Windows RT running an an HTC HD2. If it is possible to port Windows RT to just about any ARM device… what else could it run on? Just imagine a tablet landscape where you could pick your own OS, or dual boot Windows and Android.

Imagine all the Linux nerd heads exploding if Windows RT were running on a Raspberry Pi.

Or even better – if somebody ports Windows RT to run on the iPad. THAT would be epic.

Windows RT based devices remain marginally useful and tremendously overpriced (the iPad is a good $200 cheaper… not cool). Should freedom and ingenuity prevail over Microsoft’s greed, Windows RT really could take the ARM world by storm. I’ve got my fingers crossed…

Windows 8 Store Application Development: AppBar WTF

I have a great idea for an app that I intend to submit to the Windows 8 store. I am a fairly proficient .NET developer, and I already have a nice little class library all ready to go, I just need a “Modern” UI. This shouldn’t be too hard, right?

I create my project, and start adding controls. I realize I will need that settings thing that pops up when you swipe up from the bottom of the screen. But it isn’t called “settings” – that is something different. Instead it is called the “AppBar”. Now given that I am using a tool called VISUAL Studio, the primary innovation being the ability to rapidly, visually design user interfaces, then write code for interaction. So I figure adding an AppBar should be as simple as adding a menubar was in windows forms, right?

Wrong. Dead Wrong.

An AppBar is like an iFrame. You can put whatever you want in it, and it is completely NON-obvious, and non-intuitive to do so in a meaningful fashion. The Microsoft Quick Start guide only tells you how to do it with some XAML code that they neglect to tell you where to place. Want to follow along? Here is the article:


Continue reading