Thursday, March 6, 2014

AX 2012 X++ compilation from a .NET developers perspective

The last month or two I have been “forced” to look at X++ and AX2012, and getting started writing X++ is easy, if you have a background as a .NET developer.

When you start writing and compiling code in AX, you quickly get frustrated as a .NET developer. Why does it not work, - my “compilation” did not throw any errors! It works when I run the job manually, but automatically I does not!

So I realized that there was some fundamental AX2012 that I did not understand as a .NET developer, and much of the frustration was due not understand how the AX compiler works. For many (if not most!) developers this might not be a problem at all, or at least to at some point. In my case it was from the beginning.

I will try to explain how I understand as a .NET developer how the X++ compiler and runtime execution works.

At a high level, the process of compiling and X++ is illustrated in this diagram.


When you are compiling in AX, you don’t compile directly into .NET CIL, it only compiles to p-code. CIL is generated by actively choosing to generate it - either incrementally or full (full generation takes maybe 10-15 min). The Compilation results in P-code are stored in the model store (SQL database). 

Depending on the entry points your code will either be executed either directly in p-code or in CIL. From P-Code you can also easily switch to CIL execution – which is what the application does in most of the more complex proceses. However much code is still executed I P-Code.

Compilation is a three-phased process requiring all code fragments to be received from database (model store). “the three-phased process”, can be read in greater detail in this post: http://bit.ly/1e0WM3I

Phase1: Limited compile only for metadata "class declarations and method signatures"
Phase2: Full compile for metadata and code bodies.
Phase3 to PhaseN: Recompile the error elements, until success or error stabilization.

I have tried for fun to create a detailed diagram, but sometime it’s just easier to tell by code, rather than a diagram :-) decide yourself. First you see the example

First I show a diagram and next a good C# pseudo code example.


C# pseudo code example, borrowed from the post bit.ly/1e0WM3I

// Phase1: Limited compile only for metadata
// (of class declarations and method signatures).
foreach(Element in AOT)
{
       Element.CompileHeaders();
}
// Phase2: Full compile for metadata and code bodies.
foreach(Element in AOT)
{
       compileSuceeded = Element.Compile();
       if (compileSuceeded == false)
       {
              ListOfBadElements.Add(Element);
       }
}
// Phase3 to PhaseN: Recompile the errored elements
// until success or error stabilization.
if (ListOfBadElements.Count > 0)
{
       while(true)
       {
              foreach(Element in ListOfBadElements)
              {
                     compileSuceeded = Element.Compile();
                     if (compileSuceeded == false)
                     {
                           NewListOfBadElements.Add(Element)
                     }
              }
              
              if (ListOfBadElements.Count == NewListOfBadElements.Count)
              {
                     break; // The list of elements with errors has been stabilized.
              }
              ListOfBadElements = NewListOfBadElements.GetCopy();
              NewListOfBadElements.Reset();
       }
}

So what is the different between p-code and CIL? In short: p-code is lazy regarding type-checking and CIL is strongly typed, the same way as when your C# code has been compiled to CIL.

P-code
p-code is the byte code, which been compiled from X++ by the AX compiler.
First when I started writing this post I was comparing p-code as JavaScript? Because of the less restrictive type checking at runtime than compiled CIL has, but this is not true! After some good discussions with Achim (Dynamics AX Technical Architect) and Stig (Consultant), I concluded that we are not playing around coding in byte code (P-Code) but you do in JavaScript. P-Code runs in interpreted mode on either the client or the server.

CIL
Batch jobs and the Business Connector always run in CIL code, and CIL can run on both the server, or the client. CIL runs on the CLR infrastructure, which is much faster than the interpreted p-code.

Be aware when using interpreted P-code
The last thing I want to mention in this post is to be aware when using interpreted P-code. It has less restrictive type-checking at runtime than compiled with CIL, and this can cause your problems. I have probably found an AX bug where a method requiring a sub-type argument but actually getting a super-type instead. This can work fine in p-code, if the code is not calling something that is sub-type specific, but would give you and error in CIL because it’s strictly typed. And this will raise an “unable to cast the super-type to a sub-type”.






Sunday, January 19, 2014

Preconf at the Warm Crocodile Developer Conference

The Warm Crocodile Developer Conference (WCDC) is normally 2 days, but this year Microsoft held a preconf the day before, so 3 days of geeking, speaking and drinking beers at nørrebro brewery, pretty nice!

Before I go into more detail of the 3 days I will give a special thanks to Thomas Jespersen from spiir to crash at his hotel room after a lot of beers sponsored by my awesome consultant Stig from copenhagensoftware.

There were 3 sessions at the preconf

Visual Studio 2013 by Luke Hoban, Microsoft
He came allround the Visual Studio, he talked about the new era of Visual Studio has changed from being single developer focus to be more team based, by adding more client + developer services running in azure.
Then he demoed a lot of "new" stuff in VS 2013.
like:
  • Created simple web project and showed the new way of choosing project type
  • Showed async on the mvc controller
  • Browser link and web essentials how use the browser as our designer.
  • And deployed the website to azure and attach the debugger

F# Applications: From domain model to user interface by Tomas Petricek, PhD student, University of Cambridge
Tomas talked a lot of F#, and I was very curious about this because I never written a single line of F# code before.
He started by being really fundamental by showing a few sites (fsharp.org) to look at when you start out, he also mention that there is a local F# UserGroup starting up in copenhagen. Last he show how to make a Simple application checkout counter. I was pretty amazed by how few lines of code you needed to write in his demo.

ASP.NET MVC & WebAPI alongside AngularJS by Scott Allen, CTO at Medisolv
In the last session Scott showed us how to make a Single Page Application with WebAPI, Angular JS and the Entity Framework 6, and using the new standard MVC 5 template.

After the sessions there were free beers at nørrebro brewery. Henrik my boss, Stig from Copenhagen Software and I started enjoyed a few beers while talking about what presentations.


Stig to the left, Henrik to the right

After the free beer's ended, Henrik went home. Stig and I enjoyed the rest of the evening with a few other guy's with some more beer's, thanks for a great day everybody!




Sunday, January 12, 2014

What does being an MVP means to me.

My MVP lead asked, if I would answer a few questions about being an MVP, and thought of sharing the answers on my blog.

So here it is.

Tell us a little about yourself.

My name is Ronnie, I am a senior .Net developer/Technical Lead and been working at Widex for almost 3 years now. I have played around with .NET since the betas; think it was called “asp.net webmatrix” 2000-2001. My passion for Microsoft technologies slowly grown since then.

What inspired you to be active in the community?

My “Microsoft” community activity started for about 8 years ago, thanks to the umbraco community. What inspired me was the feeling of being part of a family, and there always was a few people willing to help with your problems. The last few year’s motivation has been from TypeScript, Azure and ALM.
Being and MVP inspires me to be even more active spreading my passion of Microsoft Technologies.
It makes me proud to be a MVP, and acknowledge my work in different communities, it's an award I never thought was possible to achieve.

Brag! Tell us about something great you have been working on lately (either community-related or as a technical expert).

Since TypeScript was announced, I have had a lot of focus on that. Start writing a book, and in september I gave a talk “TypeScript kata: the TDD style” presented with Visual studio to Linux/php/opensource beer drinking geek user group (called brewww). We had some heavy discussions - they were not Microsoft fans! Nevertheless, in the end they actually began to see the potential of visual studio, and that it´s free J they will probably have an IDE bitch fight event later this year, I hope they will invite me, so I can convince them all to use visual studio!
The next cool thing that I want to do is making a visual studio extension like ncrunch, just for typescript.

What is, in your opinion, the greatest advantage of being a Microsoft MVP?

To know what the future of Microsoft brings to the table by being involved in the Microsoft product development process by attending the MVP PGI events and the MVP summit. Another great advantage is being part of a new community, and getting new friends that share some of your own passions.      

What would you recommend to people who aspire to be an MVP? 

To be an MVP the most important is to have passion for Microsoft technologies, and use a lot of time in the community by, answer questions, writing books, blogging, teaching, give talks at conferences/user groups or making some new cool products that make Microsoft technologies even better. In my opinion, a good blend of it all, but in the name of your passion to Microsoft Technologies.

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.