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;
}
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.
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.
The next step is to register your Dependency Resolver. I added this line to my Application_Start.
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.
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.
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.
Here is mine CustomXmlFormatter class.
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
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.
7. Add System.Web.Http; to the top of the file.
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!
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!
Thursday, April 07, 2011
Make taskbar smaller when docking on the side
In Windows 7, you can set your taskbar icon to small and the taskbar will shrink to a smaller side. Unfortunately, it will grow back to normal size if you dock the taskbar to either the left or right side of the desktop. There is no way to make just wide enough to fit the small icons. Well, there is none supported way to do it.
Here are the steps to get back the small taskbar when docking on the side:
1. Right click on the taskbar and select properties
2. Make sure Lock the taskbar, Auto-hide the taskbar, Use small icons are all checked
3. Click Ok
4. Press Windows Key and type services
5. Restart the "Desktop Window Manager Session Manager" service by right clicking on the service and select Restarst
6. Unhide your taskbar and select Properties
7. Uncheck Auto-hide the taskbar
8. Sit back and enjoy the smaller taskbar
Here is a video that goes through the steps.
Friday, March 04, 2011
Griffon Eclipse Integration
I spend a better part of a day searching around to figure out how to get Griffon and Eclipse to play nice together. I figured I will write it up to help the next person.
First you need to install the Groovy-Eclipse plugin. Here is the step by step guide to installing Groovy-Eclipse plugin:
http://docs.codehaus.org/display/GROOVY/Install+Groovy-Eclipse+Plugin
After you installed the plugin, follow the following steps to add eclipse support to your Griffon project.
Create a new Griffon project:
> griffon create-app eclipse-integration
Add the Eclipse integration
> cd eclipse-integration
> griffon --integrate-with --eclipse
Install the Eclipse plugin to your Griffon project
> griffon install-plugin eclipse-support
If you need a specific version of the eclipse-support then you can specify it at the end. Since I am using Griffon 0.9.1a, I need to use version 0.3.1 of the eclipse support plugin.
> griffon install-plugin eclipse-support 0.3.1
Now you need to update the .classpath file in the project
> griffon eclipse-update
Now it is time to import the project into Eclipse. Go to Eclipse and select File -> Import.
Select General -> Existing Projects into Workspace
Press Next
Select the root directory of the Griffon project and click Finish.
You are almost there. If you select run right now, it will complain about GRIFFON_HOME is not set.
Right click on your project.
Select Run As then Run Configuration.
Expand Java Application.
You should find eclipse-integration under Java Application if you follow along with instruction or it will be whatever you name your project.
Select eclipse-integration.
Select the tab Environment on the right.
Click the New button
For name type in GRIFFON_HOME.
For value type in the path to Griffon.
Click Ok.
Click Apply.
Click Run.
Gotcha:
I find that when I am editing a view, I can't click Run to run the project. I have to click on the project then click run to run it. Editing the controller and model do not have this problem.
First you need to install the Groovy-Eclipse plugin. Here is the step by step guide to installing Groovy-Eclipse plugin:
http://docs.codehaus.org/display/GROOVY/Install+Groovy-Eclipse+Plugin
After you installed the plugin, follow the following steps to add eclipse support to your Griffon project.
Create a new Griffon project:
> griffon create-app eclipse-integration
Add the Eclipse integration
> cd eclipse-integration
> griffon --integrate-with --eclipse
Install the Eclipse plugin to your Griffon project
> griffon install-plugin eclipse-support
If you need a specific version of the eclipse-support then you can specify it at the end. Since I am using Griffon 0.9.1a, I need to use version 0.3.1 of the eclipse support plugin.
> griffon install-plugin eclipse-support 0.3.1
Now you need to update the .classpath file in the project
> griffon eclipse-update
Now it is time to import the project into Eclipse. Go to Eclipse and select File -> Import.
Select General -> Existing Projects into Workspace
Press Next
Select the root directory of the Griffon project and click Finish.
You are almost there. If you select run right now, it will complain about GRIFFON_HOME is not set.
Right click on your project.
Select Run As then Run Configuration.
Expand Java Application.
You should find eclipse-integration under Java Application if you follow along with instruction or it will be whatever you name your project.
Select eclipse-integration.
Select the tab Environment on the right.
Click the New button
For name type in GRIFFON_HOME.
For value type in the path to Griffon.
Click Ok.
Click Apply.
Click Run.
Gotcha:
I find that when I am editing a view, I can't click Run to run the project. I have to click on the project then click run to run it. Editing the controller and model do not have this problem.
Friday, February 18, 2011
Mac Mini ethernet port does not work at 1 Gigabit
Today I decided to connect my Mac Mini to the router using the ethernet cable and it didn't work. It would connect and then disconnect a minute later. I tried using different cables but that didn't fix the problem. Those cables work when I connect them to my PC so it is not the cable problem. Anyway, after browsing around the support forum, I decided to down grade the connection from 1 Gigabit to 100 Mbps and it starts to work.
Thursday, February 17, 2011
It takes 3 to 5 days to load money onto a Clipper Card!!
Please note that when you add value online, it can take up to 3-5 days for the value to be available to be loaded onto your card, and you must tag your card to a card reader to load the value.I was hit with that message when trying to load my Clipper Card tonight. On top of that, you can't actually add money onto your card online. You need to go and tag your card at a card reader before the money can be loaded. No wonder the page title is "Add value online" instead of "Add value to your Clipper Card online".
The next stupid thing is this line.
Your card balance will not be updated until you have tagged your card and loaded the value.Of course, you don't know when to go and tag your card because it can take up to 3-5 days before the money is available. I guess you can go and tag your card everyday then go online and check your balance. If your balance went up then you have successfully loaded your card. What a dump design. I bet those engineers made a bunch of money coming up with this stupid process too. So much for trying to be more efficient.
Of course, I do have an alternative way to do this. If I walk to my local Walgreens, they can put money onto the card right away. Since I have to walk to Walgreens to load my card, I might as well just get a new one. The card is free.
Thursday, February 10, 2011
Bidirectional binding in Griffon
It took me a lot of searching to figure out how to do bidirectional binding in Griffon.
class PersonModel {
@Bindable String firstName
}
textField(id: 'firstName', text: bind(target: model, targetProperty: 'firstName', mutual: true)
The key word is "mutual: true"
Here is where I got the info from. It is at the bottom of the article.
http://www.jroller.com/aalmiray/entry/building_rich_swing_applications_with2
class PersonModel {
@Bindable String firstName
}
textField(id: 'firstName', text: bind(target: model, targetProperty: 'firstName', mutual: true)
The key word is "mutual: true"
Here is where I got the info from. It is at the bottom of the article.
http://www.jroller.com/aalmiray/entry/building_rich_swing_applications_with2
Wednesday, February 02, 2011
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 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
Monday, January 31, 2011
backbone.js
This looks like a useful tool for those that write a lot of javascript for web development.
From backbone.js website:
"Backbone supplies structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface."
Here is a quick write up on how to use the library from Thomas Davis.
From backbone.js website:
"Backbone supplies structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface."
Here is a quick write up on how to use the library from Thomas Davis.
Sunday, January 30, 2011
Vim screencasts
Derek Wyatt published a series of screencasts on Vim.
http://ontwik.com/tools/vim-from-novice-to-professional-by-derek-wyatt-p1/
http://ontwik.com/tools/vim-from-novice-to-professional-by-derek-wyatt-part-2/
http://ontwik.com/tools/vim-from-novice-to-professional-by-derek-wyatt-p1/
http://ontwik.com/tools/vim-from-novice-to-professional-by-derek-wyatt-part-2/
Saturday, January 29, 2011
How to set CommandTimeout in EF5
var objectContectAdapter = this.DbContext as IObjectContextAdapter; objectContectAdapter.ObjectContext.CommandTimeout = 120;
Friday, January 28, 2011
A new beginning
I removed all my previous posts from this blog and started anew. It was interesting reading through my trials and tribulations but it is time to start a new chapter and leaving the past behind.
I guess I should give a little explanation for my blog url. I wanted it to be myrandomthoughts but someone already took it. I decided to be creative and look up the translation for the word thought in Vietnamese and ý kiến came up. So, there you have it. The story of my blog url.
I guess I should give a little explanation for my blog url. I wanted it to be myrandomthoughts but someone already took it. I decided to be creative and look up the translation for the word thought in Vietnamese and ý kiến came up. So, there you have it. The story of my blog url.
Subscribe to:
Posts (Atom)



