Skip to content

Flurl

August 12, 2016
tags:

In case you haven’t check out flurl, you should ;). It’s a great way to create web clients / url’s.

Here’s an example that uses the Blizzard API for world of warcraft.


string url = "https://eu.api.battle.net/";

var wowResponse = await url
.AppendPathSegments("wow", "character", "Aggramar", "Morphea")
.SetQueryParam("fields", "hunterPets")
.SetQueryParam("locale", "en_GB")
.SetQueryParam("apikey", "APIKEY")
.GetAsync();

var content = await wowResponse.Content.ReadAsStringAsync();

clsHunter hunterInfo = JsonConvert.DeserializeObject(content);

if (hunterInfo.hunterPets != null)
{
foreach (var item in hunterInfo.hunterPets)
{
Console.WriteLine("Pet name : " + item.name);
}
}

Looks great doesn’t it ? ;).

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

Asp.net MVC 2.0 around the corner

February 12, 2010

When you’re reading this article, the fact that Asp.net mvc 2.0 will be released soon won’t come as a surprise. Both Phil Haack and Scott Guthrie amongst others have been blogging about it. I started a new web project recently and was doing the input validation using Xval by Steve Sanderson. I made a leap of faith and upgraded the project to MVC 2.0 because xval had some quirks (or actually the jquery validation plugin did). Luckily those were fixed by MVC’s new build in validation system. The Gu has an excellent post on the subject. I am using the microsoft validation scripts for the client side, and they work very well, even taking culture settings into consideration out of the box.

There is a lot more to MVC 2.0, the templates are nicer. The Html.TextBoxFor(p => p.Id) is very handy, and make the input forms a lot easier to write. The ModelBinding seem to be much better now as well. With 1.0 I sometimes had to some of it by hand, as the binder didn’t grasp what it was supposed to bind. I haven’t run into that in 2.0.

mvc

The attributes for Actions / methods in your controller have been streamlined as well. You only need to put [HttpPost] over actions for Form Posts for example. One thing I haven’t used yet but might come in handy on a big project some day might be the Areas. OdeToCode has a nice article on this new feature.

Over at TekPub, Steve Sanderson and Rob Conery are doing an excellent series on MVC and are also going into the new things of 2.0. If you can spare $28,- I highly recommend watching it.

jqGrid Package

August 8, 2009
tags: ,

A complete package is now available at http://www.jqgrid.com. This was mentioned in a comment on my post about jqgrid, but I thought it was worth a mention here :).

Enjoy !