Thursday, May 31, 2012

Steps to Create Self Signed Certificate for use with C# Thrift Server and Java Thrift Client over SSL

The C# implementation of Thrift does not have build in support for SSL as of version 0.8.0.27874. It doesn't seems like there is any interest in integrating the two provided solutions, https://issues.apache.org/jira/browse/THRIFT-181 and https://issues.apache.org/jira/browse/THRIFT-66, from the community either. The Java implementation does have support for SSL though.

Unfortunately, I have a need to provide a Thrift service over SSL using C#. I used the solution provided in issue 181.

This is the story on how I went about creating a self signed certificate for the server and client side.

This is what I have on my computer
1. .Net 4.0
2. Java SDK

Create the self signed certificate on Windows
(I am using Windows 7)

1. Open IIS Manager
2. Click on your computer name on the left pane. It should look something like this.
3. Double click on Server Certificates
4. Right click and select Create Self-Signed Certificate
5. Enter "Thrift Self Signed Certificate Demo" or whatever name you want to give your certificate.
6. Export the Certificate by right click on it and select Export.
7. Fill in the file name for the certificate and the password. You should see a pfx file created in your chosen directory. For this demo purpose, my exported certificate file name is ThriftSelfSignedCertificateDemo.pfx Now we have a self signed certificate.

Convert the Certificate to JKS store type

1. For the next couple of steps you will need to have a copy of openssl. If you don't have it then you can download it from http://slproweb.com/products/Win32OpenSSL.html. I downloaded "Win64 OpenSSL v1.0.1c Light" and "Visual C++ 2008 Redistributables (x64)"
2. Open up a command prompt
3. Type in
openssl.exe pkcs12 -in ThriftSelfSignedCertificateDemo.pfx -out ThriftSelfSignedCertificateDemo.pem

4. Enter the password you provided during the certificate export process.
5. Enter in a new password for the PEM file.
6. Next type in
openssl.exe pkcs12 -export -in ThriftSelfSignedCertificateDemo.pem -out ThriftSelfSignedCertificateDemo.p12 -name " ThriftSelfSignedCertificateDemo"
7. Enter the password you provided during the PEM export process
8. Enter in a new password for p12 file.
9. Finally, we are ready to create the jks file. Type in keytool -importkeystore -srckeystore ThriftSelfSignedCertificateDemo.p12 -destkeystore  ThriftSelfSignedCertificateDemo.jks -srcstoretype pkcs12 -deststoretype JKS
10. Enter a password for the new JKS keystore
11. Enter the password you provided when creating the p12 file

Now you have all the necessary certificates for the Java Thrift client ssl and C# Thrift Server ssl.

ThriftSelfSignedCertificateDemo.jks is for the Java client.
ThriftSelfSignedCertificateDemo.pfx is for the C# server.

Monday, April 09, 2012

TopShelf Service won't install

I created a Windows service using TopShelf and for the life of me I couldn't get it to install. I followed the Command Syntax from http://topshelf-project.com/documentation/command-line-syntax/ and the install process ran with no error. But when I did net start myservice, I get "The service name is invalid." After a lot of head scratching, I realized I need to run the install process as an Administrator. Anyway, I put it here just in case someone has the same problem I have.


Saturday, April 07, 2012

Dell XPS 15z active window randomly lost focus

I have been using the Dell XPS 15z for a few months and it has this really annoying bug that drive me crazy. Some how my active window would lose focus and I have no idea why. I look at the task bar and there appears to be no other active window. This is especially frustrating while writing code. After doing a little research, I cut and paste together a little utility that helps pin point the thief. It was Dell quickset.exe util. Further research reveal that the ambient light sensor trigger quickset.exe which in turn steals the focus from the active window. You can read more from this forum, http://en.community.dell.com/support-forums/laptop/f/3518/t/19393785.aspx?PageIndex=3.

Here is the code to my little utility. I didn't come up with the idea nor the code.
https://bitbucket.org/tuesdaysiren/detectfocusstealingprocess/overview

There doesn't seem to be a fix for the problem except taping over the sensor. The only temporary fix is to adjust the back-light by pressing Fn + F6.

Friday, April 06, 2012

Partial declarations of must not specify different base classes

I am working on my first WPF application and I decided to clean up my code and moved all common properties into a  base class for all my user controls. I hit this error, Partial declarations of must not specify different base classes. After a few minutes of head scratching, I found this post,
http://blog.peterlesliemorris.com/archive/2009/07/23/partial-declarations-of-must-not-specify-different-base-classes.aspx, by Peter Morris that fixed the problem. Basically, the base class is declared in the xaml.

Basically, just change your xaml from
<UserControl x:Class="MyApp.MyUserControl" />
to
<local:BaseUserControl
  x:Class="MyApp.MyUserControl "
  xmlns:local="clr-namespace:NameSpace.To.Your.BaseClass"
  />

Yes, I copied the sample from Peter Morris's post.

Thursday, March 08, 2012

RtkNGUI64.exe using 25% of my CPU issue and solution

I had a problem with my computer's fans constantly running because RtkNGUI64.exe was using 25% CPU time continuously. The only way I was able to fix the problem was killing the process. There is a problem with killing the process though. All sound would come through the speaker even when I plug in the headphone. Unfortunately, I am working in an open environment so that is unacceptable. I finally found a solution on dell forum by cheshirecat179. Here is the link to the thread.

The problem has to do with a missing registry key (HKEY_LOCAL_MACHINE/SOFTWARE/SRS Labs/APO). RtkNGUI64.exe looks for a the registry key and since it is not there, it keeps on trying. The solution is to add the registry key.

Here are the steps from the post:
Click the Windows Orb button thing (Start Button)
In the search bar, type regedit
Navigate to HKEY_LOCAL_MACHINE/SOFTWARE
Right click "SOFTWARE" and left click "New", then "Key"
Name it "SRS Labs" (without quotes)  - that's one
Next, right click "SRS Labs", left click "new" then left click "Key" again
Name it "APO" (without quotes)

Saturday, March 03, 2012

How I solved my on board LAN wasn't able to connect above 10 Mbps problem

Yesterday, while trying to use my laptop as a test runner to do performance test, it was only able to connect to the network at 10 Mbps even though the switch and my laptop both support 1 Gbps. All the other machines that were connected to the switch were connecting at 1 Gbps. I tried to do everything including restarting my computer but nothing help. The same laptop was able to connect at 1 Gbps to the switch a few week ago. My boss needed the performance numbers and I was at a lost on what to do. I Google around and landed on this page. The solution is quite simple.
  1. Turn off your computer
  2. Wait a few minutes
  3. Turn it back on
It does sound stupid but it worked like a charm. Don't you wish all computer problems can be solved this way? 

Monday, February 27, 2012

MakeGenericType to the rescue

I have a need to return a HttpResponseMessage<> in an ActionFilterAttribute with ActionDescriptor.ReturnType. All my response object belong to a single base class. Anyway, here is how I did it.

private static void SetInvalidRequestResponse(HttpActionContext context)
{
  var returnType = context.ActionDescriptor.ReturnType;
    
  var response = Activator.CreateInstance(returnType) as BaseResponse;
  var request = context.ActionArguments.First().Value as BaseRequest;

  response.ResponseCode = "Invalid request";

  if (request != null)
  {
    response.SourceId = request.SourceId;
    response.Uuid = request.Uuid;
  }

  var genericType = typeof (HttpResponseMessage<>)
    .MakeGenericType(new[] {returnType});

  context.Response = Activator
    .CreateInstance(genericType, response, HttpStatusCode.Forbidden)
      as HttpResponseMessage;
}

Thursday, February 23, 2012

Use Windsor as Dependency Resolver for Asp.Net Web Api

Here is a little code snippet you can use to integrate Windsor into Web Api. One important note about this class is that we are only resolving Type we care to register to our container and we leave to rest to Web Api internal dependency resolver. We do that by return null in the GetService method and returning an empty collection for GetServices method. You should read Using the Web API Dependency Resolver by Mike Wasson to have a better understanding of how the process work.

public class WindsorDependencyResolver : IDependencyResolver
{
  private readonly IWindsorContainer _container;

  public WindsorDependencyResolver(IWindsorContainer container)
  {
    _container = container;
  }

  public object GetService(Type serviceType)
  {
    return _container.Kernel.HasComponent(serviceType) ?
      _container.Resolve(serviceType) : null;
  }

  public IEnumerable<object> GetServices(Type serviceType)
  {
    return _container.Kernel.HasComponent(serviceType) ?
      _container.ResolveAll(serviceType).Cast<object> () : new List<object>();
  }
}

The next step is to register your Dependency Resolver. I added this line to my Application_Start.

GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new WindsorDependencyResolver(IocContainer));

Wednesday, February 22, 2012

Found the solution

I asked my question on the asp.net forum and I got the answer. Go here to see the solution.

Anyway, I will include the answer here just in case the post disappeared in the future.

public class ReadAsSingleObjectPolicy : IRequestContentReadPolicy
{
  public RequestContentReadKind GetRequestContentReadKind(HttpActionDescriptor actionDescriptor)
  {
    return RequestContentReadKind.AsSingleObject;
  }
}
GlobalConfiguration.Configuration.ServiceResolver
  .SetService(typeof(IRequestContentReadPolicy), new ReadAsSingleObjectPolicy());

Default XmlSerializer for Web Api do not to support complex object?

I am trying to post an xml of a model with nested objects and the XmlSerializer for Asp.Net Web Api only deserialize the first level property.

I found a solution to my problem but I am sure I am not doing it right.

Here is an example of the xml I am trying to post and the C# classes it supposed to deserialize to.
<customer>
  <customerid>100</customerid>
  <orders>
  <order><orderid>1</orderid><amount>1</amount></order>
  <order><orderid>2</orderid><amount>2</amount></order>
  </orders>
</customer>
public class Customer
{
  public Customer()
  {
    Orders = new List();
  }

  public string CustomerId { get; set; }

  public List Orders { get; set; }
}

public class Order
{
  public string OrderId { get; set; }
  public int Amount { get; set; }
}

The only thing I get is CustomerId = 100. Orders count is 0. If I switch the Content-Type to application/json then it deserialized correctly.

After many trials and errors, I noticed that the Type parameter of the OnReadFromStreamAsync in XmlSerializer is IKeyValueModel instead of Customer like I expected.

I ended up writing my own XmlFormatter and replace the default one with mine. I added this two lines to my Application_Start method.

GlobalConfiguration.Configuration.Formatters.Add(new CustomXmlFormatter());
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Here is mine CustomXmlFormatter class.

  public CustomXmlFormatter()
  {
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
    Encoding = new UTF8Encoding(false, true);
  }

  protected override bool CanReadType(Type type)
  {
    if (type == (Type)null)
      throw new ArgumentNullException("type");

    if (type == typeof(IKeyValueModel))
      return false;

    return true;
  }

  protected override bool CanWriteType(Type type)
  {
    return true;
  }

  protected override Task OnReadFromStreamAsync(Type type, Stream stream, 
    HttpContentHeaders contentHeaders, FormatterContext formatterContext)
  {
    return Task.Factory.StartNew(() =>
    {
      using (var streamReader = new StreamReader(stream, Encoding))
      {
        var serializer = new XmlSerializer(type);
        return serializer.Deserialize(streamReader);
      }
    });
  }

  protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, 
    HttpContentHeaders contentHeaders, FormatterContext formatterContext, 
    System.Net.TransportContext transportContext)
  {
    var serializer = new XmlSerializer(type);
    return Task.Factory.StartNew(() =>
    {
      using (var streamWriter = new StreamWriter(stream, Encoding))
      {
        serializer.Serialize(streamWriter, value);
      }
    });
  }
}

Tuesday, February 21, 2012

Simplest Web Api Site with Nuget

Here are the steps to create the simplest ASP.Net Web Api with Nuget. If you want to know more about Web Api, go here and read up.

1. Create an Empty Web Application and call it SimpleWebApi.









2. Open your Package Manager Console if it is not already open. Go to View-> Other Windows-> Package Manager Console.

3. Type these two lines
Install-Package AspNetWebApi
Install-Package System.Json

You will see something similar to this:
PM> Install-Package AspNetWebApi
Attempting to resolve dependency 'AspNetWebApi.Core (≥ 4.0.20126.16343)'.
Attempting to resolve dependency 'System.Net.Http.Formatting (≥ 4.0.20126.16343)'.
Attempting to resolve dependency 'System.Net.Http (≥ 2.0.20126.16343)'.
Attempting to resolve dependency 'System.Web.Http.Common (≥ 4.0.20126.16343)'.
'AspNetWebApi 4.0.20126.16343' already installed.
Successfully added 'System.Net.Http 2.0.20126.16343' to SimpleWebApi.
Successfully added 'System.Net.Http.Formatting 4.0.20126.16343' to SimpleWebApi.
Successfully added 'System.Web.Http.Common 4.0.20126.16343' to SimpleWebApi.
Successfully added 'AspNetWebApi.Core 4.0.20126.16343' to SimpleWebApi.
Successfully added 'AspNetWebApi 4.0.20126.16343' to SimpleWebApi.
PM> Install-Package System.Json
'System.Json 4.0.20126.16343' already installed.
Successfully added 'System.Json 4.0.20126.16343' to SimpleWebApi.

4. Right click on the SimpleWebApi project and select Add -> New Item
5. Select Global Application Class and click Add.
6. Open Global.asax and add this line to Application_Start

        protected void Application_Start(object sender, EventArgs e)
        {
            System.Web.Routing.RouteTable.Routes.MapHttpRoute("Default Api", "{Controller}");
        }

7. Add System.Web.Http; to the top of the file.
8. Right click on the SimpleWebApi project and select Add -> New Folder and create a folder name Api. Your project layout should look like this now.








9. Right click on the Api folder and select Add -> Class.
10. Name the class as GreetingController.cs
11. Modify your GreetingController to look like this:

using System;
using System.Web.Http;

namespace SimpleWebApi.Api
{
    public class GreetingController : ApiController
    {
        public string GetGreeting(string name)
        {
            return String.Format("Hello {0}", name);
        }
    }
}
12. Press Ctrl + F5 to run your project. A browser should popup with a Directory listing.
13. Add /Greeting to the end of the url. For example: mine url was http://localhost:4831 so I change it to be http://localhost:4831/Greeting. Your browser should display something similar to this:














14. Now edit your url to be http://localhost:4831/Greeting?World. Remember to make sure your port number is correct. Here is what should be displayed.














You are done. Congratulation!