Host ASP.NET Web API In WPF Application

(The following content from

Now WCF Web API changed to ASP.NET Web API. ASP.NET Web API has the feature of self-host. In Microsoft official site, they also provides two simples ASP.NET Web API self-host samples. However, they are so simple and actually they looks like the “same” one because these 2 simples are Console applications and use very similar content.

The WPF is more popular for new Windows Application solutions, so we want to find a sample that how to host ASP.NET Web API in a WPF Application. Let’s start:

First, If you have not installed ASP.NET MVC 4 (at present it is still MVC 4 beta), please go to Microsoft ASP.NET website MVC 4 part to download and install it;

After the MVC 4 stuff installed, we can write the code now.

Note: We are using Visual studio 2010.

1: Open Visual Studio 2010 as Administrator :
(Note: this step is important, you must open Visual Studio as Administrator because later we need to listen at a particular HTTP address. )


Or, if you do not want to open Visual Studio 2010 as Administrator, you must use Use Netsh.exe to give your current Windows user account permissions to reserve the URL first:

netsh http add urlacl url=http://+:8080/ user=machine\username   (check Microsoft sample here)

2: Create a WPF application, We give a project name WpfHostWebApiDemo, make sure .NET Framework 4 is selected:

(for avoiding the build errors which mentioned in the step 7, please read step 7 first, if you don’t want to do the target framework changing, you are still OK but you have to following everything descripted in step 7 later)


3: Install ASP.NET Web API Self Host package:

We will use NuGet Package Manager to install ASP.NET Web API Self Host package. Right click the project name in  in Visual Studio 2010, and choose “Manage NuGet Packages…”, If you can not see this item, it means you have not installed NuGet Package Manager for Visual Studio 2010, Please go to NuGet project site to get help information to download and install it.


About NuGet:
NuGet is a Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects that use the .NET Framework. When you add a library or tool, NuGet copies files to your solution and automatically makes whatever changes are needed in your project, such as adding references and changing your app.config or web.config file. When you remove a library, NuGet removes files and reverses whatever changes it made in your project so that no clutter is left.

When you open the Manager NuGet Packages Windows, Input “webapi selfhost” in the top right search box, The Manager can search automatically for you, You will see “ASP.NET Web API Self Host (Beta)” (Currently it is still in Beta stage) and click Install Button.


After click Install button, The install process started:


After the installation finished, click Close button to close NuGet Package Manager.

Now you can see some information in the output windows of Visual Studio 2010:

Also, you should see there are new references were added into current project:

Now we are ready to star our Web API in current project.

4: In Current project, Add a folder named Models, and add a Model class named ItemModel:

namespace WpfHostWebApiDemo.Models
    public class ItemModel
        public int ItemID { get; set; }
        public string ItemName { get; set; }
        public double ItemValue { get; set; }

5: Add a new folder named Controllers, in this folder, add a new Item, specify the template to Web API Controller Class in Web category. Give the name ItemController


Remove all generated code and add the following code into ItemController class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using WpfHostWebApiDemo.Models;

namespace WpfHostWebApiDemo.Controllers.Controllers
    public class ItemController : ApiController
        // GET /api/<controller>
        public IEnumerable<ItemModel> Get()
            return new List<ItemModel> 
                new ItemModel() { ItemID = 1, ItemName = "Item1", ItemValue = 100 },

6: Host service:

Add the windows loaded event in MainWindow, and add host service code, All MainWindow.xaml,cs file code is like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Web.Http.SelfHost;
using System.Web.Http;

namespace WpfHostWebApiDemo
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

        private void Window_Loaded(object sender, RoutedEventArgs e)
            var config = new HttpSelfHostConfiguration("http://localhost:5477");

                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))

                MessageBox.Show("Web API service started.");

In above code, we listen  localhost:5477, which you can change the port number to what port number you like.

7: Compile and Build project:

Now we build the project, we will see at least 5 error messages:

The type or namespace name ‘ApiController’ could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name ‘SelfHost’ does not exist in the namespace ‘System.Web.Http’ (are you missing an assembly reference?)

The type or namespace name ‘HttpSelfHostConfiguration’ could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name ‘HttpSelfHostServer’ could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name ‘HttpSelfHostServer’ could not be found (are you missing a using directive or an assembly reference?)


The reason is current WPF project is based on the target framework ASP.NET Framework 4 Client Profile, which miss some libraries, Just right click the project name in Visual Studio 2010 and select property, and change the target framework to ASP.NET Framework 4.


After you changed the target framework to .NET Framework 4, Visual Studio 2010 will give you a message that the project need to be closed and re-open, but looks seems the Visual Studio 2010 can not re-load the project automatically, so here you should close Visual Studio manually first, and open Visual Studio 2010 as Administrator again, and load our demo project.

(Note: for avoid to re-open Visual Studio, you’d better change Target framework in step 2)

Now let us rebuild the application, we see the old error messages gone, but we get the following new errors:

The type ‘System.Web.Routing.RouteCollection’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’.

The type ‘System.Web.Routing.Route’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’.

The reason is we still missed a dll file, let’s add reference to System.Web, the version is 4.0


Now rebuild again. the build is OK now!

8: Run the Web API Service:

Click Ctrl + F5, you will see the service started message which we added in code.


Open web browser and input the URL address: localhost:5477/api/item

you will see the service content as XML format on the web page:


Now we know the Web API service is working! You can create a client to consume the service now.

Java 7 Released!

Oracle release Java 7 Standard Edition in 2011 July 28! This is a big news for programmers.

“We are excited to announce Java 7 is released!

With years of hard work from our dedicated engineers, the largest team ever to work on the Java language and platform, as well as valuable input from the Java community, we are moving Java forward with this release.

This release contains new language features (JSR 334), support for dynamic languages (JSR 292), a new multicore-ready API (JSR 166), new I/O APIs (JSR 203), and many other new features.”


(from Oracle official site)

More detail information please read

Install Windows Phone 7 Developer Tools for Visual Studio 2010

Recently Microsoft’s Windows Phone 7 Development is a hot pot. Microsoft has released Windows Phone Developer Tools , Normally you see the install package includes Visual Studio 2010 Express, and they provides most of information is based on Visual Studio 2010 Express. So that means the Windows Phone 7 Developer Tools are only available for Visual Studio 2010 Express ?

If for their earlier package, the answer is YES. but for now, the answer is NO. Windows Phone 7 Developer Tools will install an add-in for Visual Studio 2010 professional or ultimate version.

Please read MSDN information here :

The Windows Phone Developer Tools includes Visual Studio 2010 Express for Windows Phone, the Windows Phone Emulator, XNA Game Studio, Expression Blend for Windows Phone, samples, and documentation. If Visual Studio 2010 Professional or higher is already installed on your development computer, an add-in for Visual Studio 2010 Professional is automatically installed as well.

Extra detail information can be found another MSDN page here too:

If Visual Studio 2010 Professional or higher is already installed on your development computer, an add-in for Visual Studio 2010 Professional is automatically installed as well. With the exception of a few debugging features, the add-in provides Windows Phone application development support equivalent to Visual Studio 2010 Express for Windows Phone.

Visual Studio 2010 Professional

Installation of Visual Studio 2010 Express for Windows Phone along with add-in to existing Visual Studio installation. Developers can use either version.

OK, above is only for the SDK installation. For more Windows Phone Development, you can read MSDN here .

Where to download ?

Due to Microsoft’s App Hub – a website for Windows Phone and XBox 360 developer, you should follow 3 steps to the install process:

1:   Download and install the Windows Phone Developer Tools
2:   Download and install the Windows Phone Developer Tools January 2011 Update
3:   Download and install the Windows Phone Developer Tools Fix

Note: If you have installed SP1 for your Visual Studio 2010 before you install above Windows Phone 7, you still can install the above package. But, after you finish all install steps, when you try to open your Visual Studio 2010, you will get the following error information:

The reason is might some of software in Windows Phone 7 Developer Tools package is still the old version before Visual Studio SP1, so what you have to do is re-install your Visual Studio 2010 sp1, Actually you do not need to uninstall your Visual Studio 2010, just double click the SP1 install file, and you will see an option for "ReApply" sp1. After you click ReApply, the Visual Studio 2010 sp1 will be installed again for your system.

Finally, everything will be OK.

Retrieving the COM class factory for component with CLSID

We have a C# application which built in Windows XP using Visual Studio 2010, when we install this application to a 64-bit Windows 7 PC, we got the following error message in a popup windows:

Retreving the COM class factory for component with CLSID
{0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC} failed due to the following error:
80040154 Class not registered (Exception from HRESULT: 0x80040154

More info please read

CodeEase Article: Hate installations? Use Lightweight IIS and SQL Server

When you build an ASP.NET application, you might fee some boring works which you have to install a SQL Server database , no matter you can install SQL Server Express version, but you still have to install it. and also, if you want to try your application without using Visual Studio, you have to install IIS or set the existing IIS in your Windows system.

Now you will no more hate the above 2 works: Microsoft has provided you 2 new great products:

For detail, please read CodeEase here

About Memory Management in .NET

Today I give a topic which maybe most of us are interested in it,  no matter you are a C++ or C# programmer, or even you are not a programmer, it is from the following questions which most of us always asked:

1: Why theres is no more Pointer in C#?
2: How to release memory in C# if no Pointer ?
3: Can we force to release memory in C# ?

I am not a good article writer and can not speak too much in English. So I try to give you guys simple concepts and simple content:

There is really big differences between C# and C++ about Memory Management.

What C++ did:

In C++, when we allocate a memory to a object or class, we normally have to free it (release) otherwise this memory will NOT released and can not be used by others applications, this is called “Memory Leak”, a professional C++ programmer should always manage his memory related code otherwise your application will “Down” and it might “Down” your windows system also. So Pointer in C++ is powerful and flexible but you have to accept it is also very dangerous .

Manged code and Unmanaged code

In .NET (or Java) , pointer has been removed (you still can use Pointer in C#, actually it is that you embedded your C++ code in C# and indicate C++ code using “Unsafe” word , they are still C++ code );
People call C# and Java Managed Code,  which means some important things have been “Managed” by .NET framework (Java has its framework too), then you know now we call C++ is Unmanaged code.

The one of “Managed” thing is Memory management.

the programming machination changed a lots in C#, The big changes in C# (here we should call .NET, here I use C# instead of .NET ) is that programmer does NOT need to manage memory which he used, well, actually you can say you CAN NOT manage it .  Because the memory allocate and memory release are Managed by .NET .

Garbage Collection:

.NET framework uses AppDomain to give each application, different applications has different AppDomain, .NET manage AppDomain to guarantee each applications can not occupy memory which other applications are using. All memory is managed by a “Model” which is called Garbage Collection  (we can GC) in .NET.

GC has its mechanism to collect “Garbage Memory” (Garbage Memory is the memories unit are no more used by all applications), programmer can load GC.Collect() method to try to “force release memory” but the force will not work as your understanding, and load GC.Collect() is not recommended because it leads unexpected issues.

GC is always running in .NET, it ONLY collect garbages memory under some conditions, for example, here is a condition: when it found the available memory is not enough,  it will try to collection all garbage memory and let them to be reused.

Here we have to know:

1: No matter we use some code to try to force release memory (for example, dispose or even load GC.Collect() method), The GC will NOT work at once, your memory will NOT released at once either, ONLY GC found the “Garbage Collection Time ” comes, then it works to collect garbage memory;

2: Do not worry about GC occupy system time, this is totally a wrong understanding. how can you control GC to stop working ? and you never know what time GC will work.
 (btw: there is no more destruct concept in .NET even you can use it in C#, you only can use Finalize , but Finalize is not Release Memory)


1: Clarify concept again: Dispose NOT equals Release memory, Finalize NOT equals memory either, there is not a Right Away way to release memory in C#, and actually we DO Not need to concern it because GC is there;

2: ONLY GC can release your memory in C# ; (sure you still can use C++ code to release memory right away)

3: GC is always there, it will NOT effect your application time because it tries to avoid your application time, ONLY it found it has to release memory, or when it found system resource is not enough, or other conditions due to GC’s mechanism;

4: When you use “new” to alloc a local object in a method, when this method end, the memory of the object will be set to wait to be garbage collect, but maybe a good coding habit is setting this object = null or you can load dispose it, actually due to 1., you can not release the memory at once;

About more detail GC, you guys can search on Google, Here is a article from Microsoft below:

“Unexpected Error 0x8ffe2740 Occurred” Error When Start IIS

When you start IIS 5.1 on Windows XP Pro,  you may receive the following error message:

“Unexpected Error 0x8ffe2740 Occurred”

The reason :

The most possible reason is if a port conflict exists on the system. By default, IIS uses port 80 for HTTP communication. If an application other than IIS or other Web Server such as Apache is running and is using port 80 on the same IP address.


To resolve this problem, you can do either of the following:

    * In IIS Manager, change the port bindings for the Web site to a port other than port 80.
    * Stop the application that is using port 80, and then start the Web site from IIS Manager.

(from Microsoft Support)

How to view your ports:

If you want to identify the other application that is using port 80, You can use third-party tools like TCPView (download from Microsoft site) or FPort

Remote connect to SQL Server 2005 Express or SQL Server 2005

Microsoft SQL Server 2005 or Microsoft SQL Server 2005 Express do not allow remote access by default. If you want to remote connect or use another computer in your LAN, you have to configure on your SQL Server 2005 or SQL Server 2005 Express.

In this article, we will use SQL Server 2005 Express as the sample database.

If you don’t set something for remote connection, you may receive an error message. The following error message is a sampe:

Sqlcmd: Error: Microsoft SQL Native Client: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.

Enable remote connections for SQL Server 2005 Express or SQL Server 2005 Developer Edition

First, I suggest that you use SQL SQL Server Authentication connection but not Windows Authentication connection (you still can) for your SQL Server Database connection. If you use Windows authentication, you should have identical accounts on both server PC and remote PC (username and password are the same), This is not good for remote database connection. Don’t you think so ?

To enable remote connections on the instance of SQL Server 2005 Express, please read the following steps:

   1. Find your Microsoft SQL Server 2005 program on the Start menu in your Windows XP or related OS, point to Configuration Tools, and then you will see the menu item SQL Server Surface Area Configuration (please see below):

   2. Click SQL Server Surface Area Configuration, then click Surface Area Configuration for Services and Connections.

   3. On the new page: Surface Area Configuration for Services and Connections page,select the database which you want to set for remote connection, in our case, we have installed 2 SQL Server Express databases, we select SQLEXPRESS2005 database, then expand Database Engine, click Remote Connections, check on the Local and remote connections radio button, then select the appropriate protocol to enable for your environment, and then click Apply.

   4. Please Click OK if you receive the following message:

   5. Return to the Surface Area Configuration for Services and Connections page, expand Database Engine, select Service, On the right side, click Stop button, then wait until the MSSQLSERVER (MSSQL$SQLEXPRESS2005) service stops, and then click Start button to restart the MSSQLSERVER (MSSQL$SQLEXPRESS2005) service.

(part of above text were from Microsoft website)

Other instruction info:


The first thing that can block a connection to SQL Server is a firewall. If you have any firewalls, make sure they are configured to allow connections to SQL Server. The default TCP port that SQL Server uses is 1433. Firewalls include McAfee, Norton, Windows Firewall which ships with Windows XP SP2, and Internet Connection Firewall (ICF) which ships with Windows 2000.

(Above text copied from here Teratrax site, more info please click to visit )