Recent Updates Toggle Comment Threads | Keyboard Shortcuts

  • danielsaidi 8:52 am on May 26, 2016 Permalink | Reply
    Tags: dotnet test, dotnet watch, , portable-net45+win8, , xunit   

    .Net Core Note to Self 

    I have been playing around with .NET Core since the betas, and every new version fucks up my development environment, with different versions conflicting, old versions not being unlinked etc. I wrote a blog post a bout this a while back, but since then, much have changed.

    This blog post is just a quick brain dump of what I did when bumping my environment up to RC2 Preview 1, and what I should try if I ever encounter problems again.

    First, some useful links:

    Keep the following in mind:

    • Make sure dnx and dnvm are completely removed
    • Remove any previous .NET Core versions, using the scripts Microsoft provides
    • Ensure that the dnx, dnvm, and dotnet ommands do nothing when running them in the terminal
    • Install the latest .NET Core release
    • Install the latest Visual Studio Code release
    • Make sure to also install the C# plugin for Visual Studio Code (cmd+p then search for c#)

    Remember:

    • C# is a plugin to Visual Studio Code…no (good) intellisense without it!

    The fact that C# is a plugin to Visual Studio Code always escapes my mind, causing me to have a full .NET Core environment, but no intellisense. This is also, at the time of writing, nowhere to be found in the getting started guides (correct me if I’m wrong).

    Unit Tests

    To setup your project to use XUnit as a test runner, add these dependencies:

    • "xunit": "2.1.0"
    • "dotnet-test-xunit": "1.0.0-rc2-build10015"

    Add XUnit as a test runner by adding this below the dependencies node:

    • "testRunner": "xunit"

    Then, finally add the following import for netcoreapp1.0:

    • "portable-net45+win8"

    Now, you should be able to run unit tests with dotnet test.

    Watch

    If you do not want to run the dotnet run or dotnet test commands everytime you make a code change, you can add the DotNet Watcher to your project.

    To add it, add a new tools node, or add the watcher tool to the tools node if you already have it:

    "tools": {
       "Microsoft.DotNet.Watcher.Tools": {
          "version": "1.0.0-*",
          "imports": "portable-net451+win8"
       }
    }
    

    You should now be able to rundotnet watch run and dotnet watch test to automatically rerun as soon as any code in your project changes.

     

     

     

     
  • danielsaidi 1:04 pm on May 12, 2016 Permalink | Reply
    Tags: angular, angular-2, , ionic-2, typescript   

    Ionic 2 – Build configuration-specific application settings 

    In my new Ionic 2 app for iOS and Android, I want to use different application settings depending on my current build configuration.

    For instance, I want to use different external services during development compared to when building for releas, disable Google Analytics during development, disable logging during release etc.

    Before I begin, I happily confess that I have not yet plowed through the overwhelming amount of information that is out there for Ionic 1, Ionic 2, ES6, TypeScript, Angular 1, Angular 2 etc. If a better approach exist, please do share it in the comment section below.

    Also, note that I use TypeScript in this project.

    Step 1 – Create application settings classes

    I want to be able to have some settings that are shared between build configurations, and only override a few of them when switching build configuration.

    As such, I have a base class that defines most settings:

    app/config/app-settings-base:

    export class AppSettingsBase {
      public apiUrl: string;
      public rssFeedUrl: string;
    
      constructor() {
         this.apiUrl = '';
         this.rssFeedUrl = 'http://rssdomain.com/rss.xml';
      }
    }
    

    This base class defines an rss feed url, but leaves the api url blank. This means that a build configuration-specific setting does not have to (but can) define a value for the rss, but must do so for the api url.

    Note that this class is not injectable. This means that it cannot be injected into different components in the app. For that, we will use build configuration-specific settings classes.

    Let’s start off with the settings class that I will use while developing.

    app/config/app-settings-debug:

    import {Injectable} from "angular2/core";
    import {AppSettingsBase} from "../config/app-settings-base";
    
    @Injectable()
    export class AppSettings extends AppSettingsBase {
      constructor() {
        super();
        this.apiUrl = 'Debug API';
      }
    }
    

    This file contains an AppSettings class that inherits AppSettingsBase, then sets a debug-specific value for the apiUrl property.

    This class is injectable, which means that we can use it in our app.

    Now, let’s add a second settings class, that will be used when building the app for release.

    app/config/app-settings-release:

    import {Injectable} from "angular2/core";
    import {AppSettingsBase} from "../config/app-settings-base";
    
    @Injectable()
    export class AppSettings extends AppSettingsBase {
      constructor() {
        super();
        this.apiUrl = 'Release API';
      }
    }
    

    This file also contains an injectable AppSettings class that inherits AppSettingsBase (you will only use one though), then sets a release-specific value for the apiUrl property.

    Step 2 – Make gulp apply the correct settings class

    We will now let gulp apply the correct settings file when serving and building the app.

    First, add “gulp-rename” : “1.2.2” (or later) to your package.json. Then, require the file topmost in your gulpfile.js:

    rename = require('gulp-rename'),
    

    After that, add the following build task to gulpfile.js:

    gulp.task('copy-settings', function () {
      var settingsFileSuffix = isRelease ? 'release' : 'debug';
      var pathPrefix = 'app/config/app-settings-';
      return gulp
        .src(pathPrefix + settingsFileSuffix + '.ts')
        .pipe(rename('app-settings.ts'))
        .pipe(gulp.dest('app/config/'));
    });
    

    Finally, refer to this task in serve:before and build:

    gulp.task('serve:before', ['watch', 'copy-settings']);
    
    gulp.task('build', ['clean', 'copy-settings'], function(done) {
    

    If you now run ionic serve or ionic build, gulp will copy app/config/app-settings-debug.ts to app/config/app-settings.ts. If you add –release to the command, it will use app/config/app-settings.ts instead.

    You could easily extend this functionality to support a more build configurations, but for now this will do.

    Step 3 – Use the resulting settings class

    We now have a configuration-specific file that is created every time we build or serve the app. Since it is auto-created, you should probably add app/config/app-settings.ts to your .gitignore file, if you have one.

    You can now use the resulting settings class as normal. For instance, to verify that the correct settings file is applied, add the following to your app.ts file:

    import {AppSettings} from './config/app-settings';
    
    ...
    
    @App({
      ...
      providers: [PodcastService, AppSettings]
    })
      export class MyApp {
        ...
        constructor(platform: Platform, settings: AppSettings) {
           console.log(settings.apiUrl);
           ...
      }
    }
    
    

     

     

     
  • danielsaidi 9:31 am on April 20, 2016 Permalink | Reply
    Tags: , , , omnisharp,   

    Upgrade .NET Core RC to 1.0 

    With the release of Visual Studio Code 1.0, I decided to upgrade all old .NET Core software I had installed to the latest version. However, the older versions were not properly replaced, which caused Visual Studio Code and Omnisharp to behave quite strange.

    After installing .NET Core 1.0 from here, and upgrading to Visual Studio Code from this page, I created a new .NET Core project with these lines:

    mkdir hwapp
    cd hwapp
    dotnet new
    dotnet restore
    dotnet run
    

    The project ran without problems, but when I opened it in Visual Studio Code, I received warnings that the project could not load, the project missed an .sln file, Omnisharp could not find the “default” runtime etc.

    Turns out that older versions of dnx and dnvm conflict with the new setup. Upgrading dnvm, removing old versions and reinstalling the latest, did not work alone. I also had to specify an alias:

    dnvm update-self
    dnvm list -detailed
    dnvm uninstall VERSION -r coreclr
    dnvm uninstall VERSION -r mono
    dnvm install latest -r coreclr -alias default
    dnvm install latest -r mono -alias default
    

    After doing this, I could restart Visual Studio Code, with Omnisharp running without any problems.

     
  • danielsaidi 9:39 pm on December 17, 2015 Permalink | Reply
    Tags: asp.net 5, , , dnx-watch   

    Autorun dnx on file changes 

    When developing a console app in ASP.NET 5 on my Mac, I find it tedious to write some code, then having to leave Visual Studio Code to run dnx run from the terminal to verify that my code compiles, then dnx test to see if my tests pass.

    Luckily, you can grab a tool called dnx-watch, that will re-run as soon as a file in your project changes.

    To install dnx-watch, make sure that you have updated your computer with the latest versions, using dnvm, then install dnx-watch with this command:

    dnu commands install Microsoft.Dnx.Watcher 1.0.0

    In my console app, I have a console app project and a test project. Since the test project runs code from the console app project, I just have to run dnx-watch test in the test project’s root folder. dnx-watch will then fire as soon as I change a file in either the app or test project.

    I can then code away in Visual Studio Code, just to see my tests re-run each time I save a file in either project.

     

     
  • danielsaidi 9:48 am on December 17, 2015 Permalink | Reply
    Tags: dnu, , , osx   

    Setup DNX on Mac OS X 

    After so much waiting, “I’ll do this first”, app coding etc. etc. (yep, I blame my family as well), I have finally begun playing around with DNX and ASP.NET 5.

    For those of you who do not know the story, ASP.NET 5 will change everything…ish. You can create your web applications, web api:s and console apps on OS X and Linux, and run it everywhere. Nice, right?

    Before I begin, I’ll just mention some terms that I’ll use in this post.

    dnx stands for .NET Execution Environment. It’s a console application that you get access to when installing ASP.NET 5 on your Mac. You use it to start your web sites, run your console apps etc.

    dnvm stands for .NET Version Manager.

    dnu stands for DNX Utility. It’s a console application that you can use to install dependencies for your projects, much like npm.

    I believe that this guide would work for Linux as well, but since I haven’t tried it, I won’t swear by it.

    Step 1 – Install Mono

    To get started with DNX, first go and grab Mono for your OS:

    http://www.mono-project.com/download/

    On this page, can download a convenient installer that sets everything up for you. Nice for those of you who like me, do not favor installing a bunch of bytes and having to build your own makefile.

    Step 2 – Install Visual Studio Code

    Visual Studio Code is an open source IDE (well, not quite yet), or rather a simple text editor that can be used to develop.NET projects. It was built with plugins in mind, however, so expect an explosion of functionality in the months to come.

    You do not have to use Visual Studio Code when developing ASP.NET 5 stuff – you can use your editor of choice, like Sublime or Atom. However, I think that you should at least have a look at Visual Studio Code, to get your thumb on the pulse of the work carried out by the .NET 5 community.

    Visual Studio Code can be downloaded as a convenient install bundle:

    https://go.microsoft.com/fwlink/?LinkID=534106

    If you are used to the full feathered Visual Studio experience, you’ll notice that Visual Studio Code is insanely stripped. You cannot even create new projects or solutions from it. To do that, you need to setup ASP.NET 5.

    Step 3 – Install ASP.NET 5

    To install ASP.NET 5, download and install this file (but first check if an update is available, which probably is the case since so much is happening all the time):

    https://go.microsoft.com/fwlink/?LinkId=703940

    Once you have installed ASP.NET 5, you have to set it up. Brace yourself – you will no longer rest in the comforting arms of install bundles. The rest of the setup will take place in the terminal.

    Open up the terminal, then type dnx. As you’ll notice, the command will not be recognized. So, just run the following command:

    source /Users/<your user name>/.dnx/dnvm/dnvm.sh

    This will setup ASP.NET 5 and make it possible to run dnx and dnu from any folder. If you run the dnx command again, it will be recognized (although if naturally will warn you that you use it incorrectly).

    Step 4 – (Optional) Install Yeoman

    If you want to hack away in ASP.NET 5, you have all the tools you need now (and an optional Visual Studio Code). However, to simplify things even more, you can use Yeoman as a project generator, to avoid having to setup each project from scratch.

    To install Yeoman and the ASP.NET project generator plugin, run these two commands in the terminal:

    npm install -g yo
    npm install -g generator-aspnet
    Once installed, you can now create ASP.NET projects with Yeoman, using this command from any folder:
    yo aspnet
    This will open a wizard that lets you choose from a selection of different project types. Once you have selected a project, Yeoman will generate it in a sub folder with the same name as your project.

    Step 5 – Run your project

    This post will not cover the project structure of ASP.NET 5 projects, but to sum it up, there are no solution files, project files are now small, pretty json files and project files hold no references to the files in the project. It’s a beautiful thing.
    Once you have a project, cd into the project folder, then run dnu restore to restore all dependencies (like npm install).
    Once all dependencies are restores, you can run your project. Depending on what kind of project you have, you run it in different ways:
    • Console app – dnx run
    • Web app – dnx web
    • Web API – dnx web
    • Test project – dnx test

    Although you can run dnx build to build your project prior to running it, there is no need since the run commands builds the project as well.

    That’s a wrap

    That’s about it. In a future post, I’ll cover how to setup a code project with a test project connected to it.

     

     

     
  • danielsaidi 11:04 pm on September 17, 2015 Permalink | Reply
    Tags: , mkmapannotation, mkmapannotationview, ,   

    Update the title of an MKAnnotation 

    Simulator Screen Shot 18 sep 2015 00.04.54

    In an app of mine, I have a map where users can save personal content and present it in a beauuuutiful way. Ok, enough with the sales pitch, let’s move on to the problem.

    When the user taps an annotation, the app reverse geocodes the annotation’s coordinate and uses it to display the full annotation address as a subtitle in the callout.

    Sadly, this has worked semi-well. If the reverse geocoding operation takes too long, so that the app has already opened up and shown the callout, the subtitle is not changed.

    Turns out that you have to add some more code to make this work. Instead of just setting the subtitle, you actually have to tell the app that you will change it, then change it, then finally tell the app that you have changed it.

    The code for this becomes:

    myAnnotation.willChangeValueForKey("subtitle")
    myAnnotation.subtitle = "An address somewhere in the world"
    myAnnotation.didChangeValueForKey("subtitle")
    

    Yeah, I really don’t know why this has to be, but as soon as I added the extra code, the reverse geocoder could update the subtitle without problems, even when the operation took some time.

    Since all my annotations inherit a custom-made class called MapAnnotation, I decided to specify the subtitle property as such:

    var subtitle: String? {
       willSet { willChangeValueForKey("subtitle") }
       didSet { didChangeValueForKey("subtitle") }
    }
    

    This means the required events are fired in the correct order, every time the subtitle is set.

     

     

     
  • danielsaidi 9:45 am on September 11, 2015 Permalink | Reply
    Tags: , , constructor injection, , function injection, property injection, , webapi   

    ASP.NET and WebApi attributes with StructureMap 

    After some time away from setting up new ASP.NET MVC and WebApi projects, I am having a helluva time doing just that in a new project of mine.

    But first…

    …a nice link to all of you who struggle with the getting the new version of StructureMap up and running, provided with just the horrible StructureMap web site and all outdated blog post examples.

    This web site is up to date and contains a bunch of great information about getting the new StructureMap version up and running: http://structuremap.github.io

    The problems I faced

    I am setting up a WebApi with two levels of client auth. First of all, the client must be authorized for all requests. This is handled by a custom AuthorizationFilterAttribute that I add to a ApiController base class:

    public class AuthorizeClientAttribute : AuthorizationFilterAttribute
    {
       public override void OnAuthorization(HttpActionContext actionContext)
       {
          ...
       }
    
       ...
    }
    

    Second, the user must be authenticated for some requests. This is handled by a second AuthorizationFilterAttribute.

    Both filters depend on components that are setup by StructureMap. But how should these be resolved?

    Option 1: Custom filter provider

    I first tried implementing a filter provider that built up all attribute instances when the app starts, but could not get it to work with my authorization filter attributes. If this works, it’s most definitely the best approach, so feel free to share if you have made it work.

    Option 2: Constructor injection

    My preferred way of injecting dependencies, is doing it with the constructor. The problem with attributes, though, is that if you add parameters into the constructor, you must specify them when using the attribute as well, or add a default constructor.

    Adding a default constructor means that you have to resort to a constructor that refers to the IoC container for the default instances, and have a constructor with parameters that you can use for your unit tests, as such:

    public class AuthorizeClientAttribute : AuthorizationFilterAttribute
    {
       public AuthorizeClientAttribute()
          : this(IoC.Container.InstanceOf<IMyComponent>())
       {
       }
    
       public AuthorizeClientAttribute(IMyComponent component)
       {
          ...
       }
       ...
    }
    

    Kids, do not do this. It makes your attribute’s dependencies point out, and makes it aware of the fact that an IoC container exists. Good luck with making this attribute general for all your various projects.

    Option 3: Property injection (instance)

    I then tried injecting my dependencies using property injection on an instance property, but since the attribute does not pass through the IoC container, this did only work for unit tests.

    This means that your unit tests can set the property, but that the attribute still has to point out and poke the IoC container whenever a property is not set:

    public class AuthorizeClientAttribute : AuthorizationFilterAttribute
    {
       public IMyComponent Component { get; set; }
       
       public override void OnAuthorization(HttpActionContext actionContext)
       {
          var component = Component ?? Component = IoC.GetInstance<IMyComponent>();
       }
       ...
    }
    

    This is equally bad! Remember, the attribute should know nothing about how the project is setup and how dependencies are resolved. It should only know about the action context, and handle it though any dependencies we provide it with.

    Option 4: Property injection (static)

    I then tried injecting my dependencies using property injection on an static property instead. This allows us to set it in a StructureMap registry as well as in our unit tests:

    public class AuthorizeClientAttribute : AuthorizationFilterAttribute
    {
       public static IMyComponent Component { get; set; }
       
       ...
    }
    

    This works (READ ON!) and decouples the attribute from the IoC container and how dependencies are resolved. Still, make no mistakes, this is a terrible, TERRIBLE approach, since all requests will be handled with the same component instance.

    We do not want that. Consider a component that accesses the database or operations like that. If we want a single instance, we should get a single instance only because we have set it up as a singleton in StructureMap.

    So, how did I solve it?

    After specifying how my attributes should work:

    • Dependency injection using constructor injection
    • Unaware of anything outside the action context
    • Property scope should be handled by the IoC, not by the attribute

    I realised that there is another way to inject logic, and finally landed on injecting a function:

    public class AuthorizeClientAttribute : AuthorizationFilterAttribute
    {
       public static Func<MyComponent> GetComponent { get; set; }
       
       public override void OnAuthorization(HttpActionContext actionContext)
       {
          var component = GetComponent();
       }
    
       ...
    }
    

    This means that my unit tests can inject a function that returns a fake, a mock or whatever:

    [SetUp]
    public void Setup() 
    {
       _attribute = new AuthorizeClientAttribute();
       AuthorizeClientAttribute.GetComponent = GetComponent;
    }
    
    private IMyComponent GetComponent()
    {
       return Substitute.For<IMyComponent>();
    }
    
    ...
    

    Meanwhile, a registry can inject a function that resolves the dependency, using the IoC container:

    public class SecurityRegistry : Registry
    {
       public SecurityRegistry() 
       {
          AuthorizeClientAttribute.GetComponent = GetComponent;
       }
    
       private static MyComponent GetComponent()
       {
          return IoC.Container.GetInstance<IMyComponent>();
       }
    }
    

    To protect yourself from incorrect setup, make sure to have your attributes crash as early as possible if these function properties are not set.

    Hope this approach helps you out as well.

     
    • John 5:52 pm on November 11, 2015 Permalink | Reply

      hi Daniel, so the SecurityRegistry class is used somewhere? Does this get registered in the global.asax?

      • danielsaidi 10:41 pm on December 6, 2015 Permalink | Reply

        Hi John!

        Yes, the registry class is automatically used by StructureMap, if you tell StructureMap to look for all registries within the assembly where the class is located. However, you do not have to use a registry – you can add the code to where you set up your IoC container as well.

        All the best!

  • danielsaidi 7:55 am on August 26, 2015 Permalink | Reply
    Tags: cordova, , sudo,   

    “sudo” required for all Ionic Framework and Cordova commands 

    I am building my first Ionic Framework app. So far, Ionic Framework is super fast to setup and performs really well. We’ll se how it performs once I have started using a lot of images and content in the app.

    At home, the getting started guides worked just fine, but at work, I ran into some permission-related problems, where I had to use sudo for all Ionic and Cordova commands.

    Sure, installing Ionic and Cordova globally requires you to use sudo, but I also have to use sudo for these commands:

    • ionic platform add android
    • ionic build ios
    • ionic run android

    If I do not use sudo, Ionic is unable to remove assets in the platform folders. Also, I cannot open the project in XCode, due to lack of permissions. Quite annoying, to say the least.

    I have finally found a terminal command that solves these problems, when they occur (which is not always):

    sudo chown -R $(whoami) ~/<path to your project folder>

    Just run it, and you will no longer have to use sudo when executing Ionic or Cordova commands. You will also be able to open the XCode project (although you probably should not, since it resets each time you build).

     
  • danielsaidi 9:54 pm on May 4, 2015 Permalink | Reply
    Tags: apple,   

    XCode 6.3.1 – Code object is not signed at all. 

    After upgrading to XCode 6.3.1, I started receiving a new, strange error that I have not received before:

    ERROR ITMS-90035: “Invalid Signature. Code object is not signed at all…”

    This occurs every time I try to submit an app to the App Store, even for old apps that were perfectly submittable prior to updating to the latest XCode version.

    It turns out that the problem was an .sh file in one of the external libraries I often use. Previously, archiving .sh files has worked without any problems whatsoever, but now Apple seems to require them to be signed as well.

    Since the .sh file I use does not have to be included in the project, I just removed the project reference and kept the file on disk. Hopefully, you should be able to do the same if you run into this problem as well.

     
    • Uwe 9:05 pm on June 11, 2015 Permalink | Reply

      Daniel, you have saved my life. I got the same error with an IBM Worklight project. Worklight Studio (which is Eclipse based) generates the xcode project as a part of build process. And here a buildtime.sh will be created and included in xarchive. Removing the shell script did the trick. Thank you!

  • danielsaidi 9:00 pm on September 10, 2014 Permalink | Reply
    Tags:   

    Swift does not detect line breaks 

    I am currently porting my game concept Appamini to Swift and SpriteKit, and thus rewriting a lot of code. While porting the splash screen, I just stumbled onto something rather fun.

    In the splash screen, I have an animateAppa() method, that animates how a cat paw moves over the screen and reveals the first part of the logo – Appa.

    The very first thing I do, is to move the cat paw down one screen height, so that I can animate how it enters the scene. Still, when working on node placement, I wanted to cancel all animations and thus added a return at the beginning of the method.

    function animateAppa() {
       return
       leftHand!.position.y = leftHand!.position.y - self.frame.height
       
       //Some code for animating the hand
    }
    

    Care to guess what happens? Well, Swift ignores the line break and interprets the two lines as that it should return the value of the position change operation. As a result, the hand disappears, THEN the method ends.

    So, Apple, in the absence of semi-colons (which I like), make Swift detect line breaks, so that this does not happen. This also happens before that method, when the main animate method is called.

    func animate() {
       return
       animateAppa()
    }
    

    Yep, despite the return, animateAppa() is called.

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel
Follow

Get every new post delivered to your Inbox.

Join 28 other followers