Tuesday, April 14, 2009

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" />
<message />
</security>
</binding>
</basicHttpBinding>
</bindings>

Then I added a bindingConfiguration to the service configuration:

<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. Fortunetly, .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.

Tuesday, February 3, 2009

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

Monday, January 26, 2009

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!

Thursday, October 9, 2008

Web Dev Best Practices

This has come up in various conversations recently and I was bored so I was googling for html best practices. I thought this article from Apple was quite good.

Tuesday, September 30, 2008

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?

Friday, August 1, 2008

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

Thursday, July 31, 2008

Type casting your User Control Class in ASP .Net 2.0+

I ran into a little bit of a strange issue today:

I created a User Control that was being used multiple times on a page. It contained a few public methods and properties that allowed me to delegate loading and saving of the data to the control.

Since I have a personal aversion to typing out the same thing for controls with different names, I wanted to just loop through the Controls, check for the type, cast, and call the method. Seems simple right?

Not so much.

First I had a bit of trouble getting the actual type to cast. I googled and found a solution:

((ASP.controls_myControlName_ascx) myControl1).LoadMethod();

Super. The code ran just dandy on my local machine.

However, I ran into a bit of trouble when we deployed the code to our testing environment. It couldn't figure out what ASP.controls_myControlName_ascx. Of course, this happened when my internet was down and I was working at home and everyone was freaking out.

To fix the deployment issue, first, I got rid of the "ASP." prefix. Then it wouldn't compile on my local machine. Bah.

In googling, I came across this article: Understanding Page Inheritance in ASP.Net 2.0 by Rick Strahl. I used his solution for Pages and created an abstract base class which inherited from UserControl and contained abstract public methods. I put the abstract class into the App_Code folder and wa-la! I could cast the controls to the base class and call the methods and set public properties. Yay!

Sort of. It's actually kind of a lame solution but it works and is acceptable.