Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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.

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;
}

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!

Tuesday, February 01, 2011

Left Outer Join in Linq

I always can't quite remember how to do left outer join in Linq. Here is an example of how to do left outer join in linq using C#.

Class definitions:
class Book
{
    public int Id { get; set; }
    public String Name { get; set; }
}
 
class OrderItem
{
    public int BookId { get; set; }
    public int Quantity { get; set; }
}
Sample data:
var books = new List<Book>
{
    new Book {Id = 1, Name = "Groovy in Action"},
    new Book {Id = 2, Name = "Implementation Patterns"},
    new Book {Id = 3, Name = "C# Cookbook"}
};
var orderItems = new List<OrderItem>
{
    new OrderItem {BookId = 1, Quantity = 1},
    new OrderItem {BookId = 1, Quantity = 2},
    new OrderItem {BookId = 1, Quantity = 2},
    new OrderItem {BookId = 2, Quantity = 1},
    new OrderItem {BookId = 2, Quantity = 1},
    new OrderItem {BookId = 2, Quantity = 1}
};
Query:
var query = from b in books
            join oi in orderItems on b.Id equals oi.BookId into t
            from r in t.DefaultIfEmpty(new OrderItem())
            select new
                        {
                            BookId = b.Id,
                            BookName = b.Name,
                            Quantity = r.Quantity
                        };
 
foreach (var r in query)
{
    Console.WriteLine("Id = {0} Name = {1} Quantity = {2}",
        r.BookId, r.BookName, r.Quantity);
}
Result:
Id = 1 Name = Groovy in Action Quantity = 1
Id = 1 Name = Groovy in Action Quantity = 2
Id = 1 Name = Groovy in Action Quantity = 2
Id = 2 Name = Implementation Patterns Quantity = 1
Id = 2 Name = Implementation Patterns Quantity = 1
Id = 2 Name = Implementation Patterns Quantity = 1
Id = 3 Name = C# Cookbook Quantity = 0

Saturday, January 29, 2011

How to set CommandTimeout in EF5

var objectContectAdapter = this.DbContext as IObjectContextAdapter;
objectContectAdapter.ObjectContext.CommandTimeout = 120;