About Jason Shuler

Jason is an IT Handyman, with a background in Oracle Database Administration, Teradata Data Warehouse Programming, .NET Development (C# and VB.NET) integrating and customizing Microsoft Dynamics CRM, SharePoint, a touch of Dynamics GP, SmartConnect; Database optimizations and performance tuning, Windows Server Administration…

Visual Studio Publish Events

Suppose you want to be able to run a command line tool to make changes to the transformed web.config during the publish / deploy of a web project in visual studio.

You need to be able to trigger your command after the web.config is transformed but before it is deployed. Additionally, you need to know the folder used for packaging the deploy.

Here is how.

Right click your project and unload it. Now you can right-click and select Edit the .csproj.

Down near the bottom of the csproj, you can add the following

  <Target Name="MyPublishTask" BeforeTargets="MSDeployPublish">
    <Exec Command="$(ProjectDir)..\ToolFolder\Tool.exe $(ProjectDir)$(IntermediateOutputPath)Package\PackageTmp\ web.config" />
  </Target>

Do not simply name your target “MSDeployPublish” – this overrides the publish functionality. If you use AfterTargets it will run your tool after the deploy finishes. Using BeforeTargets is just about right – it will transform the web.config and copy all the output files to the Package Temp folder. The other piece you need is the path where the package is built – $(ProjectDir)$(IntermediateOutputPath)Package\PackageTmp\ will get you there. Your tool can wreak whatever havoc necessary on the files before they are published.

One you are done editing, reload your project. Now when you publish your tool will run.

Error creating Azure IOT Hub

I was trying to create an IOT Hub in the Azure Portal and the UI was displaying errors on the Pricing and scale tier as well as the Subscription selections.

The error details said “Unable to get property ‘value’ of undefined or null reference”

When I attempted to create the IOT Hub using the azure CLI, we got to the real cause of the issue: the subscription was not enabled for “Microsoft.Devices”

To resolve, follow the directions here to register the Microsoft.Devices resource provider on your subscriptions
https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-common-deployment-errors#noregisteredproviderfound

(Open the subscription, look for the “Resource Providers” option, search for “devices” – click register)

Once you have done this, you will be able to create an IOT Hub.

Enabling Windows 10 Continuum on Lumia 640 (theoretically any Windows 10 Lumia)

It can be done, and I have done it!

I have a Cricket wireless Lumia 640 with continuum mode working.

Follow the directions here:
http://www.windowslatest.com/2016/12/02/enable-continuum-support-lumia-phone/

I have mirrored the files here: Continuum.zip

Some notes:

1. After you install the Interop Tools app, you may need to reboot the phone. Before rebooting, I encountered crashes when attempting to open the INTEROP UNLOCK menu

2. You will probably need to first “Restore NDTKSvc” and reboot. Then the other unlock options will work

3. The directions include a tool – iutool.exe – in the i386.zip that allows for installing cab files on the phone. This tool is touchy, and is version specific. IF YOUR PHONE DOESN’T REBOOT ITSELF, THE TOOL DIDN’T WORK.
– Make sure phone is configured for developer mode
– Make sure phone has recent OS update – I believe the instructions were intended for the Anniversary Update.

When I first tried it, the tool immediately failed with an error. This probably means the tool couldn’t figure out which phone to update.

To resolve this, detach the phone, open the “Devices and Printers” control panel (search for it in the start menu). Remove any windows phones in the list. Reattach the phone, wait for windows to finish detecting, and try the command line again.

Next if it uploads the update but then fails, you may have the wrong version of iutool.exe.

I got the latest Phone updates for insider preview, and was able to successfully install Continuum using the version of iutool.exe here:

http://forum.xda-developers.com/showpost.php?p=68459157&postcount=13

(Mirrored here: WP_CPTT_NT-x86-fre.zip

The msi installer places the executable here: C:\Program Files (x86)\Windows Kits\10\Tools\bin\i386

When it works, the phone will reboot itself, you will see gears, etc. Even though the instructions say you may see an error, I did not when it worked.

Now I can use Word, Excel, etc on a Miracast connected display with a Bluetooth keyboard and mouse. If I were desperate for some spreadsheet or word processing action and all I had was the phone – I can now make it happen. When Continuum is enabled, your phone works like an input device for the TV, so you don’t technically need the keyboard and mouse.

Make SQL Server Collation act similar to SQLite

The default SQL Server database collation (“SQL_Latin1_General_CP1_CI_AS”) sorts some Unicode values as equal when they are not. If you have an nvarchar field defined as part of a primary key or unique index, you can run into some surprise duplicate keys.

In particular, I was loading data from a SQLite database into an Azure SQL (SQL Server) database. I had removed all the duplicates as far as SQLite was concerned, but there were some records that SQL Server complained as being duplicate. From what I can tell, one record used single byte characters for the word “Final” and the other used double-byte characters.

The solution in this case was to change the collation of the field to one that uses a binary sort.

“Latin1_General_100_BIN” seems to work swimmingly. No more strange collisions.

Returning custom HTTP Status codes for WCF SOAP Exceptions

When WCF encounters an unhandled exception, the thrown exception is wrapped up in a FaultException and returned to the client. You can of course throw your own FaultException to have better control over the contents of the error, but one thing you cannot control by default is the HTTP response code. It is always 500.

I had a situation where I needed to return a 503 error under certain circumstances in a WCF SOAP service.

The solution is not as simple as I might like, but it isn’t terrible. There are examples out there for changing the http status code for all exceptions (https://msdn.microsoft.com/es-es/library/ee844556(v=vs.95).aspx), but this was not at all what we want.

The solution uses the same basic framework as the mentioned article however. An Endpoint Behavior Extension registers a Dispatch Message Inspector that watches for faults. In the case of a fault. Inside the BeforeSendReply method, you have access to the reply message. For performance reasons it is best to not unwrap the XML, so we use the SOAP Action header to trigger the HTTP Status code update.

I decided to create a simple custom exception class that sets the SOAP Action to a predefined value

    /// <summary>
    /// Custom Fault Exception that when used with the CustomFaultStatusBehavior Endpoint Behavior
    /// allows returning custom HTTP status codes to the client
    /// </summary>
    public class StatusFaultException : FaultException
    {
        /// <summary>
        /// Create new exception
        /// </summary>
        /// <param name="statusCode">HTTP Status code to be returned to the client</param>
        /// <param name="faultReason">SOAP Fault Reason</param>
        /// <param name="faultCode">SOAP Fault Code</param>
        public StatusFaultException(System.Net.HttpStatusCode statusCode, string faultReason, FaultCode faultCode)
            :base(faultReason, faultCode, "CustomFaultStatus" + ((int)statusCode).ToString())
        {
            //StatusCode is placed in the response Action. Action would be "CustomFaultStatus503" to return a 503 error code
        }
    }

Here is the Custom Behavior that consumes the SOAP Action

    /// <summary>
    /// Endpoint Behavior that allows returning custom HTTP response codes for SOAP Faults 
    /// </summary>
    public class CustomFaultStatusBehavior : BehaviorExtensionElement, IEndpointBehavior
    {
        //based on https://msdn.microsoft.com/es-es/library/ee844556(v=vs.95).aspx
        public override Type BehaviorType
        {
            get
            {
                return typeof(CustomFaultStatusBehavior);
            }
        }

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            CustomFaultStatusMessageInspector inspector = new CustomFaultStatusMessageInspector();
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }

        protected override object CreateBehavior()
        {
            return new CustomFaultStatusBehavior();
        }
    }

    /// <summary>
    /// Message Inspector that updates the HTTP response code for faulted messages with a CustomFaultStatus action
    /// </summary>
    public class CustomFaultStatusMessageInspector : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault) return;
            if (!reply.Headers.Action.StartsWith("CustomFaultStatus", StringComparison.Ordinal)) return;
            //get the string value for desired response code
            string statusCodeString = reply.Headers.Action.Substring(17);
            //convert to int
            int statusCodeInt;
            if (!int.TryParse(statusCodeString, out statusCodeInt)) return;

            //cast to HttpStatusCode
            System.Net.HttpStatusCode statusCode = System.Net.HttpStatusCode.InternalServerError;
            try
            {
                statusCode = (System.Net.HttpStatusCode)statusCodeInt;
            }
            catch (Exception ex)
            {
                return;
            }

            // Here the response code is changed
            reply.Properties[HttpResponseMessageProperty.Name] = new HttpResponseMessageProperty() { StatusCode = statusCode };
        }
    }

The CustomFaultStatusBehavior must be registered in your web.config as a behavior extension, then it must be referenced in an endpoint behavior. Finally this behavior should be applied to the endpoint using the behaviorConfiguration attribute.

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.
userupdatetool

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.
http://www.robvanderwoude.com/escapechars.php

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 (https://msdn.microsoft.com/en-us/library/ee517423(v=vs.110).aspx)

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.
http://mailserver/sendservice
http://customermanagement/customerretrieval
http://customermanagement/customerupdate

Suppose you want to serve these up through you service as
https://proxyservice.example.org/sendmail
https://proxyservice.example.org/getcustomer
https://proxyservice.example.org/updatecustomer

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=4.0.0.0, 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"?>
<configuration>
  <configSections>
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <client>
      <!--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="*"/>
    </client>
    <routing>
      <filters>
        <!--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"/>
      </filters>
      <filterTables>
        <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"/>
        </filterTable>
      </filterTables>
    </routing>
    <services>
      <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"/>
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <!--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"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!--These behaviors are likely unused-->
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
        <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"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!--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"/>
  </system.serviceModel>
</configuration>

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: http://blogs.msdn.com/b/sriharsha/archive/2012/04/07/windows-azure-unable-to-find-assembly-microsoft-identitymodel.aspx).

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=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencie. The system cannot fine the find specified.