Thursday, July 26, 2012

Call SOAP Web Service With Basic Authorization

Recently I have to call a SOAP Web Service with basic authorization in .Net program. But there is not a simple way to configure the Service Proxy to send the authorization header in HTTP package. I did a little bit search on Internet. Found this solution. Basically, it is adding the header info when initiating the call to web service. It needs an “Authorization” header which is added to the HTTP call which contains the base64 encoded user name and password like this:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

Following are the sample code from this post.

Firstly a method to encode the credentials:

private string EncodeBasicAuthenticationCredentials(string username, string password)
{
  //first concatenate the user name and password, separated with :
  string credentials = username + ":" + password;

  //Http uses ascii character encoding, WP7 doesn’t include
  // support for ascii encoding but it is easy enough to convert
  // since the first 128 characters of unicode are equivalent to ascii.
  // Any characters over 128 can’t be expressed in ascii so are replaced
  // by ?
  var asciiCredentials = (from c in credentials
                     select c <= 0x7f ? (byte)c : (byte)'?').ToArray();

  //finally Base64 encode the result
  return Convert.ToBase64String(asciiCredentials);
} 

Now that we have a means of encoding our credentials we just need to add them to the headers of our WCF request.  We can easily do this by wrapping the call in an OperationContextScope:

var credentials = EncodeBasicAuthenticationCredentials("username", "password");

using (OperationContextScope scope =
          new OperationContextScope(service.InnerChannel))
{
  HttpRequestMessageProperty request = new HttpRequestMessageProperty();
  request.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + credentials;

  OperationContext.Current.OutgoingMessageProperties.Add(
                                     HttpRequestMessageProperty.Name, request);

  service.DoSomethingAsync();
}

Friday, July 20, 2012

How to make barcode font display correctly in web service

Just got an issue when using barcode font in a web service hosting in IIS7. The barcode font can't display in the document which is generated inside the web service. And the solution to make it work is setting the option "Load User Profile" of IIS 7 application pool to True.