You are browsing the archive for Prism.

Avatar of marc

by marc

Prism XE4, Where Art Thou?

April 17, 2013 in Oxygene, Prism, Uncategorized

Ok, so the cat is out of the bag, if a few days ahead of schedule: starting with the upcoming release of XE4, Embarcadero Prism will no longer be part of the RAD Studio SKU, and there will be no “XE4″ branded edition of Prism.

But worry not. As you all know, Prism has been nothing more than a re-branded version of our Oxygene for .NET product — and Oxygene will keep going on, stronger than ever.

In fact, Oxygene has long outgrown its Prism-branded edition, first when we introduced full native support for Java and Android to the language over 18 months ago, and of course with our upcoming support for truly native iOS and Mac apps, shipping next month.

So “Embarcadero Prism” as a product is going away, but the Oxygene language you have come to love and depend on will continue to shine and evolve, as it always has.

What exactly does all of this mean?

We believe that in the end, this change will be a net positive for Oxygene.

When we first started working with Embarcadero in 2008 to bring Oxygene 3.0 into RAD Studio, Embarcadero had a gap left in their lineup with the discontinuation of their ill-fated Delphi for .NET product. Both companies shared a vision of Delphi and Oxygene — then getting branded Delphi Prism — becoming two sides of the same coin: two languages evolving together and influencing each other to push Pascal forward both for CPU-native Windows development and for managed targets.

Over the years, it turned out that this was not happening, and as Embarcadero was shifting their focus to “(CPU-)native, native über alles” and onto FireMonkey, Prism (and with it Oxygene, as i’m going to start referring to it from now on exclusively) became the odd man out — the product that was there, as part of RAD Studio, but no-one liked to talk about, because it did not really fit the vision of the company.

This became clearer as Oxygene evolved.

We added support for Java and (more importably) Android, but Embarcadero had their own (very long term ;) vision of how they wanted to pursue the platform that conflicted with what Oxygene had to offer. As a result, Oxygene was forced into a split personality — with Oxygene for .NET remaining under the Prism umbrella, and Oxygene for Java becoming a separate product (for a while).

At the same time, Embarcadero became less and less interested in actually marketing and promoting the product, and it was being relegated to a “filler” to pad up RAD Studio as a worthwhile product suite.

Things got even more complicated when we started working on “Nougat”, our vision for really and properly bringing Object Pascal and Oxygene onto the (misleadingly named) Objective-C runtime that is the engine behind iOS and Mac. Once again, Embarcadero had different plans for the platform, and what is more, they — understandably — raised the concern that Oxygene for Cocoa would be too direct a competitor to their efforts on iOS (albeit once again our two companies were following two very different visions).

To wrap things up short and sweet, as of right now, Oxygene is finally standing on its own two feet again.

During the five years of partnership, RemObjects Software has always been the sole technical contributor to the core Oxygene product, and having Oxygene “back to ourselves” really just means one thing: that we can, more aggressively and consistently, continue to drive the product on all three target platforms, according to the vision we have for it. And trust me, we have some amazing things planned for 2013 and 2014, with “Nougat”, our Mac and iOS support, only being the tip of the iceberg.

What does this mean for existing customers?

Worry not. We have every eventuality covered.

First of all, if you already bought Oxygene directly from us or one of our reseller (i.e. without an Embarcadero serial number), none of this will affect you at all, you’re already set.

If you’re an Oxygene user from the Embarcadero side of the fence, now more than ever, make sure you register your XE2.x or X3.x serial number with us. This way, we know about you and can take care of you moving forward.

Once you have registered your serial, you can take advantage of our special renewal price for Prism customers and renew to a full Oxygene package licensed directly from RemObjects Software, for only $349. Remember, this not only renews you for future updates to Oxygene for .NET (the product you have now), but it also gives you the Java/Android and Mac/iOS targets, as well!

If you have active software assurance (SA) with Embarcadero that covers Oxygene, that will of course be honored. Up until August (i.e. one year from when XE3 shipped), you will continue to receive the latest updates to Oxygene for .NET from Embarcadero. This will (assuming your SA is still active at the time) include the upcoming major 6.0 release, next month.

Once your current SA expires, renewing it will not include renewed access to Oxygene, but you can use the link above at any time to renew to the full Oxygene package from us. (Note that the current renewal price of $349 is a special offer and will increase slightly once “Nougat” ships next month.)

It’s probably unlikely that you’re buying RAD Studio XE4 “fresh” without already being an existing RAD Studio user, but if you do, i’m afraid you will not receive “Prism XE4″ as part of it. You (and every other Delphi user) can use our special cross-grade offer to purchase a full Oxygene package from us, at $399 (this is also a special offer, and the price will increase slightly once we ship 6.0 next month).

In Summary

As the old saying goes, The King is dead, long live the King! Embarcadero Prism is no more, starting next week, but Oxygene is going stronger than ever.

We, and i personally, are incredibly excited about Oxygene, and about the things we have planned thru-out the rest of the year and beyond. We can’t wait to walk down the road ahead with you.

yours,
marc hoffman
Chief Architect & Oxygene Team Lead
RemObjects Software

Top 10 Reasons to use Platform Native APIs

March 14, 2013 in .NET, Cocoa, Cooper, non-tech, Nougat, Oxygene, Prism

What are native platform APIs? They are the APIs provided by the platform vendor that define the platform. On Android this is the Android SDK. On iOS it is the Cocoa Touch Frameworks. On Windows and Windows Phone it is WinRT and the .NET Framework. There are undocumented APIs, and even calls that circumvent the platform APIs, but they are not considered part of the platform API.

In addition to the native development tool provided by the platform vendor, there are 3rd party development tools providers (such as ourselves) with their own solutions. The 3rd party tools typically either focus on providing a better solution for the specific platform, or sacrifice native platform support with the objective of cross-platform simplicity. There is no reason to sacrifice platform support, as you will see in these top 10 reasons to program to platform native APIs.

Platform Native APIs are Great

Those who programmed MS-DOS applications or the early Windows API no doubt remember what a pain those APIs (or lack of) were to work with. Back then it was great to have a good abstraction to make the platform easier to work with. Today’s platform native APIs encompass all the productivity enhancements that are found in the the best abstractions. Typically, the productivity enhancements that come from additional abstractions are only in the form of familiarity and developer’s resistance to learning a new API and framework. You know things are getting carried away when there is a Java abstraction for developing Windows Phone 8 applications and a .NET abstraction for building Android applications.

The Law of Leaky Abstractions

All non-trivial abstractions, to some degree, are leaky.” If your tool forces you to use some non-trivial abstraction on top of a platform’s API, at some point it will leak – there will be something that the abstraction cannot do, or somewhere the abstraction behaves differently from platform to platform. If you are serious about developing for any platform, you need to understand the platform’s native API. The more non-trivial the abstraction, the less of the platform it can abstract successfully and the more likely you will need to move to the platform native API. If you are going to need to learn the platform API anyway, you might as well start there. No need to learn both the abstraction and the platform API – that is twice as much work.

Native Documentation

Documentation is a lot of work. Good documentation is even more work. On each platform, the platform vendor provides the documentation of the platform along with all the best practices and examples. For each additional level of abstraction that requires another level of documentation to consult. Chances are that the documentation will eventually refer you to the platform API documentation. Wouldn’t it be nice to just start at the ultimate authority and not have to wade through incomplete and outdated layers of documentation?

No Bloatware

If your abstraction adds additional graphic libraries or run-times, your application suffers with bloat. These abstractions replace the functionality already present in the platfrom and make your app bigger, slower to start-up and less responsive at runtime. Some of these add-ons are worthwhile, but if you need to double (or more) the size of your app just to write “hello world”, then you are probably using the wrong solution.

Rapid Release Cycle

When a platform vendor releases a new API you want to be able to take advantage of those features right away. It may surface new hardware features, or just introduce better ways of doing things. If you are forced to use an abstraction, you need to wait for the 3rd party to update their abstraction. This may be fairly quick, or you may have to wait for their release cycle, which, depending on where they are in development, could mean the release after the next. No matter how fast a vendor has been in the past at updating their abstraction library, a point will come where they are not updated when you need them.

Support for Platform Deviations

If a hardware vendor comes out with their own SDK extensions or variations on a platform, they will provide their support at the level of the platform API. If you are stuck behind an abstraction, you will not have access. The openness of Android is a great example with extensions like Google TV, Epsion Moverio, Ouya, and Google Glass. If you are interested in cutting edge platforms like these, you need a development tool that doesn’t lock you behind an abstraction.

Native User Experience

Each platform has a typical user experience. This comes from the native platform user interface widgets and the way they behave. It also comes from design guidelines provided in the platform documentation. If you are using an abstraction for your user interface, even one that tries to look and act like the native one, it will get in the way of this native user experience. When it comes to user experience, close isn’t close enough. Using the native platform user interface controls is the only way to give your users the experience they expect.

Less Points of Failure

Everything always works great in the demonstrations, but the more layers of interoperability and wrappers required to make your application run, the more points of failure. When you develop for the platform API directly, you are not handicapping yourself with black boxes or other points of failure for your app. The first time you find yourself debugging into that abstraction layer, you will really wonder if it was worthwhile to shackle yourself with it.

Maximum Developer Flexibility

Platform APIs are huge. In the process of creating a wrapper, choices are made to simplify or eliminate options. These simplifications and eliminations result in less flexibility for the developer. Tying a project to a subset of the features of the platform reduces what you can do with your project. Don’t tie your hands!

3rd Party Support

The majority of 3rd party components and books are going to support the platform’s API. The further you are from that, the less support you are going to have. Want to use a cool 3rd party custom control? Hope they port it to your favorite framework. And what are the odds of a book about the specific features of the platform you want to explore covering it via your specific pair of shackles?

Summary

Cross-platform abstractions are only going to get in your way and tie your hands. Any benefit in getting you up to speed faster will be lost in the long term when you hit the rough edges of the abstraction. That is the reason Oxygene is designed to use the platform native APIs directly. There is no forced or complex abstraction to get in your way of using the platform and making the best app possible.

Avatar of marc

by marc

Creating a Turn-Based Game for iOS: Nougat Tic-Tac-Toe

March 11, 2013 in iOS, iPhone, non-tech, Nougat, Oxygene, Prism, Visual Studio, WWDC, Xcode

Over the past couple of weeks, i have been working on a new sample project for Oxygene “Nougat” on the side. After having gotten Browse500 into the App Store in January and showing how to reimplement a simple native UIKit control from Objective-C in Nougat last month, i wanted to create another example that illustrates the benefits of how Nougat interacts directly with the native APIs, and i picked a technology i knew nothing about at all to do so: Game Center.

I’m not a big gamer; i don’t find myself playing games much, and i have certainly never written one before, so this was a great opportunity to explore something new.

For those of you not familiar with it, Game Center is a technology Apple ships in iOS (and now also Mac OS X) that allows for games to interact across the network to create multi-player games, and to keep track of achievements. Game Center is not about graphics, or game UI, or anything of the sort (there’s other frameworks for that), it’s only for bringing players together.

I decided to create a simple turn-by-turn game, that is, a game where multiple players (in this case two) can interact, but only one player is active at a given time. Once a player has made their move, it’s the next player’s turn. To keep things simple, i picked a game that everybody knows and that is dead simple to implement, game playing wise: Tic Tac Toe. This way, having to explain the game itself won’t get in the way of the sample code.

To start with, i had to dig myself into the Game Center documentation and i watched a couple of videos on Turn-by-Turn gaming from WWDC 2011 (sessions i didn’t attend at the time). As it turns out, the API for interacting with Game Center for such a game is surprisingly easy and straightforward, and i was up and coding in no time.

Before we get started looking at the code, let’s look at the prerequisites:

  • Here’s the amount of effort anyone from the Oxygene team had spent on thinking about or working on making GameKit (the framework for interacting with Game Center) available to Nougat, before i started this endeavor: 0. Nada. Nil.

  • Here’s the amount of legwork i had to do before i could work with the GameKit APIs, just like every other Cocoa developer would: i added a reference to GameKit to my project. Done.

That’s it. No begging someone to translate header files, or waiting for someone to create a crappy abstraction wrapper class. Add a reference, and use the APIs as Apple intended them — that’s the way development should be.

The Code

Let’s dive into the code.

First of all, the full code of Tic-Tac-Toe is included in the latest Nougat beta, and it’s also available in my Github account for anyone to explore.

There’s really three separate parts that are of interest as a sample project in this app:

  1. The GameKit integration
  2. The game board, implemented as a custom UIControl
  3. The computer player algorithm, generously provided by my good friend and long-time Oxygene user, Jeremy Knowles.

Let’s look at GameKit first.

Working with GameKit

There’s four main classes or concepts that you will work with for GameKit.

The first is the local player, a singleton object that can be obtained via a call to GKLocalPlayer.localPlayer. This objects provides the game with information about the local player — most importantly their ID, and whether the local player is in fact registered and authenticated with Game Center or not. If the player is not set up for Game Center, Tic Tac Toe will simply disable the appropriate UI and just allow local vs. computer game play (although it would be possibly for a game to provide a signup UI, if so desired).

Next is the GKTurnBasedMatchmakerViewController, which provides access to the standard GameCenter UI. It gives the user access to any and all games they might already have going on, as well as the chance to start a new game. In Tic-Tac-Toe, i make this UI available via a button in the navigation bar, and all that’s needed to show the view is code like the following:

var request := new GKMatchRequest;
request.minPlayers := 2;
request.maxPlayers := 2;
 
var mmvc := new GKTurnBasedMatchmakerViewController withMatchRequest(request);
mmvc.turnBasedMatchmakerDelegate := self;
mmvc.showExistingMatches := true;
presentViewController(mmvc) animated(true) completion(nil);

This code brings up the Game Center UI, with the list of games (if any) or straight with the “Start New Game” (if not). Via the GKMatchRequest, we force the number of players to exactly two. (Game Center itself allows games for up to 16 players):

Tic Tac Toe Game Center

The way Game Center works for starting new games is that it lets you either invite a known friend who also plays the game or — much more interestingly — auto-match you with another random player. One thing that’s cool is that after starting a game, it will always be your turn — you will either be thrown into another game that was started earlier by a different user, or you will get to start a fresh game, depending on what games are currently live and waiting for players. If you start a fresh game, you get to make your first move, and then and only then does Game Center go out and try to find someone for you to play with.

Going back to the code level, what we are looking out for is a callback on the turnBasedMatchmakerDelegate that we assigned above. Our root view controller class implements some 4 methods from the IGKTurnBasedMatchmakerViewControllerDelegate interface, and the match-maker view controller will call us back on these when interesting things happen. This is a very common pattern in Cocoa, and is how the platform handles “events”.

In particular, the callback we care about for starting a new game is:

method turnBasedMatchmakerViewController(aViewController: GKTurnBasedMatchmakerViewController) 
       didFindMatch(aMatch: GKTurnBasedMatch);

This method actually gets called any time the user picks a game in the Game Center UI — whether they are starting a new game, or selecting an existing game. This is neat, because it means we can leave all the game management to GameKit, and don’t need to keep track of ongoing games ourselves.

This callback receives the third important class, a GKTurnBasedMatch. “All” we need to do when this method is called is load the passed match as the active game. In the Tic-Tac-Toe app, we do this by calling our own loadCurrentMatch() method, which does all the heavy lifting.

Every match contains a binary blob in the matchData property that describes the current game state. The content of this binary blob is entirely up to our game, but we can use it to store up to 4KB of data, and this data will automatically be passed between all the participants as they take their turns. In turn, our Game will read the data, let the active player make their move, and then store the updated game state, as we will see in a few moments.

Loading a Game

Loading a game is done with two method calls, first, a a small helper function loads the binary data into an NSDictionary, and then we ask the board to load its game state from that dictionary (the idea being that in a future version, our game might store additional info in the dictionary that the board does not care about — that’s why i decoupled the data the Board class reads/writes from the actual binary format).

var lDictionary := dictionaryFromData(fCurrentMatch.matchData);
fBoard.loadFromNSDictionary(lDictionary,);

The same happens in reverse when we later save the updated game state. Of course, when a new game is first started, there will be no data present (GameKit doesn’t know anything about how our game data is structured, after all), so our code will need to be prepared to find an empty NSData object in matchData.

The second part, in addition to loading the board data, is determining the active player (if any) and enabling the game play. Each GKTurnBasedMatch has a currentParticipant property of type GKTurnBasedParticipant which links to the current player (it also has a participants array that contains all (two) players). We can compare this participant’s playerID to that of the local player.

If they match, it’s the local player’s turn, so we display “your turn”, and enable the board. If they don’t match, it’s either the remote players’ turn (if currentParticipant is assigned), or the game has finished. In either case, we show the proper status message, and leave the board disabled.

Playing a Turn

If it was the local player’s turn and we enabled the board, we’re done for now, and await the player to make a move. This all happens inside the Board class, which will call us back via the board() playerDidSelectGridIndex() method, once the player made their move.

What we need to do then is determine the game status (the player might have made a winning move, for example), re-encode the game status, and pass control back to game center.

There are three scenarios we need to cover:

  1. The player has won by managing to place 3 “X” markers in a row.
  2. The board has been filled (and the game just tied).
  3. Any other case — the game is still on.

In the two game-over scenarios, we set the appropriate status (Won/Lost/Tied) on each of the game participants, and then call endMatchInTurnWithMatchData() completionHandler() to tell Game Center that the match has ended as part of the player taking his turn.

In the other case, we call endTurnWithNextParticipant() matchData() completionHandler() to let Game Center know that the local player is done, and game play can move to the next player.

In either case, we will pass the updated information on what our game board looks like now, via the matchData parameter.

It is worth noting that it’s up to our game to tell Game Center “who’s next”. In our case, that decision is trivial (it’s the player that’s not the local player), but Game Center allows for turns to be passed in arbitrary ways, depending on your game’s needs — it doesn’t always have to go around the (virtual) table.

Once we called either of the above fund methods, it’s no longer our turn, and all we can do is wait for the remote player to make a move.

Handing Remote Turns

Of course, eventually the remote player will make their move, and GameKit provides a second delegate interface for this case, IGKTurnBasedEventHandlerDelegate, which we have hooked up to the GKTurnBasedEventHandler.sharedTurnBasedEventHandler singleton.

What will happen once the remote player moved is that Game Center will show a notification banner to the user, saying something along the lines of “It’s Your Turn”, and play that annoying fanfare sound. When and only when the user taps that notification, will we receive a call to the

method handleTurnEventForMatch(aMatch: GKTurnBasedMatch) 
       didBecomeActive(didBecomeActive: Boolean);

method to let our application know that something happened. This is nice, because it saves us from worrying about showing any UI to the user to ask if they, say, want to switch from the game they are currently looking at to the one that has received a response. When we get the callback, we already know that the user has decided to view the game in question.

So all we really need to do is the same as we did in … didFindMatch() above: load the passed match and enable the board, if appropriate.

House Keeping

This basically takes care of all the Game Center interaction needed for our simple game. There’s a few more minor items that i won’t go into detail for this post; for example, there’s a callback you will want to handle to quit games if the user selects to delete them in the Game Center UI. There also are APIs for providing a custom UI for the list of games, instead of relying on the standard UI provided by Game Center (all Tic-Tac-Toe does with this is adjust the Game Center button to either read “Games” or “Start”, depending on whether there are any games ongoing or not).

In Tic-Tac-Toe, all the GameKit interaction is located in RootViewController.pas, which is only ~500 lines of code total, so it should give you a good overview and starting point for your own game.

Caveats

There are a couple of caveats you might want to be aware of when working with Game Center games; these had me stumped for a short while, so hopefully pointing them out here will help save you frustration:

  • In order for Game Center to work, your app needs to be registered on iTunes Connect with the appropriate app ID. Even for the simulator. This is counter-intuitive if you are used to App Store development, because normally you don’t have to go to iTunes Connect to register your app until you’re (almost) ready to go and submit it. For Game Center, you need to register it first. If you don’t, GKTurnBasedMatchmakerViewController will just come up looking all empty and dysfunctional.

  • As best as i can tell, you must specify “gamekit” in the UIRequiredDeviceCapabilities section of your Info.plist file for things to work properly.

  • Finally, and most importantly, notifications do not work in the Simulator. If you worked with Push Notifications before, this might not come as much of a surprise, but realize that callbacks such as handleTurnEventForMatch() … will never, ever be called on the Simulator — which seriously will impact how you test game interaction. (In essence, i found the only way to work around this was to manually invoke the GKTurnBasedMatchmakerViewController and re-select the active game to trigger the app to reload the game data and detect the changed game state.)

The Game Board

The second piece of interest in the game is the Board class, which implements all the UI of the game as a really simply UIControl descendant.

The implementation is fairly straight-forward; the class maintains a 3×3 array to keep track of which player has claimed a particular spot on the game board, and in which move (by keeping track of the move number, the game can show different versions of their “X” and “O” markers, making the board look more dynamic).

The begin/continue/endTrackingWithTouch() withEvent() methods are overridden to keep track of — you guessed it — the user’s finger, and they use animations to fade the user’s game piece in and out, and to move it to the next appropriate spot, as the finger moves. (You’ll notice that while the user can move their finger all over the board, the game piece will always “snap” to a fixed position in the closest matching grid spot with a smooth animation.)

All the game pieces (the grid, the “X” and “O” game pieces, etc.) are pre-created images, and the game pieces come in 5 versions (since 5 is the maximum number of moves any one player can make).

The entire Board class is really straightforward and there isn’t much worth covering here that won’t be clear from looking at the code. Worth pointing out is the makeComputerMove method, which invokes Jeremy’s mean ComputerPlayer class, which is used when not playing in Game Center mode.

Tic Tac Toe Board

Summary

I think that’s it (and it’s probably enough ;). Make sure to check out the code on GitHub, and let me know what you think!

Oh, and: even though the code is written in Oxygene, as are the code snippets here, i hope the general description of how to work with GameKit will also be useful to “regular” Cocoa developers using Objective-C. Another nice thing about Oxygene working directly against the standard Cocoa APIs without any abstractions!

Avatar of marc

by marc

Custom iOS Controls in Oxygene “Nougat”

February 22, 2013 in Cocoa, iOS, Nougat, Oxygene, Prism, Visual Studio, Xcode

A week or so back, Yari D’areglia had an excellent tutorial on his blog on How to build a custom control in iOS that gave a nice rundown of some of the tasks involved, including handling touches, drawing some non-trivial custom UI, and returning events to the application via the target/action pattern.

While Oxygene “Nougat” can of course use any such controls directly and without having to convert or wrap them, i thought it would be fun to try and port the code over to Nougat and see what it looks like (and what kind, if any, challenges would be involved).

We don’t have Oxidizer support for Objective-C yet, so i did this manually, but it was still a very straight-forward process, and below are a few notes:

  • It turns out the new “Auto-Fix” for = vs. := assignments that we are shipping in the February release (which RTMs today) is a huge time saver. Just leave all the “=” in place, and the compiler will fix them for you when you hit build. This is new since i last converted code a few weeks back, and a much appreciated improvement.

  • There’s really only two “repetitive” tasks i found myself doing a lot to convert Obj-C to pascal: (a) changing Objective-C style “[]” method calls to use regular Oxygene “.” or “:” operators and (b) replacing type names with “var” in local variable declarations, such as CGpoint centerPoint = … to simply var centerPoint….

  • There were a couple of C macros used in the original code, which translated nicely into inline methods — a new feature in the Oxygene language for version 6.0.

All in all, i spent maybe 30 minutes last night converting and then tweaking/cleaning the code, and then the control and surrounding sample app was working perfectly (i also found a couple of new compiler bugs — remember Nougat is still beta — which always makes Carlo happy. When i woke up this morning, they were already fixed ;).

 

If you’re at all interested in creating your own controls for iOS (whether in Nougat or in Objective-C), i recommend to check out Yari D’areglia’s post. His original code can be found on GitHub, as can be my ported version.

 

Screenshot

Oxygene Gets Big(Integers)

January 18, 2013 in .NET, Oxygene, Prism

A huge part of cryptography is big numbers. Really big numbers. For example, the SHA-256 cryptographic hash produces a 256-bit thumbprint of any data you give it. Exactly how big is 256-bits?

  • 8 bits = 256
  • 16 bits = 65536
  • 32 bits = 4294967296
  • 64 bits = 1.84467E+19
  • 128 bits = 3.40282E+38
  • 256 bits = 1.15792E+77

So the maximum value for a 256-bit unsigned integer is:

115 792 089 237 316 195 423 570 985 008 687 907 853 269 984 665 640 564 039 457 584 007 913 129 639 936

Unfortunately most programming languages only have 32-bit or at most 64-bit numbers available. So in order to store large numbers like these they require you to make the awkward move to byte arrays or some other complex construct. That isn’t the case with Oxygene.

Oxygene has the BigInteger datatype. BigInteger is an arbitrary length signed integer, so it can be as big as you have memory for, and it can be used like a normal integer.

To include BigInteger support you just need to add a reference to the System.Numerics.dll assembly (part of the .NET 4.0 Framework), add System.Numerics to your uses clause, and you are good to go. Now you can use BigIntegers just like any other data type.

Behind the scenes, BigInteger is actually an object with methods, properties, constructors and operators to make it easier to work with BigIntegers. So instead of using Math.Abs use BigInteger.Abs.

You are probably wondering “What does all of this have to do with cryptography?”. I’m glad you asked. Here is a method to calculate a SHA-256 on a string and return the value as a BigInteger

class method Hash.Sha256(text: String): BigInteger;
begin
  using hash256: SHA256Managed := new SHA256Managed() do begin
    var bytes := Encoding.UTF8.GetBytes(text);
    var hash := hash256.ComputeHash(bytes);
    exit new BigInteger(hash);
  end;
end;

The ComputeHash method on the SHA256Managed object returns a byte array containing the value of the hash. Luckily there is an optional constructor for BigInteger that takes a byte array as a parameter. This creates a BigInteger from the value of the byte array.

Another great place to use BigIntegers is with the cryptographic random number generator. Unlike the random number generator you are used to, the one provided by the RNGCryptoServiceProvider is cryptographically secure – meaning future values cannot be predicted. The RNGCryptoServiceProvider will generate a sequence of bytes of any size, which makes BigIntegers another great fit.

About creating a BigInteger from a byte array: Since a BigInteger is signed, this is just about as likely to result in a negative as a positive number. If you always want a positive number, you can append a zero byte to the end of the byte array, we will do that for our random number routine.

This method will return a BigInteger of the number of bytes specified.

class method Rnd.BigRnd(bytes: Cardinal): BigInteger;
begin
  using rng := new RNGCryptoServiceProvider do begin
    var tokens := new Byte[bytes + 1]; // one extra byte for the sign
    rng.GetBytes(tokens);
    tokens[bytes] := 0; // keep the result positive
    result := new BigInteger(tokens);
  end;
end;

Take a look at the code and see what sort of uses you can find for really big integers. BigInteger support was introduced a while ago for Oxygene for .NET – yet another feature you probably didn’t know you had.

Avatar of marc

by marc

Working with User Interface files in Oxygene “Nougat”

January 2, 2013 in Cocoa, iOS, Mac, Nougat, Oxygene, Prism, Visual Studio, Xcode

In this article, i want to talk a bit about working with user interfaces in Oxygene Nougat.

As you know, Nougat is a native compiler for the Objective-C runtime, meaning that it works directly with the classes provided by Apple’s Cocoa and Cocoa Touch frameworks. This extends from low-level classes such as NSString or NSArray to the high-level visual components based around NSView (Mac) and UIView (iOS).

One common way for Mac and (especially) iOS apps to work with UI is to simply create the necessary views and controls that make up an app’s UI from code. But sooner or later, especially when dealing with more complex or sophisticated user interfaces, you will want to use the visual designer. This works on the same principles, whether you are using Xcode/Objective-C or Nougat.

Mac and iOS interfaces are designed in Interface Builder, which as of version 4 is directly integrated into the Xcode IDE, and when working with Nougat, that is where you will work with your interfaces, getting the same experience and the same power and flexibility of UI design that developers using Objective-C get, as well.

There are two file formats used for designing UI on Apple’s platform — the older XIB format and the newer (and iOS-only) storyboard format. The principles for dealing with these files are similar, but for the topic of this article, we’ll focus on XIB files, as those apply to both Mac and iOS development. In a future article, i will go into some more details specific to storyboards.

Background: What are XIB Files?

So what are XIB files? From the point of view of the UI designer, XIB files contain the views or windows that you design in Interface Builder — the controls, their layout and properties, and their connections to your code.

It is important to understand that on a technical level, XIB files are stored object graphs. That means that an XIB file, essentially, is a hierarchical set of objects descriptions. When an XIB file gets loaded at runtime, all the objects defined in the XIB file get instantiated, configured, and connected as described in the XIB.

These objects can be a combination of standard framework classes (such as NSView/UIView, NSButton/UIButton, etc), classes from third party libraries, or even classes defined in your own application code. When the Cocoa runtime loads an XIB, it goes thru the list one by one, looks for the classes with the appropriate names and news up the necessary objects.

Each XIB file also knows about a special object called the “File’s Owner”. This object will not be created when the XIB is loaded. Rather, the object that initiated the loading of the XIB file will take the place of the File’s Owner within the XIB’s object graph — including any connections and references to it. We will see how that is useful and important, soon.

Loading up an XIB

When and how do XIB files (or storyboards) get loaded? There are several possibilities:

 

NSMainNibFile

If your Info.plist contains an NSMainNibFile entry, the Cocoa runtime will automatically load up that XIB as your application starts up. The global NSApplication/UIApplication instance will become File’s Owner of the XIB, and every object in your XIB will be instantiated.

This mode is common for Mac applications, and in fact you can see it in action in our Cocoa Application template(s). You probably noticed that (aside from the startup code in Program.pas) the project contains an AppDelegate class that is usually used as the “launching point” for your application’s own code.

How does this AppDelegate class get instantiated? Easy: If you own the MainMenu.xib file in Xcode (the xib that is specified to be the NSMainNibFile in Info.plist), you see that — among other elements — it contains an AppDelegate item. This is your own AppDelegate class.

initWithNib:*

For simple applications, you can get away with just putting all your stuff into MainMenu.xib, but as applications get more complex, that’s a bad idea, not only because — as indicated above — when an XIB is loaded, all objects referenced in it are created. If your application contains dozens of windows or views, you don’t usually want all of those to be loaded up as your application starts.

Instead, it is common practice to pair individual XIBs for each view or window XIB with a matching ViewController or WindowController class — a practice that you will see in just about all the iOS project templates, and also in the *Controller item templates we provide with Nougat.

How does this work?

Simple: your application will define a custom class, usually descended from UIViewController (or NSViewController/NSWindowController) where you will put all the application logic for that view or window. As far as your app is concerned, this class is your implementation for that particular view (or window — for simplicity reasons i’ll stick to talking about iOS Views for now, but the same concepts apply for OS X views and windows).

In the initializer for your view controller, you will ask the base class to load up the XIB file that backs your view, for example by calling

self := inherited initWithNib('MyViewController') bundle(nil);

This essentially tells the base class to initialize it by loading MyViewController.xib (from the main application bundle) and creating all the objects defined in it.

So all those objects get loaded up, but how do you then get access to them from your code? Simple: remember when i said above that the object loading the XIB becomes the File’s Owner? When you load an XIB using the initWithNib() call, your view controller class becomes the File’s Owner — and any connections you set up in the XIB between the File’s Owner and the other elements in your XIB will be connected to your view controller class.

Connections

Did i say connections? So how does this work?

Easy, really. XIB files know about two basic kinds of connections between objects: Outlets and Actions.

You can think of outlets as references to other objects. If your view controller class has a property of type UIButton, and your XIB file contains a UIButton, that’s a match made in heaven. You can just Ctrl-drag the button onto the File’s Owner (or vice versa) in the XIB to hook them up, and now you have access to the UIButton from your code, because as the XIB gets loaded and the UIButton gets created, it gets hooked up to your property automatically.

Actions, you may have guessed, can be thought of as events. If something happens with the objects in the XIB (such as a button being tapped), they send out events. Just as above, if your view controller exposes a method with the right signature (that is, any method with exactly one parameter of type “id” or a concrete class), you can Ctrl-drag it into your XIB file to hook them up — and when the event triggers, that method is called.

Of course outlets and actions can be hooked up between any two objects inside your XIB, not just with the view controller. For example, you can cause an action on one control to trigger a method on a different control.

Ok, so how does the XIB designer in Xcode know about the methods and properties on your view controller (or other classes)? Magic! As you write your classes, Nougat will automatically* update the XIB and Storyboard files, behind the scenes, with information about all the relevant classes and their properties and methods — that is any property marked “[IBOutlet]” and any method marked “[IBAction]“. As you work on your XIB file in Xcode, it sees this information, and makes the connections available.

If you need to expose a new control to your code or want to hook up a new event, simply add a new property or method to your code, and that’s it.

Let Me See This in Action

For this example, i’ve created a new “UIViewController with XIB” from the template. I have then added the following items to the “MyViewController” class:

property myButton: UIButton;
property myLabel: UILabel;
method buttonTapped(aSender: id);

The following screenshot explores the XIB (and storybook) designer in Xcode:

Figure 1: On the left side of the window, you see a hierarchical view of all the objects in the XIB — this includes all visual objects (in this case just the one UIView for now, but also other objects such as the File’s Owner).

On the right side, the “Utilities View” has the “Identity Inspector” pane activated, showing details about the selected object (the File’s Owner). Note that the XIB designer knows that File’s Owner is a “MyViewController”. It got that information from the template – but this is editable, so you can just type in or select the right class name. Of course it should match the class that is loading this XIB at runtime.

Figure 1

Figure 2: We have dropped a couple of controls onto the view — you can see them both visually and in the hierarchy on the left. The right pane has been switched over to the “Connections Inspector” tab, which shows all the connections available on our File’s Owner. Among them, you see our two properties and the method. There’s also a “view” property (defined by the UIViewController base class), already connected to the root view.

Figure 2

Figure 3: Click and drag from the little circle right of the “myButton” name to the button to make a connection to the UIButton. (You can drag to the control on the design surface or to the “Button — Tap Me!” item in the hierarchy.)

Let go when you are over the button, and the connection is made. If you were to go and build your app now, the myButton property would give you access to the button from code.

Figure 3

Figure 4: You can also drag from the hierarchy view to a control. When you let go, the XIB designer will present a list of all properties that match — in this case the UILabel qualifies both for “myLabel”, and for the “view” property (because UILabel descends from UIView).

Figure 4

Figure 5: Connection actions work the same way. You can Ctrl-drag from the control to the receiver (here the File’s Owner) to connect the default action of that control (in this case, the button tap) to a method. As you can see, the Connections Inspector also shows a complete list of all actions that can originate from the control, so you can — if needed — assign them all to individual methods.

Figure 5

Now all that’s left to do is maybe write an implementation for “buttonTapped” such as this:

method MyViewController.buttonTapped(aSender: id);
begin
  myLabel.text := myButton.titleLabel.text;
end;

to see both actions and outlet access in — pun not intended — action.

Terminology: XIB vs. NIB?

In the text above, i talk about XIB files, but the method names all mention NIBs. What’s up with that?

XIBs are a newer, XML based format that is used for the UI at design time. When you compile your app, the XIB files are converted to binary NIB files for you, and those binary versions of the files are embedded into your app. All the APIs working with these files predate the new format (and, at runtime, only work with the older NIB format), that’s why all the method names refer to NIB, not XIB. When you pass around names, you never need to (or should) specify the file extension anyway, so this is a distinction that you can largely ignore (unless you want to go spelunking into your .app bundle).

What’s “First Responder”?

Similar to File’s Owner, “First Responder” is another placeholder object exposed in the XIB file that has special meaning. The First Responder is not a concrete object, but essentially refers to “the first object that has focus that can handle this”.

By connecting actions to the First Responder, you can have them dynamically be sent to different parts of your application, depending on the state your app is in. A good example is the “Edit|Copy” menu in a Mac application. If a text field has focus, you would expect the Copy command to apply to the content of that text field. If a different control has focus, different content would be copied. By connecting the menu’s action to the First Responder’s “copy:” method, Cocoa will take care of calling “copy()” on whatever control or view has focus — in fact, all you need to do to make Copy/Paste work with your own custom view would be to implement the corresponding methods, and they would get called if your view has focus as the user invoked the menu item (or Cmd-C keyboard shortcut).

Summary

I hope this gave you a quick introduction to XIB files and how they work. A good 95% of the content of this article is not really specific to Nougat; the same concepts and techniques apply to working on XIB files with Objective-C — that’s by design, because Nougat is a true first class citizen on the Cocoa frameworks and Objective-C runtime.

Footnotes

(* in the current beta drop, this update does not happen automatically yet. You can right-click your .XIB or .storyboard file in Solution Explorer and choose the “Sync XIB”/”Sync Storyboard” to trigger an update.)

Avatar of marc

by marc

Using RemObjects SDK and Data Abstract with Oxygene Nougat.

December 25, 2012 in Cocoa, iOS, Mac, Nougat, Prism, ROFX, Visual Studio, Xcode

Nougat is, of course, designed to work with any existing Objective-C libraries out there, because it directly consumes and generates code for the Objective-C runtime. As such, it should come as no surprise that Nougat is ready to use RemObjects SDK and Data Abstract for Xcode, out of the box.

That said, with the new Alpha builds of RemObjects SDK and Data Abstract that we shipped on friday (build .1069), we have made a few improvements that make it even easier to get started with RO/DA in Nougat. These are three-fold:

Read-to-Use .fx files

Unlike .NET and Java, Cocoa libraries do not include easy to parse metadata for compilers to consume. Instead, it depends on .h files to define the available APIs — which is fine when consuming the libraries from a C compiler. Because .h files are slow and complicated to parse, Nougat introduces an intermediary format in the form of .fx files. You can think of an .fx file as “pre-compiled headers” file for a given framework or library; a set of metadata that represents all the information expressed in the framework’s .h files, but encoded in a way that it is easy and quick for the Oxygene compiler (and IDE toolchain) to process, when compiling, driving Code Completion etc.

While Nougat comes with the necessary tools to generate .fx files for any of your favorite third party libraries (and of course ships with .fx files for the supported base SDKs), that is an extra step we want to alleviate, so the new build of RODA/Xcode includes .fx file for those libraries out of the box. After installation, you will find the files next to the corresponding binaries in ./Bin.

All you need to do to use the SDK or Data Abstract from Nougat is to go to “Add Reference”, select the .fx file for your platform (i.e. OS X or iOS) to add a reference. That’s it.

libDA.fx Reference

From the .fx, Nougat will automatically know about all the types in the RO/DA library, and will take care of getting the static library and any dependencies linked in.

Static Libraries for OS X

In the past, RODA/Xcode included precompiled binaries in the form of a framework for OS X and static libraries for iOS. Frameworks are easier to deal with in Xcode, because they combine a binary with its accompanying header files, which is why we chose to ship OS X binaries as a framework. iOS does not support the framework format for third party libraries, so the choice there was easy: static libraries are the only option.

For Nougat, the benefits of a framework (on OS X) are diminished, because metadata is provided in the .fx file anyways, so a static library is just as easy to deal with, and has fewer files involved. For that reason, we have added a static library version of RODA/OS X to the product (in addition to the Framework). Xcode developers can choose to use either version, depending on their preferences (the static library has the benefit of being linkable straight into the executable, which is nice if you’re creating command line tools that use RO/DA); Nougat developers will mostly want to use the new static library alongside its .fx file.

CodeGen for Nougat

For pure Data Abstract use, you’re pretty much all set with the above, but if you’re building custom RemObjects SDK services that you want to talk to, there’s one more step missing: Interface code.

Talking to RO services depends on having strongly typed interfaces generated for your local proxy classes and any complex types you are passing back and forth between the client and the server — and until last week, RO/Xcode generated this code in Objective-C only.

That was not a complete showstopper for Nougat. Remember, Nougat can use any Objective-C library, so you could compile those files using Xcode and the use them from Nougat (in fact, that’s what i’ve been doing with for small RODA project i have been working on over the past few weeks). But that’s not ideal, of course.

The new alpha now includes native Nougat CodeGen for your services, so you can generate an Interface .pas file and add it straight to your Nougat project — as it should be.

The new CodeGen is exposed in three places:

  1. Of course the codegen2.exe command line utility has been updated, so if you generate code from the command line, you can use the /lang:nougat option to have interface files written for Nougat.

  2. Service Builder has also been expanded to support Nougat alongside all the other languages (that menu is getting mighty big!):

Service Builder

  1. Finally, we also added Nougat CodeGen to our rodl2objc.app on the Mac (which is now really becoming overdue for a rename ;). While we were at it, we also revamped the UI for this tool a bit to make it (simple as it is) nicer to use, and look at:

rodl2objc

(and as the beta progresses, CodeGen will also be available directly inside the Visual Studio IDE, as well)

So with that you should be all set to build your first great client application for the Mac or iOS, using RemObjects SDK/Data Abstract and Oxygene “Nougat” over the holidays ;)

Let us know how it all works out!

yours,
marc

Avatar of marc

by marc

Oxygene “Nougat” BETA 2 is out!

December 3, 2012 in iOS, Mac, Nougat, Oxygene, Prism, Visual Studio

On Friday, we shipped BETA 2 of Oxygene “Nougat“, the next major platform for our Oxygene language (in case you have missed it or have been living under a rock, Nougat is “Oxygene for Cocoa” and brings your favorite programming language to native Mac and iOS development. You can read more about it here and in my previous blog posts).

Jim also recently spent some time on a great “Oxygene Overview” video that went live today and gives a first peek at Nougat, too.


 

It’s been about 8 weeks since we shipped BETA 1 (and we shipped updated builds to testers more or less weekly since then), and the team has been really busy and made great progress on all fronts. BETA 1 was a very early look at the product — it was still very rough, the “this is what you need to know to get started” list was way long, and many things did not (by design) work yet. But we wanted to let the early adopters get started, and we’ve gotten great feedback for this first part of the beta cycle.

BETA 2, out now with build .1139, is a lot more robust, should provide a fairly decent “out of the box” experience to get started, and — most importantly — sees most core functionality working decently.

BETA 2 supports running and (still limited) debugging of Mac apps (Cocoa and console) and iOS apps on both the Simulator and actual devices. BETA 2 has fully integrated the deployment toolchain, so that with the press of a single key (F5, a.k.a. “Start”), your app gets compiled, linked, packed up, code signed, and uploaded to your device. The compiler has been vastly improved in BETA 2, with lots of bugs fixed and lots of features and improvements all thru-out; the corresponding IDE experience has improved as well, for example with code completion and related editor smarts fully understanding the new “multi-part” method name syntax, everywhere.

Of course we still have miles and miles to go before we reach RTM. As promised from the get-go, we are shooting for a release of “1.0″ (or rather “6.0″, as it may be) in the “first half of 2013″. Now, we strongly plan for that to not mean “on June 30″ (we’re not Apple ;), but we are taking our time to get everything right, and we do still have a good 5-6 months ahead of ourselves in terms of getting Nougat to final.

But, we also know that you are anxious to get started, and a lot of you have been holding off jumping into the dangerous waters with BETA 1. But if you are at all adventurous and inclined to live on the edge a bit, BETA 2 (and its continuing semi-weekly updates) is as good a point to get your feet wet as any.

So what are you waiting for? Assuming you have already ordered your copy of Oxygene, head over to beta.remobjects.com to grab your copy of “Nougat” BETA 2 now! Make sure to check out my “Getting Started” post, as well.

(If you don’t have Visual Studio 2012 installed yet, grab the latest Oxygene for .NET or Java installer from here first, and then install the Nougat beta on top (this will upgrade all three editions to the latest bits)).

Also, don’t forget to let us know what you think — leave your comments here, or join the discussion in our private beta forum at connect.remobjects.com/categories/nougat-beta.

Yours,
marc

Free issue of Blaise Pascal magazine to registered users

November 5, 2012 in Guest Post, Java, Oxygene, Prism

I must have missed this one being announced, but registered users of XE, XE2 and XE3 products can pull down a free copy of Blaise Pascal, the magazine for all things Pascal-based.

Details are on this edn post by Tim DelChiaro and you can pull down the PDF magazine from Code Central.

The free issue, Issue 24, runs to 120 pages and has a number of articles from notable authors (such as Cary Jensen, Bob Swart and Bruno Fierens) on a variety of subjects including FireMonkey 2, Smart Mobile Studio, HTML 5, Delphi XE3 Styles, Delphi XE3 helper types, and interviews with various industry luminaries, including Marco Cantu, Mike Rozlog, marc hoffman and David I.

Also in the issue is my second article on Oxygene for Java: Supporting new android features in old android versions with Oxygene.

Download the magazine – I hope you like the contents!

Windows Store Development with Oxygene

November 1, 2012 in .NET, Metro, Oxygene, Prism, Windows

When Microsoft released the Visual Studio 2012 Shell, support for building Windows Store apps (formerly known as Metro apps) was missing. This certainly frustrates Windows Store Development with Oxygene which ships with the Shell.

Fortunately I’ve found a work-around to this annoying omission. Simply install Visual Studio 2012 Express for Windows 8 (free download) and then install (or re-install) Oxygene for .NET. This activates the support for WinRT templates and the Modern UI designers in the Shell. After that you can use the WinRT and Modern UI designers in the Shell with Oxygene for .NET.

The Visual Studio Shell and the Express Editions share many resources. As long as the Express Edition is installed, the Visual Studio Shell has WinRT and Modern UI support available for use in Oxygene for .NET development. The Express edition does not support Oxygene, so you will need to continue using the Shell.

Update: It was reported that it may be necessary to uninstall the Shell if you have trouble installing the Express Edition. So if you run into trouble you might try that.