Trim leading characters from a string in TSQL

The easiest way to do this is multiply by 1, but if it is a (n)varchar data type, it is a little more challenging.

This was the query I had to run:

DECLARE @insurancenumber nvarchar(100),@charactertopurge nvarchar(1)
SET @charactertopurge='0'
SET @insurancenumber='00PK102947'
SELECT @GMPI=GMPI
from Patient.dbo.PatientAlias
where AliasField=substring(@insurancenumber, patindex('%[^'+@charactertopurge+']%',@insurancenumber), len(@insurancenumber))

VS 2010 Code Intellisense Improvements (VS 2010 and .NET 4.0 Series)

VS 2010 Code Intellisense Improvements (VS 2010 and .NET 4.0 Series)

This is the tenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. 

In today’s blog post I’m going to cover a small but really nice improvement to code intellisense with VS 2010 – which is its ability to better filter type and member code completion.  This enables you to more easily find and use APIs when writing code.

Code Intellisense with VS 2008

To help illustrate this intellisense improvements coming with VS 2010, let’s start by doing a simple scenario in VS 2008 where we want to write some code to enable an editing scenario with a GridView control.

We might start off by typing “GridView1.Edit” to bring up intellisense to see what Edit members are available on the control.  Doing this with VS 2008 brings up the intellisense drop-down and filters the current location in the dropdown to the members that start with the word “Edit”:

image

This is great if the method/property/event we want to work with starts with “Edit” – but doesn’t really help us if the “Edit” member we are looking for starts with something else (for example: the “RowEditing” event or the “SetEditRow()” helper method).  We have to either manually scroll up and down looking for the other edit members, or pull up the object browser or help system to find them.

Code Intellisense with VS 2010

Let’s now try out the same scenario with VS 2010.  When we type “GridView1.Edit” within VS 2010 we’ll find that the EditIndex property is still highlighted by default.  But the intellisense list has also been filtered so that it enables you to quickly locate all other members that have the word “Edit” anywhere in them:

image

This allows us to quickly see all of the edit related methods/properties/events and more quickly find what we are looking for.

Searching for Keywords

This new intellisense filtering feature of VS 2010 is useful for searching for any member – regardless of what word it starts with.  For example, if we want to enable paging on a datagrid and can’t remember how to-do it, we could just type “GridView1.Paging” and it would automatically filter out everything but members that have the word paging.  Notice below how no members on the GridView class actually start with the word “Paging” – but I am still finding the two members that do have paging in them later in their names:

image

Searching for Types

This new intellisense filtering capability of VS 2010 is also useful for quickly finding classes and types. For example, when we type “List” to declare a variable, the editor will provide automatic filtering to show all types that have the word “List” somewhere in them (including IList<> and SortedList<> – which do not start with List):

image

This makes it much easier to find type names you can’t entirely remember – without having to resort to searching through the object browser and/or using help documentation.

Pascal Case Intellisense

The .NET Framework naming guidelines specify that type and member names should be “Pascal Cased” by default.  This means that each word in a type or member should start with a capitalized letter (for example: PageIndexChanged). 

VS 2010’s intellisense filtering support now enables you to take advantage of this to quickly find and filter methods based on their pascal naming pattern.  For example, if we typed “GridView1.PIC” VS 2010 would filter to show us the members that have PIC in their name, as well as those members which have a pascal cased name where the word segments start with that letter sequence:

image

Notice above how PIC caused both “PageIndexChanged” and “PageIndexChanging” to show up.  This saves us a few keystrokes when resolving either member or type names. 

Summary

I think you’ll find that the new intellisense filtering approach in VS 2010 makes it easier to quickly find and use classes and members when writing code.  You can take advantage of it with both VB and C#.

Hope this helps,

Scott

P.S. In addition to blogging, I have recently been using Twitter to-do quick posts and share links. You can follow me on Twitter at: www.twitter.com/scottgu (@scottgu is my twitter name)

Applying BizTalk Hotfixes – Guidelines for Administrators

Microsoft Support have just a published a helpful support article discussing some of the general guidelines that need to be followed when applying BizTalk Server Hotfixes, applicable to all versions from BizTalk Server 2004 onwards.
The article covers some of the more salient points we need to remember as BizTalk Adminstrators, including:

Considerations when installing Hotfixes on […]

Visual Studio 2010 Beta 2 Flowchart Workflow Designer Video

I’ve just posted the second in a series of webcasts looking at Workflow Foundation 4.0 in Visual Studio 2010 Beta 2. This time the flowchart workflow designer takes centre stage, and I use it to build a basic workflow for the flight check-in process at an airport. I also make a few calls to a WCF service from the workflow using the new messaging activities, I’m going to focus on those next and hopefully get another webcast out very soon. Stay tuned…
The webcast is here.

SharePoint 2010 SDK is available for viewing (beta-ish)

Grab a look at the SDK – here – http://msdn.microsoft.com/en-us/library/dd776256.aspx and
interestingly the BDC (now – Business Data Connectors) and BCS (Business Connectivity
Services) are the enhanced former 2007 BDC.

BCS = http://msdn.microsoft.com/en-us/library/ee556826(office.14).aspx

I’ve got lots to talk about and show but where to start.maybe “once there was a developer”
🙂

Stay tuned.

Mick.

Client Certificate Authorisation with WCF in Development Environments

I have meant to write a blog post about client certificates in a development environment for a while now, as every time I come to implement it I forget a step somewhere. There are resources online for a number of the steps below, but I wanted to consolidate that information along with my own steps into a single place that I can use as a reference. This may also be useful to others, hence why I am making a blog post rather than file it away in my mesh repository somewhere.


So, what am I trying to do here? Well, I would like to create a WCF service that utilises SSL and requires that clients use a certificate for authentication in a development environment where I do not have any certificates supplied to me. I am setting this up in a Windows 2008 environment (so IIS 7) with .NET 3.5. The whole process will involve the following steps:



  1. Create certificate to act as a root certificate authority

  2. Install root certificate

  3. Install service certificate on server

  4. Configure site to use SSL certificate

  5. Export client certificate

  6. Import certificate on client

  7. Configure WCF Service

  8. Configure client(s)

Step 1 – Create Certificate to act as Root Certificate Authority


To use chain trust validation during development you need to create a self-signed root CA and place it in the Trusted Root Certification Authority store. The certificate used by WCF is then created and signed by the root self-signed certificate and installed in the LocalMachine store.



  • Open the Visual Studio command prompt and browse to the location where you want to save the certificate files.

  • Enter the following command:


Makecert -n “CN=MyRootCA” -r -sv MyRootCA.pvk mYRootCA.cer



  • In the Create Private Key Password dialog box, enter a password, confirm the password, and then click OK



  • In the Enter Private Key Password dialog box, enter the password again and then click OK.



  • You should now have two files MyRootCA.cer and MyRootCA.pvk

Step 2 – Install Root Certificate Authority


The certificate that will be created using this certificate authority will need to have the CA installed on both the client and the server, as it will be used to verify the certificate.



  • Follow these steps on both the server and client(s)

  • Run MMC

  • Add certificates snap-in

  • Choose computer account, as this certificate needs to be made available for all users

  • Choose local computer

  • Browse certificates snap-in and go to certificates node under trusted root certification authorities

 



  • Right-click this and select import from the popup menu

  • Browse to the folder where you created the root CA certificate



  • Accept defaults for rest of import wizard

  • You can double-click the certificate entry to view and validate it installed correctly


Step 3 – Install Service Certificate on Server


You now want to create the certificate for the service on the server and the following steps will do this. Once completed you will see the certificate via the certificates snap-in of MMC and browsing to the following location: Certificates (Local Computer) -> Personal -> Certificates



  • Open the Visual Studio command prompt and browse to the location where you saved the Root CA certificate files

  • Run the following command


makecert -sk <KeyName> -iv MyRootCA.pvk -n “CN=<MachineName>” -ic MyRootCA.cer -sr localmachine -ss my -sky exchange -pe



  • Where <KeyName> is the subject’s key container name (which should be unique) and <MachineName> is name of the server which must match the DNS or NetBIOS name

  • Enter the password you defined previously


Step 4 – Configure Site to use SSL Certificate


We now want to configure the website that is to host the WCF service to use the SSL certificate we just created. This step assumes you have already created a website for HTTPS.



  • Open IIS Manager

  • Browse to “Sites”

  • Right-click on your site and select “bindings” from popup menu



  • Click edit and from the SSL certificate drop-down choose the certificate you have just installed

Step 5 – Export Client Certificate


Now we want to export the certificate that will be used on the client(s). At the end of this step you should have a new file created with a pfx extension.



  • Open MMC

  • Add the certificates snap-in and select “Computer Account”

  • Browse to Certificates (Local Computer) -> Personal -> Certificates

  • Right-click on the certificate you created (should be name of server), select “all tasks” and then “export”

  • In the wizard select that you want to export the private key



  • From the next screen select the defaults

  • Enter a password to protect the private key

  • Select where you want to export the certificate and complete the wizard

Step 6 – Import Certificate on Client


Now we need to import the certificate we just exported onto the client(s). You should have already imported the certificate authority in step 2, but if not make sure you do so at this point. Note that we are using the current user here, it just happens to be the way we have things configured later on. You may have a different setup here.



  • In MMC, add certificate snap-in for “current user”

  • Browse to Certificates (Current User) -> Personal -> Certificates

  • Right click this node and select All Tasks and Import from the popup menu

  • Follow the steps in the wizard, selecting the pfx file you exported in the previous step


Step 7 – Configure WCF Service


This is the WCF service that we are hosting and requiring authentication for. We happen to be using basicHttpBinding here, but it could be something else



  • Make the following entries in your web.config

<services>
      <service behaviorConfiguration=”MyBehaviour” name=”MyService”>
        <endpoint name=”MyEndPoint” address=”” binding=”basicHttpBinding” bindingConfiguration=”ClientCertificateTransportSecurity” contract=”MyContract” />
        <!–<endpoint address=”mex” binding=”mexHttpsBinding” contract=”IMetadataExchange” />–>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name=”MyBehaviour”>
          <serviceMetadata httpsGetEnabled=”true” />
          <serviceDebug includeExceptionDetailInFaults=”true” />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding name=”ClientCertificateTransportSecurity”>
          <security mode=”Transport”>
            <transport clientCredentialType=”Certificate” />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>



  • Note that if you do not have the mex commented out like above you will receive the error “The SSL settings for the service ‘None’ does not match those of the IIS ‘Ssl, SslNegotiateCert, SslRequireCert, SslMapCert’”.

Step 8 – Configure Client(s)


If using custom app


Make sure you have the following in your configuration file.


<system.serviceModel>
    <client>
      <endpoint address=”https://myServer/myService.svc”
                binding=”basicHttpBinding”
                bindingConfiguration=”ClientCertificateTransportSecurity”
                contract=”MyContract”
                name=”MyEndPoint”
                behaviorConfiguration=”ClientCertificateCredential” />


    </client>


    <bindings>
      <basicHttpBinding>
        <binding name=” ClientCertificateTransportSecurity”>
          <security mode=”Transport”>
            <transport clientCredentialType=”Certificate” />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>


    <behaviors>
      <endpointBehaviors>
        <behavior name=”ClientCertificateCredential”>
          <clientCredentials>
            <clientCertificate findValue=”myThumbprint”
        storeLocation=”CurrentUser”
        x509FindType=”FindByThumbprint” />
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>


  </system.serviceModel>


Where myThumbprint is available from the certificate



If using a browser to view the service


Internet Explorer


Should just work, a popup should appear that asks you to specify the certificate to pass



FireFox



  • You will get an error that says “HTTP Error 403.7 – Forbidden” “The page you are attempting to access requires your browser to have a Secure Sockets Layer (SSL) client certificate that the Web server recognizes.”

  • In FireFox go to Tools -> Options -> Advanced -> Encryption -> View Certificates

  • Click import and select the certificate with private key file you exported earlier (the .pfx file)

  • You will need to clear history now or restart browser

Fiddler


You may want to use fiddler to examine what is going on. When you have fiddler open you will receive a message saying “The server [your server] requires a client certificate. Please save a client certificate in the following location”. Pretty self explanatory. You will need to export your certificate from MMC certificates snap-in, certificates -> personal -> certificates but this time do not export the private key, just export as a DER encoded certificate, copy and rename to the folder/name that fiddler wanted you to.


Issues


“There was an error downloading ‘https://MachineName/servicefolder/Service.svc’. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel”



  • If CA not installed on client then a trust relationship cannot be established and the above error can occur

“The SSL settings for the service ‘None’ does not match those of the IIS ‘Ssl, SslNegotiateCert, SslRequireCert, SslMapCert’”



  • You will get this error if you do not make sure the clientCredentialType is not set to certificate in the service configuration

  • If the mex is not commented out in the configuration of the service

  • If the binding of the website isn’t set properly (as shown in step 4)

LineAdornment Extension Fixed For Beta 2

I’ve now fixed all remaining issues with my Current Line Highlighting extension for Visual Studio 2010. Besides fixing all build issues, I started running into issues where IWpfTextViewLineCollection.GetMarkerGeometry() was returning null when the text snapshot was empty (like an empty line).
I reworked the code to avoid this call and instead manually create a new geometry […]

Client Profile in .NET 4

If you redistribute or require .NET 4 for your applications, you now have the option of installing .NET 4 Client Profile – a subset of the Framework intended for client applications.


Even better, Client Profile includes almost all pieces of Windows Workflow Foundation and Windows Communication Foundation! The few exceptions are assemblies oriented around web-hosting and WF3 components; I’ll get to these limitations later in this post. First, I’ll describe how you can start taking advantage of the Client Profile right away, and explain what’s included from the perspective of WF and WCF. For more details about other parts of the Client Profile, refer to this introductory post by Jossef Goldberg.


An overriding theme of our efforts has been to ensure that applications running in .NET 3 or 3.5 remain unaffected when switched over to running in .NET 4. Also, developers with projects building in .NET 3 or .NET 3.5 looking to move to .NET 4 are also not affected (and in some cases, only minimally affected) when rolling their projects forward.


So if Client Profile doesn’t interest you, relax – it’s a choice. Also, note that if you install .NET 4 Full, .NET 4 Client Profile is a fully contained subset of .NET 4 Full – so anything that’s a part of .NET 4 Client Profile is a part of .NET 4 Full.


To enable your application to target the Client Profile, you just need to change the “Target Framework” setting in your project like so:



Applications built and targeted this way will be able to run on machines that have the .NET 4 Client Profile installed, as well as those with .NET 4 Full. These projects will not let you build successfully when referencing classes that exist in only .NET 4 Full. On the other hand, applications targeted at .NET 4 Full will be unable to run on machines that only have the .NET 4 Client Profile installed on them, and you’ll get an error message directing you to download and install the Full framework:



To maximize what you could exploit in the Client Profile, we have refactored two assemblies. Each of these assemblies is now effectively split into two, one existing in the Client Profile and another that can be referenced from only .NET Full projects:


1. We’ve moved the JSON serialization classes from System.ServiceModel.Web.dll to System.Runtime.Serialization.dll. These serialization classes are being type-forwarded, so if you have any existing applications, they’ll continue to run just fine. System.Runtime.Serialization.dll will be installed with.NET 4 Client Profile, while System.ServiceModel.Web.dll will come with only .NET 4 Full.


2. We’ve moved and type-forwarded some classes related to hosting and activation from System.ServiceModel.dll to a new assembly, System.ServiceModel.Activation.dll. The former assembly is a part of .NET 4 Client Profile, while the latter is in .NET 4 Full.


Like I mentioned earlier, almost all assemblies we shipped with .NET 3 and .NET 3.5 are a part of the new .NET 4 Client Profile. In addition, almost all assemblies we are shipping for the first time in .NET 4 – including all WF4 assemblies – are a part of .NET 4 Client Profile. A comprehensive list of what’s in the Client Profile and what’s not will be published on MSDN.


So what’s not included in .NET 4 Client Profile? Here is a list of the main pieces, but this is not meant to be exhaustive. If your applications depend on anything from this set of assemblies, your projects should target .NET 4 Full:


– WF3 in .NET 4: This includes System.Workflow.Runtime.dll, System.Workflow.Activities.dll, System.Workflow.ComponentModel.dll, System.WorkflowServices.dll, and other related SQL files, performance counters, and tools.


– WF4 and WCF Hosting assemblies: System.Xaml.Hosting.dll, System.ServiceModel.WasHosting.dll, System.ServiceModel.Web.dll, System.ServiceModel.Activation.dll, WsatConfig.exe, and related tools