Archive for the ‘code’ Category.

.Net Core 1.1 – WebApi Integration testing

Things have changed a bit since the DNX .Net WebApi Integration testing post that I wrote about a year ago. This post will show updated code for .Net Core 1.1, I’m using the TestHost library as before.

I’m using these Nuget packages
xunit 2.3.0-beta1-build3642
Microsoft.AspNet.TestHost 1.1.1

Here is the UnitTest itself

using System;
using System.Diagnostics;
using System.Net.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Hosting;
using Xunit;
using DevOps.Notes.Core.Util;

namespace DevOps.Notes.Web.Spec
{
  public class ValuseControllerTest
  {
    [Fact]
    public async void PingTheServerRepeat()
    {
      // Setup client & server
      TestServer server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
      HttpClient client = server.CreateClient();
      // Make a request and check response
      var getResponse = await client.GetAsync(“api/values/”);
      var response = await getResponse.Content.ReadAsStringAsync();
      TraceLog.Log(“web api, response=” + response);

      // Hit the webapi, repeatedly
      Stopwatch watch = Stopwatch.StartNew();
      for (int i = 0; i < Util.Repeat; i++)
      {
        getResponse = await client.GetAsync(“/api/values/”+i);
        response = await getResponse.Content.ReadAsStringAsync();
      }
      watch.Stop();
      TraceLog.Log($“WepApi, round trips ={Util.Repeat}, Execution time, millisec={watch.ElapsedMilliseconds}, average roundtrip=” + ((double)watch.ElapsedMilliseconds / Util.Repeat));
      TraceLog.Log(“web api, response=” + response);

      // Done, release resources
      server.Dispose();
      client.Dispose();

    }

  }
}

DNX .Net WebApi Integration testing

I needed to compare some gRPC round trip numbers to plain .Net WebApi. So the question became how to test WepApi round trips from UnitTest harness.

It’s actually pretty simple if you are using the newer DNX libraries. I’m using the TestHost library to get things done.

From project.json

“System.Net.Http”: “4.0.1-beta-23516”,
“Microsoft.AspNet.TestHost”: “1.0.0-rc1-final”,

The UnitTest itself

[Fact]
    public async void PingTheServerRepeat()
    {
      // Setup client & server
      TestServer server = new TestServer(TestServer.CreateBuilder().UseStartup<Startup>());
      HttpClient client = server.CreateClient();

      // Make a request and check response
      var getResponse = await client.GetAsync(“/api/values/5”);
      var response = await getResponse.Content.ReadAsStringAsync();
      Logger.Log(“web api, response=” + response);

      // Hit the webapi, repeatedly
      Stopwatch watch = Stopwatch.StartNew();
      for (int i = 0; i < Util.Repeat; i++)
      {
        getResponse = await client.GetAsync(“/api/values/” + i);
        response = await getResponse.Content.ReadAsStringAsync();
      }
      watch.Stop();
      Logger.Log($“WepApi, round trips={Util.Repeat}, Execution time, millisec={watch.ElapsedMilliseconds}, average roundtrip=” + ((double)watch.ElapsedMilliseconds / Util.Repeat));
      Logger.Log(“web api, response=” + response);

      // Done, release resources
      server.Dispose();
      client.Dispose();
    }

Log4Net configuration and scope extension

I had the need to setup Log4Net logging in a new project the other day. It is fairly easy to setup, just add the listeners you want in the configuration files. Then use it, of course you get most things for free the log level etc. We also wanted to make it super easy to use Scope, so I added a LogExtension that takes care of that. The idea is if you forget to close the scope it will be automatically done once the scope object gets garbage collected. Below is example code including UnitTests.

logger_sample

Fireflies

I had an idea about writing a small code to animate fireflies. On Christmas break I was bored and I figured I had a few hours to play with it. I also wanted to use some tools I hadn’t used yet and figured that was a good time to do Javascript since I haven’t done much Javascript. I fired up the editor ( Sublime ) and used the browser to run / debug, Firefox and FireBug of course. There is a bit of a difference using this setup compared to writing Java code in Eclipse which I’m used to. First off you don’t get the compilation in Sublime and secondly you have to switch to another program to load and debug. Switching between the two was what annoyed me. Later I though, what if I can find a tool that is an editor and can Ftp to a server as well and runs within the browser. If on each save you can Ftp it to a sever that is serving the Javascript then I could do it all from the browser. I went looking around and fount Net2Ftp which is supposed to at least come close to the tool I’m wishing for. I will have to try it out the next time I’m coding in Javascript. The other thing that got me is that there is no good way of declaring your own classes, you have to work with prototypes and such, why that is beats me.

As you can see from the code, it’s not pretty.

If you want to see the Javascript in action click here.

fireflies

iPhone sample code

I figured I would try out developing on Mac Os making an iPhone app. My first experience on the Hackintosh building an application ( my first blog post from it as well ). Anyway, I downloaded the SDK got xCode going and followed some Hello world tutorial. I feel Hello world is just too simple to get a feel for the environment and Objective-C. So I decided to port my HandiCap Android sample to the iPhone, should give me enough time to play with xCode and get a feel for it.

As I started up xCode and started coding first I noticed was the keyboard shortcuts which are strange when using PC keyboard on the Mac, I run the Mac in a VM. I understand I can map that anyway I want so that shouldn’t be a problem if I decide to do some more development. As I knew this sample was going to be short I didn’t bother changing it. When using xCode it doesn’t really feel like an IDE rather a collection of different tools. I had a hard time finding out how to set controls on a view in the beginning once I got the appropriate tools open it was pretty much straight forward. One thing that I don’t really understand is when you link controls to the File owner, why does that link your controls to your code view ? why not link that to the view itself as that is where the code resides ? I guess I will figure that out later as time goes on.

So let’s take a look at the code, first you need to reference the controls in the header file that you already setup in the Interface builder. Yes you need to do that by hand, it is not taken care of by the IDE, more integration is needed on the IDE’s behalf if you ask me. Note the UITextFieldDelegate tag on the controller, this one is needed to hide the keyboard when Return is pressed along with code in the class file.

#import <UIKit/UIKit.h>

@interface HandiCapViewController : UIViewController <UITextFieldDelegate>
{
       
        // First half
        IBOutlet UILabel *lbPlayer1;
        IBOutlet UITextField *txPlayer1;       
        IBOutlet UILabel *lbPlayer2;
        IBOutlet UITextField *txPlayer2;
       
        // Second half
        IBOutlet UILabel *lbWinPlayer1;
        IBOutlet UITextField *txWinPlayer1;
        IBOutlet UILabel *lbWinPlayer2;
        IBOutlet UITextField *txWinPlayer2;
}

(IBAction) btCalculate_Clicked:(id)sender;

@end

Then we start coding in the class ( .m ) file

#import "HandiCapViewController.h"
#include <tgmath.h>

@implementation HandiCapViewController

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
(void)viewDidLoad
{
    [super viewDidLoad];
       
        // Disable the two result fields
        txWinPlayer1.userInteractionEnabled = FALSE;
        txWinPlayer2.userInteractionEnabled = FALSE;
}

(void)didReceiveMemoryWarning {
        // Releases the view if it doesn’t have a superview.
    [super didReceiveMemoryWarning];
       
        // Release any cached data, images, etc that aren’t in use.
}

(void)viewDidUnload {
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
}

// Shut down the keyboard
(BOOL)textFieldShouldReturn:(UITextField *)textField
{
        NSLog( @“textFieldShouldReturn start”);
       
        // This code should be made dynamic instead of ugly if / else
        if( textField == txPlayer1 )
        {
                [txPlayer1 resignFirstResponder];
        }
        else if( textField == txPlayer2 )
        {
        [txPlayer2 resignFirstResponder];
        }

        return TRUE;
}

               
// Calculates handicap
(void) calculate:( double *) pdaPlayers;
{
        // STRONGER is lower handicap
        // See who is better rated coming in,
        Boolean bStrongerFirst =  pdaPlayers[0] < pdaPlayers[1];
        // Holds results
        double strong_race, weak_race;
       
        if( bStrongerFirst )
        {
                // What’s the race
                weak_race = MAX(2, 6floor( pdaPlayers[1] ));
                strong_race = weak_race + round( pdaPlayers[1] – pdaPlayers[0] );
                // set the slots before returning
                pdaPlayers[0] = strong_race;
                pdaPlayers[1] = weak_race;
        }
        else
        {
                // What’s the race
                weak_race = MAX(2, 6floor( pdaPlayers[0] ));
                strong_race = weak_race + round( pdaPlayers[0] – pdaPlayers[1] );
                //  Set the slots before returning
                pdaPlayers[0] = weak_race;
                pdaPlayers[1] = strong_race;
        }
}

(IBAction) btCalculate_Clicked:(id)sender
{
        NSLog( @“Button clicked start”);
       
        double dPlayerOne = [txPlayer1.text doubleValue];
        double dPlayerTwo = [txPlayer2.text doubleValue];

        // What is the race
        double players[2] = { dPlayerOne, dPlayerTwo };

        // call the function to calculate
        [ self calculate: players ];

        // Display it
        txWinPlayer1.text = [NSString stringWithFormat:@“%.0f”, players[0]];
        txWinPlayer2.text = [NSString stringWithFormat:@“%.0f”, players[1]];

        NSLog( @“Button clicked end”);
}

(void)dealloc
{
        // First half
        [lbPlayer1 release];
        [txPlayer1 release];
        [lbPlayer2 release];
        [txPlayer2 release];
       
        // Second half
        [lbWinPlayer1 release];
        [txWinPlayer1 release];
        [lbWinPlayer2 release];
        [txWinPlayer2 release];
   
        [super dealloc];
}

@end



I disabled the two result fields in code in the viewDidLoad function as it did not work to set Accessibility Enabled = false from the Interface builder, I don’t know why.
The textFieldShouldReturn function implements the functionality that goes with UITextFieldDelegate in the header file. Simply when the user is done with input in the two text fields he can hit return on the keyboard and the keyboard gets hidden again.
The calculate function is a straight port from the Android code, I only had to include tgmath.h and use the math functions from there.
The btCalculate_Clicked is where all the functionality happens, simply convert the text input from string to double then call calculate and display in the result fields. There is no error checking on the input as I was feeling lazy.
I’m using NSLog to log out to the console, if you want to create a program for production you should maybe write your own logging or use third party library to be able to control the logging level both debug and runtime.
Lastly we have dealloc function where we release the resources the code has been referencing. As pointed out by my friend Mick they are introducing automatic dellocations by the compiler called ARC ( Automatic Reference Counting ) in the near future. That should be welcomed by objective-c developers as they don’t have to keep track of and releasing resources, fewer bugs and more productivity. Some changes discussed on Stack Overflow This experience reminded me of other c / c++ coding with a twist I find the [ class function:param ] syntax strange, but I’m sure I can get used to that.


Below is the app in action and here is the code if anybody is interested HandiCap xCode project

Sign align and release Android application

In order to release your app in the Android market place you need to digitally sign it. The instructions are here. But in short I will show you what you need from the command line, you won’t have to read all the instructions. First off make your app .apk name something different then what your going to use in the end. As the process requires the input and output to have different file names.

Lets take a look, this example is from DOS command line

Create the signature key
C:\Temp> keytool -genkey -v -keystore c:\temp\release-key.keystore -alias MyAlias -keyalg RSA -keysize 2048 -validity 10000

Sign using the key
C:\Temp> jarsigner -verbose -keystore release-key.keystore release.MyApp.apk MyAlias

Verify that it took
C:\Temp> jarsigner -verify -verbose release.MyApp.apk

Run the align tool as recommended
C:\Temp> zipalign -v 4 release.MyApp.apk MyApp.apk

And your all done, now publish it and start watching the downloads.