Friday, December 13, 2013

Integration testing Azure Active Directory

This post is my history of how I got from not knowing how Azure Active Directory (AAD) to write some integrations tests with MSTest


Last week I had to investigate if Azure Active Directory was an option for my company’s next Web project and future applications. I started to play around inside the Azure Portal to see how that works, and must say that was very intuitive and easy to use- so I won’t cover that in this post.

Now that I had the fundamental understanding on how the AAD worked in the Azure Portal I needed to figure out how I could work with the data through code. I asked Magnus Mårtensson  aka @noopman on twitter (who is Windows Azure MVP) what frameworks to use, and he suggested that I should look at the Windows Azure AD Graph API. The API helps developers execute create, read, update, and delete (CRUD) operations on Windows Azure AD objects such as users and groups. Just the thing I need!

I thought that I could download the files via Nuget, but I wasn’t able to find it, and after some googling I found and MVC Sample App for Windows Azure Active Directory Graph the solution also included the WindowsAzure.AD.Graph project.

This was pretty cool, I could browse through all the code and understand how it all fits together. But why are example code often presented using a web or windows application? Why not just cut of all that web/windows crap and presented the code in small unit tests? This way you can easer understand what it takes to do a specific task with an API.

Prequisites you need to know how to setup an application in AAD if not got here http://msdn.microsoft.com/en-us/library/windowsazure/dn151791.aspx


Enough talking let’s make the tests happens!

Step1

Create a unit test project, in this example I’m using MSTest. Make references to the following dll’s (the dll’s can be found in the WindowsAzure.AD.Graph project)
  • Microsoft.Data.Services.Client.dll
  • Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
  • Microsoft.WindowsAzure.ActiveDirectory.GraphHelper.2013_04_05.dll


Step2

Be sure that your application Azure Directory Access need to be SINGLE SING-ON, READ AND WRITE DIRECTORY DATA
First Create a GraphServiceHelper class, in this code you have need to specify the
tenantName: example ronniestestaccount.onmicrosoft.com


ClientId and Password
The clientID and password you can find in AAD under the applications “Enable your app to read or write directory data”
public static class GraphServiceHelper
{
        public static DirectoryDataService Create()
        {
            var tenantName = " ronniestestaccount.onmicrosoft.com";
            // retrieve the clientId and password values
            string clientId = "XXXXXXXX-XXX-XXX-XXX-XXXXXXXXXXXX";
            string password = "v4J4p5gHnUeb437Mu4fzLP7e9Oo529ycpE3CNbA104g=";
            // get a token using the helper
            AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantName, clientId, password);
            // initialize a graphService instance using the token acquired from previous step
            var graphService = new DirectoryDataService(tenantName, token);
            return graphService;
        }
    }


Step3

Now were ready to write some tests, to get started and make sure that you have connection to your AAD write a simple test that get all the users that exist in you AAD. (In my case I have created a few users, so I know that I have more than 2 users in the AAD)

Test1

private DirectoryDataService DirectoryService{
      get { return GraphServiceHelper.Create(); }
}


[TestMethod]
public void ShouldHaveMoreThanTwoUsersInAAD()
{
            var users = DirectoryService.users;
            Assert.IsTrue((users.ToArray().Length >= 3));
}

When this test works, let’s try to create a new user.

Test2

[TestMethod]
public void CanCreateUser()
{
                             DirectoryDataService dataService = DirectoryService;
                             string alias = Guid.NewGuid().ToString();
                             User user = new User();
                             user.displayName = alias;
                             user.userPrincipalName = alias + "@ronniestestaccount.onmicrosoft.com";
                             user.mailNickname = alias;
                             user.passwordProfile = new PasswordProfile{

                                                                                                       forceChangePasswordNextLogin = false, 
                                                                                                       password = "Myy%1982"
                                                                                                };
                             user.accountEnabled = true;
                             dataService.AddTousers(user);
                             dataService.SaveChanges();
                             User newUser = DirectoryService.users
                                                          .Where(usr => usr.userPrincipalName == alias + " @ronniehhegelundgmail.onmicrosoft.com")
                                                          .FirstOrDefault();  
Assert.IsNotNull(newUser);
}

Run the test and got to see the success and go to you AAD to verify it.
Now that we have created a user let’s update the userprofile, by Finding the UserPrincipal of you newly created user in the AAD, and use that instead of the USERPRINCIPAL in the following code example.

Test3

[TestMethod]
public void CanUpdateUserDepartmentName()
{
                             DirectoryDataService dataService = DirectoryService;   
                             User user = dataService.users.Where(it => (it.userPrincipalName == USERPRINCIPAL)).SingleOrDefault();
                             string departmentName = "IT Department_" + DateTime.Now;
                             user.department = departmentName;
                             dataService.UpdateObject(user);
                             dataService.SaveChanges(SaveChangesOptions.PatchOnUpdate);                
                             User newUser = DirectoryService.users
                                                          .Where(it => (it.userPrincipalName == USERPRINCIPAL))
                                                          .SingleOrDefault();
                             Assert.AreEqual(newUser.department, departmentName);
}

 

Summary

In this post I just showed how easy it is to write integrations test against the AAD. And a more lightweight way to try working and debugging the API, than through a MVC application.


Friday, November 29, 2013

Do we need a TypeScript BCL

I have been thinking about starting a new TypeScript project TypeScript.BCL.

I'm not quite sure that I need it, but I also feeling dumb writing my own "standard types" for example the Guid. So I was thinking what would a TypeScript.BCL consist of.

Quick brainstorm:

  • Guid
  • Lists, queues, stacks, hashtables, dictionaries and readonly
  • StringBuilder


I know that I already can find most in JavaScript or TypeScript already, but I think i would be nice if there was only one place to get what you need, and a dedicated group to maintain the library. This would also be a good opportunity to meet others that would geek and talk about TypeScript.

So should we, or should we not have a TypeScript base library, that is the question, please post questions or comments that would be great.

Thursday, November 28, 2013

My first MVP summit

Back in Denmark after an awesome mvpsummit.



This was my first time attending the MVP Summit, first trip to the USA and first time experience what jet-lags is all about. This was pretty energized consuming!

I arrived at the Seattle airport Saturday after a 14 hour flight, and took a cab directly to Hilton Hotel in Bellevue. When I arrived to the hotel my roommate Thomas has already chosen a bed and left the building.

I went downtown Bellevue to checkout the city for a few hours, then I went back to the hotel lobby and drank a few beers and saw some american football (this I don't understand).



The MVP summit was really great and inspirational, sadly I can't say much about the session's, but did talked to Anders Hejlsberg and Mads Kristensen and some other cool guys from Microsoft.
Unfortunately I did only shortly meet with my MVP Community Lead William Jansen who is just doing and awesome job, hopefully I would meet him again in the future.

MVP Summit is not only about technical sessions and the future of Microsoft products, but also about connecting with other MVP's, and that was amazing to geek and have fun with fellow MVP's.

I met to MVP's from Denmark Thomas Martinsen and Morten Nielsen who both were Client Developer MVPs.
Later I bumped into Mariano Gomez, great guy who quickly found out that I was having a Dynamics AX 2012 issue, and invited me to talk with the rest of the Dynamics MVP's pretty cool, here I met Murray Fife who knew a lot about the Product Configurator.
Later I met Azure MVP Magnus Mårtensson who got me drunk - pretty funny guy from sweden.

The last day me and my roommate took a cab to the Space Needle here we helped a guy to take pictures while he purposed to his girlfriend, After that we played tourist downtown Seattle.

Thomas and I at the great wheel

Last we went to the Rockbottom Brewery in Bellevue and drank a few beer's


All in all a great first time MVP summit, hopefully I will have the opportunity to attend again next year!





Friday, September 20, 2013

My Talk at brewww on TypeScript, TDD and code kata’s.

I did my first "real" talk last Friday 13th. "TypeScript Kata: The TDD style"
I think it went pretty well, in the light of it was Friday 13th, and the lack of my presentation just finished 30 min. before I had to go to the event. So I didn't have the time to do any review or rehearse.

My talk was meant to be a lightning talk that is max. 15 min. long, so that was, what I prepared for.
The other speaker couldn't make it, so I could talk for as long as I wanted – Great! I forgot Time and Space and don’t know for how long I talked.….

The attendee’s was very good to ask question, and we had some great discussions back and forth. Some of the guy’s said that I was pretty brave. In the light of, that all the attendees were drinking beers, and Open Source PHP/APACHE/LINUX/APPLE guy’s and in the fact that I’m a "Microsoft" man, showing of code in Visual Studio.


Hopefully I inspired a few people to dig into TypeScript, TDD or start making code kata’s.- And Basim realize that TypeScript is way better designed than CoffeeScript ;-p

Even though @mortendk and @christianjul, got inspired to make a bitch fight on Text editors and IDE's later this year, and of cause they want's me or somebody I know to defend Visual Studio! 

Thanks people @Brewww to give me an awesome night, this is not the last time I attend @Brewww or given talks, - I think Im already addicted :-)
What is Brewww?
Brewww is for web developers, designers, nerds, geeks and all others from the web industry. The people is primary Open Source PHP/APACHE/LINUX/APPLE guys. The meetups is quarterly for lightning talks / beer tasting and in copenhagen. Brewww is the brainchild of @mortendk and @christianjul. 

Wednesday, August 21, 2013

TypeScript v0.9 enum bug

/*
Update, after upgrading to v.0.9.1 it works as it should!
*/

I think I found a bug in the TypeScript enum. in the below example the WindeDirections.None should automatically be assigned the value 4, but it's actually 0.

TypeScript code
enum WindeDirections {
    North = 0,
    South = 1,
    West = 2,
    East = 3,
    None      
}

compiled code:
var WindeDirections;
(function (WindeDirections) {
    WindeDirections[WindeDirections["North"] = 0] = "North";
    WindeDirections[WindeDirections["South"] = 1] = "South";
    WindeDirections[WindeDirections["West"] = 2] = "West";
    WindeDirections[WindeDirections["East"] = 3] = "East";

    WindeDirections[WindeDirections["None"] = 0] = "None";
})(WindeDirections || (WindeDirections = {}));

I will write about TypeScript enum in details later :-)



Friday, August 2, 2013

TypeScript : Generics, < T > is for Type

Finally we got generics in TypeScript version 0.9, I have patiently waited for that feature, and now it's here, great!

There is already a few that have ben blogging about TypeScript Generics and give some examples. This is cool, though they haven't ben telling the fundemental of generics in TypeScript. So I have trited to do that, instead of another cool example :-)

What are Generics

Generics was introduced in version 0.9. Generic types allow for code reuse with type safety. The Internal algorithm remains the same, only the type changes and disappears again on compilation and generates no artifacts to the resulting JavaScript.

Why use generics

Generics provide quality to your solution by giving your type-safe at compile-time, and reduce repetitive programming tasks, by creating generic type-safe abstractions to classes and methods.

Generic type parameters

Specifies when they instantiate a variable of the generic type.
Type parameter name commonly starts with T. Consider not just give the parameter the name T For example, call it TThing as below:
In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they instantiate a variable of the generic type.

class ItemCollection< TThing >
{
    private _things: Array< TThing >;

    Add(thing: TThing) {
        this._things.push(thing);
    }
}


Generic constrains

When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified by using the extends keyword. You can define constrains with an interface or a specific class. Example below by making a constrain to IAnimal.

class AnimalCollection< TAnimal extends IAnimal >
{
    private itemArray: Array< TAnimal >;
   
    constructor() {
        this.itemArray = [];
    }
   
    FeedAll() {
        this.itemArray.forEach(
            (item) => item.Feed()
        );                   
    }       
}


Generic classes

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like the Array. A simple example of a generic class could be a class as follows:

class ItemCollection< T >
{
    private itemArray: Array< T >;
   
    constructor() {
        this.itemArray = [];
    }
   
    Add(item: T) {
        this.itemArray.push(item);       
    }
   
    GetFirst(): T {
        return this.itemArray[0];
    }
}


Generic methods

A generic method is a method that is declared with type parameters, as follows:

    Add(item: T) {
        this.itemArray.push(item);       
    }

You can also specify constrains on Type parameter, the below tells you that the parameter animal should implement the interface of IAnimal as follows:

function Add< T extends IAnimal >(animal: T)
{
    //...
}

Conclusion

TypeScript generics ensure type-safety and quality, reduce repetitive programming tasks, simplify the overall programming model, and do so with elegant, readable syntax. Generics is a compile-time only concept that disappears on compilation and generates no artifacts in the resulting JavaScript.

Thursday, July 25, 2013

Visual Studio RavenDB DataSource Explorer

Helping other developers being more productive at their daily work, is something that I enjoy. The last idea I got was trying to extend Visual Studio, by making a RavebDB DataSource Explorer prototype. This was fairly easy thanks to the documentation on msdn http://msdn.microsoft.com/en-us/library/bb165051(v=vs.100).aspx

It is still just a prototype, it needs validation and code cleaning. For now I can register new data sources by clicking on 

and the below dialog opens to create the datasource.


When RavenDB explorer is open I can right click on a datasource and connect to the server, or remove it from the explorer window.












When I have connected to the server it list all the databases




























When I double click on an item it opens an internet explorer window and goes directly to that document in the RavenDB Management Tool.
I have a bunch of ideas to this project, basic management options like, create new Database etc.
If you have any ideas/feature you think could be valuable, please let me know, I will love trying to implement them.

Sunday, July 14, 2013

Simple TypeScript Unit Test Project Templates

Inspired by John V. Petersen's latest post http://codebetter.com/johnvpetersen/2013/07/05/a-simple-jquery-qunit-based-javascript-unit-test-project-template/ I thought that TypeScript needed Unit Test project templates to.

I prefer using the Jasmine test framework, but knows that Qunit is popular, so I decided to make a project template for each of them. I have published them on the visualstudiogallery.

TypeScript Qunit Test Project
TypeScript Jasmine Test Project

After installing your preferred Test Project you can find it by choosing new project and go to "other langauges => TypeScript"














The basic structure for the jasmine project looks like this:



The Quint look almost the same, the only different is that I have installed the qunit.d.ts file via nuget instead of the jasmine.d.ts.
The reason for the d.ts files is placed in this structure "Scripts/typings/jasmine/jasmine.d.ts" is that, this is the basic structure when you install TypeScript definition files from nuget.

To get it working you also needs to install the chutzpah javascript runner

When this is done, the test will show up in the VS test explorer window.


Thanks John, for the inspiration. I now don't need to copy paste my TypeScript test projects.

Wednesday, July 3, 2013

2013 Microsoft® MVP Award! in Visual C#

A couple of month’s back I’ve got an email from Microsoft that I have been nominated for a MVP award, the only thing I should do was to fill out a word document. First I thought it was a spam mail and reread the mail. When I was sure it wasn’t spam I filled out the document, and then forgot all about it.
Then a few days ago I’ve got an email “Congratulations 2013 Microsoft MVP!”



I couldn’t believe it! And I still really can’t!.. But my MVP award should arrive on Monday, and when I have the award in my hand I’m sure that I believe it :o)

Today, there are more than 4,000 MVPs worldwide. They represent more than 90 countries, speak over 40 languages, answer more than 10 million questions a year, and are awarded in almost 90 Microsoft technologies.

And I must thanks for those that have nominated me and how proud I am to be a MVP.

Thursday, March 14, 2013

Brewing beer Kata 1st. draft

I am giving a 15min. lightning talk at @brewww "TypeScript kata: The TDD style" Friday 22. of marts.

And thougt I would make a brewing beer kata to the talk, though I'm not sure the following kata is good enough as a standard Kata, please give comment to improvements. Ill promise to post the final Kata in TypeScript later :-)

First draft of the kata:
  1. Create a simple Brewary with a method IBeer Brew()
    1. The method take 0 parameters but needs to return an IBeer
    2. The Beer should be of type lager
  2. Allow the Brew method to handle a brewingTemperature and a fermentationInDays argument
    1. If brewingTemperature is less than 5 throw exception “Temperature is to low”
    2. If brewingTemperature is greater than 4 and less than 11 return a beer of type lager
    3. If fermentationInDays is less than 7 and greater than 14 throw exception “fermentation for lager beers should be between 7 and 14 days”
  3. Add optional ingredients of type string as “roasted malt” and “barley” to make a stout
    1. If fermentationInDays less than 5 and greater than 6 throw exception “fermentation for stouts beers should be 5 or 6 days”
    2. brewingTemperature not equal 20 throw exception
    3. Expect result to be of type Stout
    4. Expect beers alcohol to be 7percent if fermentationInDays is 5
    5. Expect beers alcohol to be 8percent if fermentationInDays is 6

Tuesday, February 19, 2013

Declaration source files and google analytics

What is Declaration source files?

Declaration source files are restricted to contain declarations only. Declaration source files can be used to declare the static type information associated with existing JavaScript and expose their behavior.

I have started to implement TypeScript in my projects at work :-)

In that case I had to implement google analytics but ran into the problem, that I did not have intellisence for the that.

I googled a bit and could not find any declaration file for that, so I made my own.
I can now acces ga, _gaq, _gat and the Tracker object with intellicense in my TypeScript file, nice...

Example

describe("tester Google Analytics Code  _gaq object", () => {
    it("can create _push", () => {
        _gaq.push(['_setAccount', 'UA-XXXXXXX-YY']);
        _gaq.push(['_gat._anonymizeIp']);
        _gaq.push(['_trackPageview']);

        _gaq.push(() => {
                var tracker = _gat._getTrackerByName('UA-65432-1');
                tracker._trackPageview();
            }
        );
    });  
});

I have pushed it to https://github.com/borisyankov/DefinitelyTyped but until it is merged you can get the files here https://github.com/RonnieHegelund/DefinitelyTyped/tree/master/google.analytics



Sunday, February 17, 2013

TeaCrunch - CodeCoverage for Typescript

When working in .NET and writing unit test, I really like the green dots NCrunch gives me. I think its a great way to show what code you have test coverage on.

I would love to have this in TypeScript to, but haven't found any, so I have started making a prove of concept my self.



The prove of concept works, but is very unstable and have to rewrite the code, and need to find out how I can read the results from the test explorer. The biggest problem is to find the time to rewrite my code :-)

Saturday, February 16, 2013

TypeScript - The rest parameter

Rest parameter in TypeScript has nothing todo with REST (REpresentational State Transfer)

If you are familiar with C# params keyword, The rest parameter is the same. The rest parameter lets you specify a function parameter that takes an argument where the number of arguments is variable.

An example could be a function that make a Sum of a variable length of numbers:


Sum(1,2,3,4);

C# example

public int Sum(params int[] list)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  return sum;
}
TypeScript example

public Sum(...list Number[]) : number
{
    return list.reduce( 
        (a,b) => { a + b }
    );
}
And the result when compiled to JavaScript

function sum() {
    var numbers = [];
    for (var _i = 0; _i < (arguments.length - 0); _i++) {
        numbers[_i] = arguments[_i + 0];
    }
    return numbers.reduce(function (a, b) {
        return a + b;
    });
}


Wednesday, February 13, 2013

Update to the book content has changed a bit


Update to the book content has changed a bit.

Introduction to enterprise design
    What is enterprise design?
        Design priciples
            Reliability
            Sepreation Of Concern
            Flexibility
            Maintainablitiy
            Reuseablity
            S.O.L.I.D
                Single responsibility principle
                Open/closed principle
                Liskov substitution principle
                Interface segregation principle
                Dependency inversion principle
        Design patterns
            Working with design patterns
            The benefits of patterns
            Antipatterns

The road to enterprise 
    Testing strategies.
        Unit tests
        Components Tests
        Integrations tests
        System tests
        Manual tests
    Acceptance test
    Test driven development     
        What is TDD
        TDD Kata as an example
    Testing frameworks
        jasmineJS
        QUnit
        Selenium - automated browser tests
    Continous Integration
        Teamcity
            Setting up automated tests
            Setting up automated deployment
        Continous Delivery

Design patterns in action
    View patterns
        MVVM
            Knockout as an example
        MVC
            Backbone as an example

TypeScript Fundamentals
    What is TypeScript
    TypeScript keywords
    Types
        Primitive Types
            The String type
            The Number type
            The Boolean type
            The Null type
            The Undefefined type
    Interfaces
    Classes
    Functions
        Functions arguments
        Arrow Functions
        Extension methods
            What is code smell?
    Inheritance
    Modules
    Generics (not supported yet) .
    Declaration Source Files

TypeScript Tools
    Visual Studio
    Web Essentials
    Sublime text

Thursday, January 24, 2013

Enterpise development in TypeScript


I have started writing a book” Enterprise development in TypeScript”

I am an agile developer, so this book will be published Early and Published Often. This way I can get feedback from readers and make the book as good as possibly.
The focus of this book is to use TypeScript in your enterprise applications. The book will go through the basics of TypeScript, different tools and frameworks, how to create unit tests and, then automate your tests, builds and deployment. The book is far from done, and if you think the book is missing something please don’t hesitate to contact me.

Please, tweet and show your support by saying what you'd like to pay for it at https://leanpub.com/enterprise-development-in-typescript

Book contents would be something like this
1.       TypeScript Fundementals
·         What is TypeScript
·         Static vs Dynamic type language
·         Interfaces
·         Classes & functions
·         Inheritance
·         Modules
·         Arrow functions
·         Generics (not supported yet)
·         TypeDefinitionFiles

2.       TypeScript Tools and frameworks
·         Visual Studio
·         Web Essentials
·         Sublime text

3.       Introduction to enterprise development
·         What is enterprise development?
·         The enterprise code

4.       The road to enterprise
·         Decouple of code
·         Test driven development
·         Continous Integration
·         Continous Delivery
5.       Design patterns
·         Inversion of Control / Dependency Injection
·         Facade pattern
·         Factory pattern
·         MVVM
·         MVC