TOP

Configuring WCF with BasicHttpBinding and SSL

Despite a variety of posts on this topic, I had to go through a bunch of articles just to get what seemed to be a simple task.

I started with this post How to setup a WCF service using basic Http bindings with SSL transport level security. The post gives a good explanation of how to get a ssl certificate and set up IIS to use the certificate. In my case, I just wanted to use SSL and not credentials. So I modified the web.config like this:

<bindings>           
	<basicHttpBinding>               
		<binding name="basicHttps">                   
			 <security mode="Transport">                        
				<transport clientCredentialType="None"></transport>                        
				<message></message>                   
			</security>              
		</binding> 
	</basicHttpBinding>       
</bindings>

Then I added a bindingConfiguration to the service configuration:

<pre class="brush:xml">
<service name="PartnerAPI.Service" behaviorConfiguration="PartnerAPI.ServiceBehavior">    
	<!-- Service Endpoints -->    
	<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttps" contract="PartnerAPI.IService" >

Now after doing that, I went to my service at https://localhost/PartnerAPI/Service.svc?wsdl which gave me the error:

Could not find a base address that matches scheme http for the endpoint with binding MexHttpBinding. Registered base address schemes are [https].

I also needed to tell the MexHttpBinding to use SSL. Fortunetley, .Net gives us SSL for MexHttpBindings so we don’t need to configure it. Set the binding attribute to mexHttpsBinding instead of mexHttpBinding.

<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>

Since I had httpGet enabled for Metadata, we also need to set it to use SSL. Instead of setting httpGetEnabled=”true”, I set httpsGetEnabled=”true”.

<serviceMetadata httpsGetEnabled="true"/>

Finally, the wsdl displays correctly with https and I get a 403 error with http.

I change the url in for my test client but when running unit tests, I get this exception

System.ServiceModel.Security.SecurityNegotiationException: Could not establish trust relationship for the SSL/TLS secure channel with authority.

This is happening because in dev, my SSL certificate is invalid. I need to override validation of the certificate in my test client.

//force acceptance of invalid ssl certificates (for dev)     
ServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => true);
 
//create the client      
client = new PartnerAPITest.TutorAccountAPI.ServiceClient();

Note: I’m using an anonymous function that always returns true. You could also create a custom class that inherits ICertificatePolicy. Both approachs are explained here.

Read More
TOP

Getting random rows from Sql Server

I’m working on a project where I want to return related content. The sproc I wrote seems to work ok but because I was sorting by the insert date or the title, it would always return the same thing for all content closely associated.

So how do I get it to return only the closely related content AND randomize it?

Here is the what I did:

SELECT *
FROM #tmpRelated 
JOIN Content c ON r.ContentID = c.ContentID
ORDER BY r.TotalRelevance DESC, r.TotalMatches DESC, newid()

Ordering by newid() will return a random row in Sql Server. In testing this, it worked perfectly. Cool!

Here is the article I found on this. It gives ways to return random rows in Sql Server, MySql, PostegreSql, Oracle, and IBM D2.

Read More
TOP

Neat way to handle Nullable types …

Ever since I read Rick Strahl’s blog post on the C# ?? operator, I’ve been in love with the C# ?? operator. Mostly I use it as a clean way to test a ViewState variable for null in a property. For example,

protected string stringToPersistOnPostBack { 
    get {
         return (ViewState[this.ClientID + "_stringToPersistOnPostBack"] ?? "").ToString();<
     }
}

Somewhere along the way, the real purpose of the ?? operator was forgotten though. It’s true purpose is to give a default value to a Nullable type thus allowing you to use it as the type.

I started with this code:

bool doExpand = (IsPostBack && e.Node.Expanded);

which gave me an error:

Operator && cannot be applied to types 'bool' and 'bool?'

While I often enjoy the use of Nullable types, they do introduce often annoying, sometimes unnecessary complexity to code. But thankfully, the nice folks at Microsoft came up with a rather nifty solution … the ?? operator.

At first, I thought I’d have to use the ?? operator to give e.Node.Expanded a default value of false AND cast the object to bool. Instead, all I had to do was this:

bool doExpand = (IsPostBack && (e.Node.Expanded ?? false));

See? Neat!

Read More
TOP

Forcing ASP .Net Validators and ValidationSummary to use CssClass

Here’s something strange. If I create a validator using the following mark up:

<asp:requiredfieldvalidator id="rfv_txt" runat="server" errormessage="Required" CssClass="errorText" />

and my css class is:

errorText {
    color: purple;
}

My validator still renders with red text. Checking the markup, I see that ASP .Net has added an inline style attribute (style=”color: red”). Obviously, inline styles take precedence over class styles. But why is this inline style being applied at all?

I found this blog post that fixed the issue by setting the Forecolor to Color.Empty but it could only be done server-side.

I figured there must be a way to set this client-side and after much annoyance, I found it:

<asp:requiredfieldvalidator id="rfv_txt" runat="server" errormessage="Required" CssClass="errorText" Forecolor=""/>

So in order to set the color of validators or ValidationSummary via a CSS class you must set both the CssClass property and set the Forecolor property to an empty string. Why ASP .Net? Why?

Read More
TOP

WPF Data Binding Not Refreshing When Bound to Static Object

And the WPF Data Binding wierdness/frustration continues …

I have a DataTemplate where DataType is defined. (In other words, WPF magic figures out when to use the template based on the type that is being bound). The Template includes a ComboBox which is bound to a static object in my UserControl class. The SelectedItem of the combobox is bound to a property of the DataTemplate’s type (which, in this case, is a linq entity object).

It looks something like this:

My problem was that when I changed the DataContext of the UserControl which in turn changed the DataContext of this DataTemplate’s parent control and the DataTemplate itself, the data in the ComboBox didn’t change. In other words, while all the controls around it were being re-bound, this particular control wasn’t.

Grrr.

After much googling, I found a cheap – but helpful – solution. Force the ComboBox to rebind every single time but adding a IValueConverter (which does nothing but return the value) to the binding.

Here is the article with the solution.

Seriously, these WPF Data Binding issues are ridiculous. I mean what exactly was Microsoft testing this shite for? It surely wasn’t real-world examples or even with it’s own new technology (Linq to SQL for example).

Read More