Skip to content

Testing WebApi 2 Controllers

April 2, 2014

My most recent project is to create a WebApi for a database. I have been using Asp.net WebApi 2, to create it, and at first it was pretty simple, but I wanted to do some more complicated things and then I ran into a lot of reading and googling (as usual). I have now setup tests for my Web Services using the httpSelfHostServer. This is what is in every controller test class:

      private static System.Uri GetBaseAddress()
        {
            var baseAddress = new Uri("http://localhost:8765");
            return baseAddress;
        }

        private HttpSelfHostServer getServer()
        {
            // Load the controller's DLL (bit of a trick needed to get the server working)
            Type tableControllerType = typeof(TableApi.Controllers.TableController);

            System.Uri baseAddress = GetBaseAddress();
            var config = new HttpSelfHostConfiguration(baseAddress);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "Api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // permission required to use the port
            // netsh http add urlacl url=http://+:8765/ user=machine\username
            return new HttpSelfHostServer(config);
        }

Then you can use the server like this in your test itself :

[TestMethod]
public void SectionsKassaNrReturnsElements()
{
     using (HttpSelfHostServer server = getServer())
     {
	server.OpenAsync().Wait();
	HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
		"http://localhost:8765/Api/Table/?kassanr=1");
	request.Headers.Add("X-ApiKey", "123456");
	using (var client = new HttpClient(server))
	{
        	client.BaseAddress = GetBaseAddress();
		var response = client.SendAsync(request).Result;
		response.EnsureSuccessStatusCode();
		var list =
                  response.Content.ReadAsAsync<IEnumerable<modelSection>>().Result;

		Assert.AreEqual(list.Count(),2,"Actual count : " + list.Count());
	}
     }
}

As you can see I am using an ApiKey header for identification. I have seperate tests for that. If you’d really want to do it according to the rules, you’d need a setting up the database routine as well in your testing class !

Link:

SelfHosted example at asp.net

 

Searching Twitter Using Csharp

August 17, 2012

Somehow through a tweet I ran into WebEssentials 2012 and decided to try it out in my spanking new Visual Studio 2012. It works very nice, but what caught my attention was the Paste Special -> Paste Json as classes. As I wanted to try this I checked out the Twitter search api, which you can ask to return Json results. The Web essentials plugin did indeed work and it came up with this, though I slightly edited it as I didn’t want to use nested classes.

public class Metadata
    {
        public string result_type { get; set; }
    }

    public class Result
    {
        public string created_at { get; set; }
        public string from_user { get; set; }
        public int from_user_id { get; set; }
        public string from_user_id_str { get; set; }
        public string from_user_name { get; set; }
        public object geo { get; set; }
        public object id { get; set; }
        public string id_str { get; set; }
        public string iso_language_code { get; set; }
        public Metadata metadata { get; set; }
        public string profile_image_url { get; set; }
        public string profile_image_url_https { get; set; }
        public string source { get; set; }
        public string text { get; set; }
        public object to_user { get; set; }
        public int to_user_id { get; set; }
        public string to_user_id_str { get; set; }
        public object to_user_name { get; set; }
    }

    public class TwitterResponse
    {
        public double completed_in { get; set; }
        public long max_id { get; set; }
        public string max_id_str { get; set; }
        public string next_page { get; set; }
        public int page { get; set; }
        public string query { get; set; }
        public string refresh_url { get; set; }
        public Result[] results { get; set; }
        public int results_per_page { get; set; }
        public int since_id { get; set; }
        public string since_id_str { get; set; }
    }

Using restsharp I simply make a call to twitter and then parse the result through
Newtonsoft.Json‘s excellent json library. This is a simple Asp.net MVC website. Here is the Controller.

public ActionResult getTweets()
{
//
// retrieve last 10 tweets in #tweetfleet, this is the URL we want
//
string url = "http://search.twitter.com/search.json?q=%23tweetfleet&page=1&rpp=10";

var client = new RestClient("http://search.twitter.com/");
var req = new RestRequest(Method.GET);
req.Resource = "search.json";
req.AddParameter("q", "#tweetfleet");
req.AddParameter("page", 1);
req.AddParameter("rpp", 10);

var response = client.Execute(req);

JsonSerializer serializer = new JsonSerializer();
TwitterResponse tweets = (TwitterResponse)serializer.Deserialize(new JsonTextReader(new StringReader(response.Content)), typeof(TwitterResponse));

return View(tweets);
}

And this is the View:

@model myMvc.Models.TwitterResponse

@{
ViewBag.Title = "getTweets";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Latest Tweets in #tweetfleet</h2>

<p>
<ul>
@foreach (var item in Model.results)
{
<li>@item.from_user says @item.text</li>
}
</ul>
</p>

Needless to say the view could be much more fancy, but it’ll do for this example ! It results in something like this.

All in all pretty easy once you find out how to glue the various pieces together :).

Twitter Bootstrap

July 25, 2012

For a new small sideproject that didn’t have any ties to any other project, I used Twitter Bootstrap. And I must say I liked it a lot. The css part of the framework is very handy. You can easily place elements of your site, tables are nicely formatted. Everything looks quite snappy and hip ;).

So if you have a little side project and you’re able to test something new, I’d say give twitter bootstrap a try !

DataTables jQuery Plugin

April 22, 2012

Sometimes you come across a plugin and you wonder why you didn’t find it before ! One of those I found recently is jQuery.DataTables. With very minimal effort you can add searching, paging and theming to your datatables. You can enable jQuery-ui theming very easily so your tables look like the rest of your site ;).

Only drawback so far, I found is that it gives very vague errors in case your table isn’t formatted the way it should be (like forgetting thead tags). So study the examples carefully, in case you get an odd error at first.

Data Table

Backup files with Powershell

April 19, 2012

Finally I found some good use for Powershell. I was always intrigued by Powershell when I read about it on Hanselman’s blog, but so far never really found a good use for it. But now that I am managing a webserver on which ascii files are stored regularly (complicated story¬† ;)), I needed some easy way to backup these files once they’re older than say 30 days. Things start clugging up fast !

So here it is, my first powershell script, it uses 7zip to put the files into an archive and subsequently removes them. Probably could see some improvement, but it’s working fine as it is now.

$ftp_root = "D:\Data\Ftp"
[string]$zipexe = "C:\7Zip\7z.exe"
$date = Get-Date 
$DateStr = '{0:yyyyMMdd}' -f $date

#start-transcript $(%{'d:\logs\archivelog_{0}.txt' -f $DateStr})
Write-Host "Archive script Datum : " $DateStr

foreach ($dir in (Get-ChildItem $ftp_root -Recurse | where {$_.PsIsContainer})) {
	 
	 foreach($file in ($dir.GetFiles("P*.*") | where-object {$_.LastWriteTime -lt (get-date).AddDays(-30) } )) {	 

	Write-Host "Executing : $zipexe a -t7z " $(%{'{0}\{1} {2}' -f $dir.FullName, "archive.7z", $file.FullName})
        
	& $zipexe a -t7z $($dir.FullName + "\archive_" + $DateStr + ".7z") $file.FullName
        remove-item $file.FullName -force -whatif   
	 } 	 
	 
	 foreach($file in ($dir.GetFiles("J*.*") | where-object {$_.LastWriteTime -lt (get-date).AddDays(-30) } )) {	 
		& C:\7Zip\7z.exe a -t7z $($dir.FullName + "\archive_" + $DateStr + ".7z") $file.FullName
	 } 	 	 
}

Haack Looks Back

December 28, 2011

Nice article on the Haacked’s blog (former MS employee !) on .net in 2011.

http://haacked.com/archive/2011/12/26/oss-net-2011.aspx

He missed a few obvious things, but the post has been edited since :).

Mix 2011

April 13, 2011
tags: ,

A lot of announcements and new stuff released at Mix 2011 !

Haacked.com has more news and of course Scott Hanselman has more info as well.

The new tools will include modernizr to help asp.net mvc developer step into the age of css3.0 and html5.

My favourite videos: http://tinyurl.com/mvcfavs

Follow

Get every new post delivered to your Inbox.