Monthly Archives: April 2017

Creating an Angular 2 component

An Angular 2 component (written using TypeScript) is a class with the @Component decorator/attribute.

For example

import { Component } from '@angular/core';

@Component({
   // metadata properties
})
export class MyComponent {
   // methods, fields etc.
}

In it’s simplest form we might just supply an inline template to the metadata properties, to define the component’s HTML. Although we can create multiline HTML encased in back ticks `<multiple line HTML>`. We can also store the HTML in a separate file and reference it using templateUrl. Let’s look at some examples.

Single line HTML

@Component({
   template: '<p>Hello</p>'
})
// class definition

Multiline HTML (using the backtick)

The backtick ` is used for multiline strings.

@Component({
   template: `
   <p>Hello</p>
   <p>World</p>
   `
})
// class definition

External Template HTML

@Component({
   templateUrl: 'my-template.html'
})
// class definition

Ofcourse, the equivalent of an HTML component wouldn’t be so useful if we couldn’t also define styles. So, as you’d expect we also have the metadata property for style that works in the same way as the template.

The main thing to note is that the stylesUrls is plural and expects and array of styles, i.e.

@Component({
  selector: 'my-app',
  templateUrl: 'my-app.html',
  styleUrls: ['my-app1.css', 'my-app2.css']
})
// class definition

Referring to class fields

At this point, the class itself might seem a little pointless, but by adding fields etc. to it we can reference these from the @Component template itself.

For example

@Component({
   template: '<p>{{greeting}}</p>'
})
export class MyComponent {
   greeting: string = 'Hello';
}

The {{ }} is Angular 2’s expression syntax, meaning it can contain code to access fields, or actual expressions, such as 2 + 3 or method calls such as max(a, b).

My first Fody ModuleWeaver

I’ve been wanting to look into Fody for a while now, I find it a little annoying when I have to pollute code that actually is a functional part of an application with a mass of boilerplate code, which could be automatically generated. Obviously we can look at T4 templates, partial classes and other ways to achieve such things, but a nice AOP style way is to “code weave” the boiler plate at compile time.

Note: To really get the benefit of Fody you need to understand Mono.Cecil which allows us a simpler way to write our IL. This is outside the scope of this post.

I’m not intending to go too in depth with Fody in this post, but I am going to describe creating a really pointless ModuleWeaver (the class/code which weaves in our new IL code) to add a new type to your assembly as a great starting point for more interesting/impressive code.

I’m going to show how to develop some code into a separate solution and use from a Test application (which sounds easy, and is once you know the expectations of Fody, but took me a while to find those expectations due to some tutorials being out of date) and I’ll also show how to develop a ModuleWeaver within an application’s solution.

Let’s create our first weaver

  • Create a class library project named TestWeaver.Fody.
    Note: The .Fody part is important as Fody will search for DLL’s using *.Fody.DLL
  • Add NuGet package FodyCecil
  • Create/rename you Class1 as/to ModuleWeaver.cs
  • Include the following code in the ModuleWeaver class
    public class ModuleWeaver
    {
       public ModuleDefinition ModuleDefinition { get; set; }
    
       public void Execute()
       {
          ModuleDefinition.Types.Add(
             new TypeDefinition("TestNamespace", "TestType",
                    TypeAttributes.Public,   
             ModuleDefinition.ImportReference(typeof(object))));
       }
    }
    

Note: The basic source for Execute is taken from ModuleWeaver.

Creating a test application

  • Create a console application (we’re not actually going to write any console code for this, so we could have used a different project type)
  • Add NuGet packages Fody (and this should add FodyCecil)
  • Change the FodyWeavers.xml to look like this
    <?xml version="1.0" encoding="utf-8"?>
    <Weavers>
      <TestWeaver />
    </Weavers>
    

Deploying our weaver assembly

Okay, now if you build this ofcourse it will fail, we need to deploy the previously created TestWeaver.Fody somewhere. As we’re not using NuGet to deploy it and not including it in the solution, we have to place the DLL in a specific location so Fody knows where to find it.

Note: Remember, these DLL’s are solely for code weaving and not required in the deployed application, hence we do not need these files to go into the bin folder and we do not need to reference any *.Fody.DLL assemblies as they’re just used by Fody to change our IL (unless you’ve put attributes or the likes in the DLL – best practise would be to have these in a separate DLL which is referenced).

Add a folder named Tools to the to your solutions folder. i.e. SolutionDir/Tools.

Drop the files from your TestWeaver.Fody into this folder and now try to rebuild our test application. Now Fody should use you waver DLL to change the IL. If you open the application assembly in ILSpy (or the likes), you should see Fody (via our TestWeaver) created the TestNamespace and TestType we defined in our ModuleWeaver.

Including our Weaver in our solution

If you’ve covered the steps above, now delete the SolutionDir/Tools folder as we’re going to instead create our Weaver in a project within the test application solution.

In this case

  • Create a class library named Weavers in our test application
  • Create a class/rename the Class1 to TestWeaver.cs
  • Add this code to TestWeaver
    public class TestWeaver
    {
       public ModuleDefinition ModuleDefinition { get; set; }
    
       public void Execute()
       {
          ModuleDefinition.Types.Add(
             new TypeDefinition("NewTestNamespace", "NewTestType",
                    TypeAttributes.Public,   
             ModuleDefinition.ImportReference(typeof(object))));
            }
        }
    

    Note: I’ve renamed the namespace and type within the generated IL just to ensure we notice the difference in ILSpy

Notice (again) that we do not reference this project, but we will need the project to be built before our test application. So select the solution and right mouse click, select Project Build Order and you’re probably see Weavers listed after the test application, hence select the Dependencies tab, ensure your test application project is select in the Projects drop down and tick Depends On Weavers.

Now rebuild, inspect the resultant assembly using ILSpy. The namespace and type added should have their names changes as we’re now generating our IL code via the solution.

Debugging your Weaver

Obviously, as the weaving takes place as part of the build, we’re going to need to attach our debugger to a build or run the build via a debugger. Initially I simply placed a Debugger.Break() in my Execute method on my weaver module and clicked the build button. This worked the first time but not subsequent times and required the weaver to be in the same solution as the test application, so we’d be best to run msbuild directly from our project and debug via that application.

Here’s a comprehensive post on debugging msbuild – Debugging a Fody Weaver (Plugin) and/or debugging MSBuild.

We can also add logging to our application via some of the other possible insertion points in our Module Weaver, foe example, take a look at ModuleWeaver and you’ll see the “option members” include LogWarning, LogError, LogInfo (and others) which allows us to output log information during the build.

References

Simple AOP with Fody
ModuleWeaver
Fody on github
Creating a Fody Add-in

Interacting with SOAP headers using CXF

Sometimes you might want to interact with data being passed over SOAP within the SOAP headers, for example this is a technique used to pass security tokens or user information etc.

CXF comes with quite a few “insertion points” whereby we can insert our code into the workflow of WSDL creation, SOAP calls etc. Here we’ll just look at the specifics of intercepting the SOAP call and extracting the header (ofcourse the reverse can also be implemented, whereby we intercept an outward bound call and insert a SOAP header item, but that’s for the reader to investigate).

I’m only going to cover implementing this in code, but obviously this can also be setup via Spring configuration also.

To add an interceptor to our JaxWsServerFactoryBean, we do the following

JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
// set up the bean, address etc.

org.apache.cxf.endpoint.Server server = factory.create();
server.getEndpoint().getInInterceptors().add(new SoapInterceptor());

Now let’s look at the SoapInterceptor

public class SoapInterceptor extends AbstractSoapInterceptor {
    public static final String SECURITY_TOKEN_ELEMENT = "securityToken";

    public SoapInterceptor() {
        super(Phase.PRE_PROTOCOL);
        addBefore(WSDLGetInterceptor.class.getName());
    }
    
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        String securityToken = getTokenFromHeader(message);
        // do something with the token, maybe save in a context
    }

    private String getTokenFromHeader(SoapMessage message) {
        String securityToken = null;
        try {
            List<Header> list = message.getHeaders();
            for(Header h : list) {
                if(h.getName().getLocalPart() == SECURITY_TOKEN_ELEMENT) {
                    Element token = (Element)h.getObject();
                    if(token != null) {
                        securityToken = token.getTextContent().toString();
                        break;
                    }
                }
            }
        } catch (RuntimeException e) {
            throw new JAXRPCException("Invalid User", e);
        } catch (Exception e) {
            throw new JAXRPCException("Security Token failure ", e);
        }
        return securityToken;
    }
}

Intercepting localhost calls with Fiddler

A while back I wrote a post on Intercepting and creating SOAP messages using Fiddler.

I’ve just had to revisit this post to debug changes in a SOAP implementation which seemed to be causing unexplained failures.

So I started up the servers (running in Java) and configured my .NET client as per the previously mentioned post, but for completeness, let’s show the App.config changes here anyway

<system.net>
   <defaultProxy>
    <proxy bypassonlocal="false" usesystemdefault="true" />
   </defaultProxy>
</system.net>  

I then ran Fiddler v4.5.x.x and then the .NET application. Fiddler showed no traffic.

Fiddler and localhost from a .NET application

Hunting around, I found several possible solutions, for intercepting IE or another browser, changing localhost to localhost. was one suggestion as well as adding the Fiddler proxy in some other way, but as per Problem: Traffic sent to http://localhost or http://127.0.0.1 is not captured, simply changing localhost in your application to the machine’s name worked and now I could intercept localhost messages.

Unable to install new software in Eclipse (behind a proxy)

I’m using Eclipse to do some Java work and I wanted to install subclipse from the marketplace/via the install new software. Now I have to go through a proxy server and this can be setup easy enough, but I found the Install New Software dialog stuck at 2% for ages or Market place just does nothing. I even tried downloading the plugin I wanted and deploy manually but it wanted to access other plugins/components, meaning again I got stuck accessing anything on the web.

So how to we fix this issue…

Note: I’m using Neon at the time of writing, therefore I can only confirm that the below works for this version of Eclipse.

Setting your proxy in Eclipse

First let’s review setting up our proxy server configuration in Eclipse.

  • Select Window | Preferences
  • Select General | Network Connections
  • Switch Active Provider to Manual
  • Edit HTTP & HTTPS to set your proxy host, port, user credentials
  • You may also need to set SOCKS up for your proxy, but this might cause an issue if your proxy doesn’t support it. Spoiler Alert: this was caused a problem where I couldn’t download from the market place etc. see below
  • You may well need to Add localhost and 127.0.0.1 to the Proxy bypass option in the Network Connections dialog
  • I had HTTP, host dynamic unchecked
  • Press OK to confirm your proxy settings

Install new software or go to the Eclipse Marketplace

Now I want to install subclipse (or install new software). Either way when running install I now hit the previously mentioned problem of not completing our download from the market place.

The problem appears to be down to (if you read setting up the proxy you’ll see the spoiler), the proxy actually doesn’t support SOCKS. So if you’ve setup a host, user credentials etc. for SOCKS, select SOCKS and click the Clear button (you cannot remove the fields using Edit).

Ofcourse if your proxy does support SOCKS, I’m afraid this probably won’t help.

Now retry accessing the Install New Software or Eclipse Marketplace and all should work.

npm and a proxy server

I was just setting up npm to try out Angular and hit the age old problem of accessing the internet through a proxy server.

You can set your proxy servers as follows

npm config set proxy http://<username>:<password>@<proxy>:<port>

and likewise the https proxy as follows

npm config set https-proxy http://<username>:<password>@<proxy>:<port>

This should create the relevant configuration file (.npmrc) in your c:\Users\{username} folder on Windows.

To confirm the location you can simply type

npm config get

Note: type “npm config” to get a list of usage commands.

You can also edit the .npmrc with a text editor, which is the simplest way to update password or the likes for your proxy.

Cannot GET / in Angular

I was playing with the quick start tutorial from Angular’s setup page on their web site.

Using the file/folder layout on their THE HERO EDITOR I removed all folders/files not listed in their diagram.

For completeness I’ll duplicate the information here

angular-tour-of-heroes
|—src
|—|—app
|—|—|—app.component.ts
|—|—|—app.module.ts
|—|—index.html
|—|—main.ts
|—|—styles.css
|—|—systemjs.config.js
|—|—tsconfig.json
|—node_modules …
|—package.json

I then ran npm start from the command prompt in the root angular-tour-of-heroes and up pops the browser with Cannot GET /, looking at the output from npm I could see index.html was not found by npm.

I also noticed npm couldn’t find a file bs-config.json, so I located that from the quick start and placed it in the root angular-tour-of-heroes folder and all worked correctly, no more 404.

Here’s why, the bs-confog.json gives the baseDir of the “website”, here’s the file context

{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    }
  }
}

Ubuntu server updating

Every month (at least) I check my Ubuntu servers for updates and every month (at least) I forget how I clean old installs etc.

The following is a list of commands that I use regularly. This post is not meant to be a comprehensive description of these Linux/Ubuntu commands, more a checklist for updating my servers.

df or df /boot

When I log into my servers and see updates available the first thing I tend to do is run df and check the /boot usage/space available (obviously I could jump straight to the next command in my list, but I sort of like knowing what space I have available). I’ve tried carrying out an update in the past with next to no space available and sadly end up spending way too long trying to clear up partially installed components and/or clear disc space.

Alternatively, if you only want to view the /boot usage/space – which is really what we’re after here, just use df /boot.

sudo apt-get autoremove

apt-get is the Ubuntu based package manager (well, it’s actually originally from Debian), we’ll need to run it as the su. The options supplied will remove old packages and configurations files and all unused packages.

Why is the above useful? Well as we add updates to Ubuntu, it’s not unusual to find previous releases sat on our machine in the /boot area (I assume this is so we could roll back a release). Once you’re happy with your latest updates (or as I do, prior to the next update), run this command sudo apt-get autoremove to clear out these unused packages and free up disc space.

sudo apt-get update

The update option will retrieve a new list of packages available. This doesn’t install new versions of software but will ensure all package index files are upto date.

sudo apt-get upgrade

Now its time to upgrade we run sudo apt-get upgrade. This will look to clear out old packages if required, but doesn’t seem to do a more comprehensive removal, unlike purge and autoremove.

This command uses information from apt-get update to know about new versions of packages on the machine.

sudo apt-get dist-upgrade

If we want upgrade dependencies etc. this can be used instead of the straight upgrade.

sudo reboot now

Time to restart the server. This will obviously reboot the machine instantly (now).

uname -r

I don’t tend to use this during my “update” process, but if I want to know what version of the Linux kernel I’m running, using uname -r will tell me. This does become important if (as has happened to me) I cannot autoremove old kernels. Obviously when targeting specific kernels you need to know which one is current, or to put it another way, which one to not remove.

So for example, at the time of this post my current kernel is

4.4.0-72-generic

dpkg -l | grep linux-image

If you want to see what kernels exist on your machine, use dpkg -l | grep linux-image. This will (in conjunction with uname -r) allow us to target a purge of each kernel individually, using the following command.

sudo apt-get -y purge linux-image-?.?.?-??-generic

Obviously replace ?.?.?-?? with the version you wish to remove. This will then remove that specific package.