You are browsing the archive for Uncategorized.

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

Oxygene Goes to School

December 13, 2012 in Android, Cooper, Java, Linux, Oxygene, Uncategorized

Dr. Norman Morrison recently published a wonderful series of Oxygene for Java tutorials on his “Pascal Programming for Schools” site, including some on Android development. He reports that students in his school are already using Oxygene for Java for their educational projects and are very excited about building Android applications as well.

Oxygene is great to use in educational settings. It holds true to the design paradigms of Object Pascal, which make it easily readable and discoverable. It doesn’t stop there though, but extends the language with great new language features frequently found in academic languages, like Tuples, Duck Typing and Aspect Oriented programming. The fact that it supports all common platforms of today is a real plus too.

Dr. Morrison also reports using Oxygene for Java to develop for his ARM-based Raspberry Pi, and includes some examples, too.

Adding Oxygene for Java to their curriculum has really energized both the department and the students while expanding their program!

Avatar of marc

by marc

What is “Nougat”? — Part 4

October 19, 2012 in iOS, Mac, Nougat, Oxygene, Prism, Uncategorized, Visual Studio, Xcode

In the first three parts of this series, we took a look at the basic concepts and design principles behind Oxygene “Nougat”, and the IDE experience. In this fourth installment, i’d like to give you an overview of the build and deploy process, and a quick peek at debugging.

Building your project is something that happens behind the scenes and most of the time, we don’t think much of it. We press F5 in the IDE, and a few seconds later our app is running. But a lot is going on behind the scenes to get from your source code to the final executable — and a lot more than usual, for building Mac and iOS apps.

Let’s have a look. All that we’ll be seeing here happens, of course, behind the scenes and automatically, without you having to worry about a thing.

It all starts with the Oxygene compiler, which takes your source files and turns them into executable code. For Nougat, that is the same Oxygene compiler you know and love, only instead of emitting a final “.exe” or “.jar” file as it would do for .NET or Java, it generates a file with CPU-native binary code for either x64 or armv7(s), and a “.o”. (In fact, if you’re building an iOS app with armv7 and armv7s support, the latter being new for the iPhone 5, it will generate two such files.)

On the back-end, Oxygene leverages the great LLVM compiler, which generates highly efficient code.

The “.o” is not the final executable, it still has to be linked. So next, our toolchain calls “ld”, which is the linker. This happens via CrossBox, passing the “.o” file over to the Mac, linking it against all the frameworks it needs, and returning the final executable (which is extension-less) back.

At this stage, we’re done if we’re building a Mac console app, that is, a simple executable that you want to run from the command line. Most Mac (and all iOS) apps aren’t simple console apps, so there’s more that needs to be done to get a final, runnable app — and Nougat does that for you, of course.

Mac and iOS apps come as what is called “Bundles” — which are really folders with an .app extension that are treated as individual files by the OS X finder and other parts of the OS. In the Project Properties of your Nougat app, you’ll find a checkbox called “Create .app Bundle” (checked by default in most templates) that enables this functionality:



With the option set, Nougat’s build chain will take the executable generated above, along with any other files your app needs (such as images or other resources) and generates a full .app bundle. It will also automatically generate an Info.plist file describing your app, or take an existing Info.plist file that’s part of your project and adjust/tweak it as necessary.

The Info.plist file, next to the executable, is an important part of the .app bundle that tells the OS how to run our app, what documents it supports, what application icon to use, etc.

If you’re building a Mac app application, you can be done at this point, and the resting .app bundle is fully runnable. However, these days it’s good practice to digitally sign your application (and in fact that’s required for iOS apps, and also for Mac apps if you want to use the Mac App Store).

How do you sign your app? Nothing easier than that. Looking at the Project Properties again, there’s an option called “Code signing certificate name”, along with a drop down that shows you all the (relevant) certificates Nougat found on your Mac that can be used for signing apps (this list will differ between Mac and iOS projects). Simply select the right certificate, and when you build, Nougat will automatically code-sign the final .app bundle for you.



For iOS apps you will usually choose a “iPhone Distribution: XXX” or “iPhone Developer: XXX” certificate issued by Apple, where XXX is your name or your company name. Distribution certificates are used to build apps to ship on the app store or deploy to beta testers or inside your company; Developer certificates are used while you’re testing your apps on your own devices.

For the Mac, you can choose between “3rd Party Mac Developer Application: XXX” certificates for deployment of Mac App Store apps, or you can use Apple’s new “Developer ID Application” certificates, for non-MAS apps.

In either case, all you need to do is select the certificate, and off you go.

iOS applications also need what is called a “provisioning profile”, generated on Apple’s developer portal, to govern how they can be run. As you might have guessed, there’s an option in Project Properties that lets you pick the provisioning profile you want to use from a list, and Nougat takes care of the rest.

The actual code signing, once again, happens on the Mac, marshaled over transparently via CrossBox, so you don’t even notice it’s happening.

There’s a few more things that might have to be done as part of this process (for example .xib and .storyboard files that might be part of your project will get post-processed into a binary format before being included in your .app bundle), but finally, we have a finished .app bundle that’s ready to be used — run, debugged or, hopefully at some stage, be submitted to the App Store.

Running and Debugging also happens seamlessly. In the CrossBox menu we already saw in my previous post, you can select a Mac or a Device (real or virtual) connected to your Mac:



The menu will list any Mac on the network that’s running CrossBox, as well as any remote CrossBox server you might have connected to. Underneath each Mac, you can select the device you are building for and deploying/running/debugging on. For Mac OS X applications that is just the Mac itself, but for iOS, you can choose between the “iOS Simuator”, a generic “iOS Device” (which lets you build for a device seven without having a real one attached), as well as any actual devices connected to your Mac:

For iOS, the selection you make here affects several parts of the build process. First of all, the Mac you select is of course the one that will be used for all tasks that need to be handled Mac side (linking, code signing, etc).

More importantly, by either choosing “iOS Simulator” or a device (whether a real one or the generic “iOS Device”), you are telling Nougat whether to build your project for device hardware (i.e. in most cases armv7 and armv7s binary, and against the real iOS SDK) or for the Simulator (in which case it will generate an i386 binary, linked against a separate Simulator version of the SDK).

Finally, the device choice also influences how your finished application runs. If you selected a real device, Nougat will deploy the .app to that device, and optionally launch it there, to run or be debugged, and if you selected the iOS Simulator, the app will launch in the simulator on the Mac. (Obviously, an app cannot be deployed or run on the generic “iOS Device”, that option is for building the app only.)

Debugging the application is almost unspectacular, in spite of a lot of effort having gone (and continuing to go) into this: Nougat adds a full Mac and iOS debugging engine into Visual Studio, based on the LLDB debugger, allowing you to use virtually all of the capabilities of the Visual Studio debugger that you are used to from .NET (and Java — where we did the same). You’ll be using the debugger as you always have:

Summary

Ok, so this post took you on a quick tour on what happens behind the scenes when you press “Start” to build and run your Mac or iOS project.

In hindsight, there’s a lot happening, but none of it is any black magic. Nougat takes care of all the gory details for you, so you don’t have to worry about provisioning profiles, code signing and the like, but it will document all the steps it takes (and any command line tools it runs) in the MSBuild log, so that there’s no “black box” and you can know what’s going on, if you care.

Reminder: Keep in mind that the Nougat beta is active now (we started last Monday), so if you pre-ordered the Oxygene 5.2 bundle or own a Suite Subscription for Xcode (we’ll have to rename that one, won’t we?), you have access to the beta now. If you didn’t — well, what are you waiting for? Order your copy now!

Stay tuned for more.

Avatar of marc

by marc

Recent Improvements to the RemObjects Licensing UX

September 14, 2012 in Uncategorized

With the new Oxygene 5.2 release, we have made some significant improvements to the user experience for our software licensing system.

Licensing is always a necessary evil. You gotta do something to enforce licenses, but you don’t want to go to the extreme and inconvenience the honest users (which are the only ones who see the licensing system, as crackers usually just completely remove it) any more than necessary.

Our licensing system always has been very easy-going and laissez-faire: Your licenses are stored in your account, and our software offers to automatically download the latest licenses for you — but you can also grab a license file from our website manually, if you run the software on machines that are offline. We have no “activation”, and no limit on installs — we trust our customers to do the right thing.

Everwood Live

With the new version of the licensing system, which we internally call “Everwood Live”, we’re going the extra step to make licensing even more simple and more unobtrusive for you. This new system is on Oxygene 5.2, and it will also make it’s way into the all-new RemObjects SDK and Data Abstract 7 and into Hydra 4 later this month.

The first time you use one of the products in your IDE (Visual Studio or Delphi) or via of our tools such as the new Schema Modeler 7, you will be greeted with the following dialog:


Everwood Live Login

Ideally, this will be the first and only time you ever come in contact wit EWLive, on this machine. If you enter your username and password, EWLive will reach out to our server, and automatically download your licenses (for all your products) for you, and right away you are set to use all the RemObjects Software products you own.

As you install newer versions of the product, the way that our licensing system works is that an updated license file will be required (this is to prevent one leaked user license to entitle pirates to free updates for a full year). In the past, the frist time you used a new version you would be prompted for your account details, to download a new license. Not any more — Instead what you will see (if you are quick enough and pay attention) is this dialog:


Everwood Live Updating Your Licenses

and after a second or two, your license has been updated and you are ready to go. Chances are, you didn’t even notice this was happening.

Only if there’s a problem downloading your licenses (say you are offline, or — shame on you — your subscription has expired), all you be bothered with a dialog that needs your actual attention:


Everwood Live No Valid License

And Beyond

The UI in Oxygene 5.2 (and the other releases coming this month) is just the beginning of our plans for Everwood Live, and we are are going to to extend this further, including providing much better notifications of new releases (with direct download links), a new UI to manage and check your license and subscription status, and features that go beyond licensing to integrate your remobjects.com account with your product experience (think support, and/or bug reporting).

Behind the Scenes

The new Everwood Live is completely implemented in Oxygene (of course) and WPF 3.5 (because we need to support BDS and Visual Studio 2008). I need to admit that this has been the first project i have done using WPF in a log while (I implemented most of the EWLive UX myself) and i must say i was blown away by how nice and flexible WPF is for building classic Windows UI — the usual prejudice is that WPF is pinkly for fancy 3d graphics stuff — and my experience has really reassured me in recommending WPF as the way to develop Windows GUI applications, today.

EWLive itself is pretty simple; it talks to a few plain HTTPS APIs on our server, to authenticate a user (this happens only once, on the first login screen), to (re)download the license file for a user, or to get the list if current releases.

EWLive stores your user credentials in a secure manner, persisting only your username and an machine-bound “HMAC” that our server can use to authenticate requests for license files. The HMAC does not contain your password, but will be invalidated if you change your password on our website, and is thus fully secure.

Migrating a Metro app from Beta to Release Preview

July 5, 2012 in .NET, Metro, Oxygene, Prism, Uncategorized, Visual Studio, Windows

There were a few breaking changes to Metro apps when the Visual Studio 2012 Release Candidate came out. To develop for the latest version of Metro sing our tools, you will need the June 2012 Release or newer, which you can get from the usual places, including our [licensed downloads page](http://downloads.remobjects.com) and [as trial version](http://www.remobjects.com/trials).

Once you have the June Release or a newer beta installed, you are ready to build Metro apps for the Visual Studio 2012 Release Candidate and Windows 8 Preview, but if you started working with the Consumer Preview of VS11, you’ll need to make the following changes:

  • Remove public from your XAML Pages and App partial classes – You will get an error like ‘(E57) The type visibility for “app” does not match other class parts.’ Simply remove the public visibility modifier from the declaration in the interface section of your pas files. So instead of “type app = public partial class” it should say “type app = partial class”.
  • Add a default language – You may get a warning like “(APPX1901) The DefaultLanguage property is either missing from the project file or does not have a value. The fallback language is set to the Visual Studio language: en-US.” You will need to open the .oxygene project file in your favorite text editor and add the line <DefaultLanguage>en-US</DefaultLanguage> in the first <PropertyGroup>. The warning will then be removed.
  • Recreate your certificate – Anytime you move a project from one machine to another you may find you need to recreate your certificate. You will know because you get a warning like “(APPX0107) The certificate specified is not valid for signing.” The fix is simple:
    1. Just find the XXX_TemporaryKey.pfx file in your solution (where XXX is the name of your project) and remove it.
      TemporaryKey in Solution Explorer
    2. If you try to build now, you will get the warning “(APPX0104) Certificate file ‘XXX_TemporaryKey.pfx’ not found.” You need to create a new certificate: Double-click your Package.appxmanifest file in the solution explorer. From there, go to the Packaging tab.
      Package.appxmanifest Packaging tab
    3. Click the Choose Certificate… button. From the Choose Certificate dialog, click the Configure Certificate drop down, and select Create test certificate…
      Choose Certificate
    4. Then, on the Create Test Certificate dialog, you can provide a Publisher ID or just click OK. Now you will have a new “XXX_TemporaryKey.pfx” file and the warning will go away.
    5. The Metro Style Apps Dev Center has more information about valid certificates.

There were a few other changes, but those will vary from app to app, depending on what you’ve done in the app. I’ve updated my MetroExamples to work with the latest Release Preview and the June Release.

Avatar of marc

by marc

We need to get out less…

January 12, 2012 in Uncategorized

I’m happy to let you know that we have just posted the first set of events that RemObjects will be participating in this year on our event calendar at remobjects.com/events.

2011 was our busiest year so far, with eleven conferences and events we participated in. One highlight has of course been our own DSConf in Las Vegas in February. 2011 also has been the busiest travel year yet for myself as well, with 10 cities in 8 countries visited.

While I myself plan to take things easier this year and will (most likely) leave the city and country only for WWDC, 2012 is already shaping up to be an exciting year where RemObjects events are concerned.

We have 360MacDev and 360iDev coming up again, both in Denver. This will be our third year at 360iDev.

There’s also a lot of Android-related events coming up, matching our increased investment in the Java and Android platform with both the recently-released Oxygene for Java and our upcoming Data Abstract and RemObjects SDK for Java. Jim will be doing an in-depth training course at Android Bootcamp next week and will also be presenting at AnDevCon III in San Francisco in May.

There’s also the Boise Code Camp in Jim’s home town, and of course the Delphi Developer Days, which we’re sponsoring once again this year, as well.

Find information about all our upcoming events at remobjects.com/events — and stay tuned; we’re only 2 weeks into the year, there will be a lot more events coming up.

Oxygene by Example – Threading

January 2, 2012 in Uncategorized

Threads are ways to run multiple things in parallel, at the same time. Each program in Oxygene has 1 or more threads, by default just one, which is the main thread, which is the one in which the gui code runs. Using multi-threading allows you to run something in the background, while keeping your main thread responding to actions from the user (in a gui application). It’s also useful when dealing with blocking operations, like sockets and data access. There’s no practical limit to the number of threads that run at once, it depends on the system resources (memory, cpu) how many will work at once.

Threading

Thread Class

The thread class represents the basis for all the other ways of working with threads. The thread API is simple to use. The constructor takes a delegate to run as the method for a thread, the “Start” method makes the thread start for the first time. “Join” waits for the thread to finish.

var lThread := new Thread(method begin
  var lClient := HttpClient;
  try
    var lResponse := lClient.Get('http://blogs.remobjects.com/feed/rss').Content.ReadAsString;
    Invoke(method begin // synchronize to the main thread
      LoadResponseData(lResponse);
    end); 
  except
    on e: Exception do  
      Invoke(method begin
        MessageBox.Show('Failed: '+e);
      end);
  end);
lThread.Start;

ThreadPool Class

The ThreadPool class offers static methods to run something when a CPU is available. It will create up to a certain number of threads (configurable, defaults to the number of CPU cores) and execute any task it gets given to it in order. Using the Thread Pool is simple. The QueueUserWorkItem method takes a delegate with an optional “state” arguments that gets passed to this delegate.

method MainForm.UpdateRssFeed;
begin
  ThreadPool.QueueUserWorkItem(method begin
    var lClient := HttpClient;
    try
      var lResponse := lClient.Get('http://blogs.remobjects.com/feed/rss').Content.ReadAsString;
      Invoke(method begin // synchronize to the main thread
        LoadResponseData(lResponse);
      end); 
    except
      on e: Exception do  
        Invoke(method begin
          MessageBox.Show('Failed: '+e);
        end);
    end;
  end);
end;

Task Class

The Task class was introduced with .NET 4.0 and introduces a new way to deal with threading. A task is an asynchronous operation. There are two classes, the Task class has no return value, while the Task<T> class does. Using the Task class is simple:

var lTask := new Task<String>(method begin
      exit lClient.Get('http://blogs.remobjects.com/feed/rss').Content.ReadAsString;
  end);
lTask.Start; // add to the default task thread pool and run on another thread.
 
lTask.ContinueWith(method (arg: Task<String>) begin
    try
      var lResponse := arg.Result;
      Invoke(method begin // synchronize to the main thread
        LoadResponseData(lResponse);
      end); 
    except
      on e: Exception do  
        Invoke(method begin
          MessageBox.Show('Failed: '+e);
        end);
    end;
  end);

Tasks can, in addition to this, also be waited upon with the “Wait” call, and the result can be read with the “Result” property.

Timers

There are 3 timer classes in .NET. One is in System.Windows.Forms.Timer, which does not run in a thread but runs at an interval in the main thread. The other two are about the same in features, except that the System.Timers.Timer has a synchronization object to talk back to the main form, while the System.Threading.Timer is a bit more lightweight. These classes offer a way to run code at an interval, for example every 5 seconds, or every 100 msec. In addition to thread, the version in the System.Threaded namespace allows specifying an initial interval.

var lTimer := new Timer(method begin
    Console.WriteLine('Timeout!');
  end, nil, 5000, 250);

This timer will keep running until the application closes, or the Dispose method is called. It first triggers after 5 seconds (5000 msec), then after that every 0.25 second.

Futures

The Oxygene language offers Futures which can optionally return and run either asynchronous, like a task, or delayed on the caller thread. Futures have the advantage that they’re a language element that are easily portable. Internally asynchronous futures use Task if it’s available, or the Theadpool class if it’s not. Futures are assignment compatible with Task/Task<T> on .NET 4, and Func/Action on 3.5.

var lAsync := new async lClient.Get('http://blogs.remobjects.com/feed/rss').Content.ReadAsString;
 
...
 
MessageBox.Show(lAsync);

When to use what

While opinions may vary on the subject, I tend to use the System.Threading.Timer for anything that runs multiple times at a constant interval. The futures map to Task or the thread pool depending on the .NET version, which I would use over those two. If for some reason I would not want to use a future, then I’d use the Task class when I’m developing against .NET 4 or above and have a short running thing to do, the Threadpool for short running things on versions that lack the Task class, and Thread for anything else.

Synchronization

Main Thread

When running in a thread, sometimes you have to tell the GUI that data is available. Updating the GUI from the thread is not safe, and usually leads to hard to find errors. The way to deal with this is using Windows Forms “Control.(Begin)Invoke”, or WPF/Silverlights’ “Dispatcher.(Begin)Invoke”. These apis take a delegate and will execute this delegate on the main thread. The Invoke methods will wait for the main thread to be done with the given task, the BeginInvoke methods will not and let the thread continue right away.

Object Access

Accessing a complex object is not generally a safe operation. Most objects in .NET are not thread safe, and will fail with strange errors when accessed from multiple threads at once. Do deal with this, you can use locking or interlocked access to simple fields.

Locking can be done with the “locking” statement. Locking is done on any object instance, generally this is an object not used for anything else.

type
  MySafeStringList = class
  private
    fLock: Object := new Object;
    fList: List<string> := new List<String>;
  public
    method Delete(s: string);
    method Add(s: string); 
    method GetCopy: List<string>;
  end;
 
method MySafeStringList.Delete(s: string);
begin
  locking fLock do fList.Remove(s);
end;
 
method MySafeStringList.Add(s: string); 
begin
  locking fLock do begin
    if not fList.Contains(s) then fList.Add(s);
  end;
end;
 
method MySafeStringList.GetCopy: List<string>;
begin
  locking fLock do begin
    exit new List<String>(fList);
  end;
end;

The locking statement will make sure only 1 thread at any given time have a lock on the object during the time the statement after it runs.

The other way to deal with values safely is with the Interlocked class. This class is limited to a few types and a few operations and makes it possible to exchange, compare, increment and decrement values safely.

Waiting for threads or resources

Sometimes it’s required to wait until some data is available, or to have the thread idle for a specific amount of time, but still make it possible to terminate it safely. An “EventHandle” is useful for this. There are two different event handles, one resets automatically, the other does not. These classes are called AutoResetEvent and ManualResetEvent. An event can have two states: Set and Unset. When it’s unset, the Wait operation will either timeout after a while, if a timeout is given, or wait for it to be set. The Set operation can be called from any thread and lets any possible waiting thread return with reset. At this point it will reset to Unset if it’s an AutoResetEvent, or stay set if it’s a ManualResetEvent. A useful use of this is to terminate a thread:

CheckForUpdatesThread = class
private
  fEvent: ManualResetEvent := new ManualResetEvent(false);
  fThread: Thread;
 
  method Work;
public
  constructor;
  method Stop;
  method CheckForUpdates;
end;
 
method CheckForUpdatesThread.CheckForUpdates;
begin
  ...
end;
 
 
method CheckForUpdatesThread.Work;
begin
  loop begin
    if fEvent.WaitOne(10000) then  // Wait for 10 seconds, returns true if it was set.
      exit;
    CheckForUpdates;
  end;
end;
 
method CheckForUpdatesThread.Stop;
begin
  fEvent.Set;
  fThread.Join; // wait for it to finish
end;
 
constructor CheckForUpdatesThread;
begin
  fThread := new Thread(@Work);
  fThread.Start;
end;

Concurrent Structures

.NET 4.0 introduces several new collections that are safe access from multiple threads. Among these structures are ConcurrentDictionary and ConcurrentStack. These have slightly different methods for adding and retrieving members than their non-thread safe counterparts but provide a fast way to work concurrently with shared data.

Original article

Oxygene by Example – Command line parsing

December 23, 2011 in .NET, Cooper, Mono, Oxygene, Prism, Uncategorized, Wiki

This is second article in my blog post series “Oxygene by Example”.

While working with command line arguments in Prism is quite simple, the “Main” method has an array of string that holds the value, it can become quite complex when having to parse options too. When having to work with those, it’s easiest to use the NDesk for Oxygene file. It’s a single file that can be added to any project (no need for a separate dll library). It was originally written in C# by Jonathan Pryor, we ported it to Oxygene so it can be embedded in an Oxygene project too.

The first step is to add NDesk.Options to the uses list, this is where the classes are defined. A general console application entry point looks like:

class method ConsoleApp.Main(arguments: array of String): Integer;
begin
  var lSourceUri: String;
  var lDestinationUri: String;
  var lSomeOption: Boolean;
  var lShowHelp: Boolean;
  var lOptionSet := new OptionSet(); 
  var lFiles: sequence of String;
 
  lOptionSet.Add("s|source=", "{filename or url} of source object", v -> begin lSourceUri := v end );
  lOptionSet.Add("d|destination=", "{filename or url} of destination object", v -> begin lDestinationUri := v end );
  lOptionSet.Add("o|someoption", "some binary option", v -> begin lSomeOption := assigned(v) end );
  lOptionSet.Add("h|?", "show help", v -> begin lShowHelp := assigned(v); end );
  try
    lFiles := lOptionSet.Parse(arguments);
  except
    on  Exception  do
      lShowHelp := true;
  end;
  if  (lShowHelp)  then begin
    lOptionSet.WriteOptionDescriptions(Console.Out);
    exit 1;
  end else  begin
    Console.WriteLine('Options supplied:');
    Console.WriteLine('Source: ' + lSourceUri);
    Console.WriteLine('Destination: ' + lDestinationUri);
    Console.WriteLine('Some option: ' + iif(lSomeOption,'ON','OFF'));
    for each el in lFiles do Console.WriteLine('Argument: '+el);
  end;
  Console.ReadLine();
end;

The OptionSet class is the main class for the options parser, first you have to define the different options by using the “Add” method. The first parameter defines what option it maps to. in “s|source=”, there are two bindings for this option, “s” and “source”, the | just separates them. The “=” is used to denote that the option takes a parameter. “s” is a single letter option, to use it one can use “MyApp -ssourcefile.text”, or “MyApp –source sourcefile.text”, the short options do not have a space, and a single dash, the long options have a space and two dashes.

The second parameter for Add is the description, when writing out the option list it will print this (see below), the last parameter is a delegate that gets called when it’s triggered. This delegate (in the cases above we use anonymous methods) has one parameter with the value passed. From these anonymous methods we set the options we define in the variables above it, that way we can read them later on.

The last step is lOptionSet.Parse(arguments), this will return a list of “rest” parameters, anything that’s not an option (or parameter to an option) will be in this list. It will raise an exception when there’s an error parsing arguments. We set the lShowHelp to true in this case, so we can later write the options to the console with WriteOptionDescriptions.

Using the Ndesk.Options classes makes parsing parameters a lot easier than doing it manually. The OptionSet classes have a lot more features, all of which are documented at the top of the source file Options.pas.

The original version of this article can be found in our wiki.

Oxygene by Example – Singleton

December 16, 2011 in Uncategorized

This is the first item in my series “Oxygene by Example”, this time about singletons.

Singleton classes are used when there’s only ever one instance of a class needed. They differ from Static Classes in that they have an actual instance, can implement an interface and you can use them as parameters to a method. There are different ways of writing singletons, but the easiest way is by using a readonly class variable:

type
  IObjectCache = interface
    method GetOrCreate(aName: string; aNeedNewValue: Func): T;
  end;
  GlobalObjectCache = class(IObjectCache)
  private
    fCache: Dictionary := new Dictionary;
 
    constructor; empty; // required to be private; so nobody can instantiate it
  public
    class property Instance: MySingleton := new MyObjectCache; readonly;
 
    method GetOrCreate(aName: string; aNeedNewValue: Func): T;
  end;
 
method GlobalObjectCache.GetOrCreate(aName: string; aNeedNewValue: Func): T;
begin
  locking fCache do begin
    var lValue: Object;
    if fCache.TryGetValue(aName, out lValue) then exit T(lValue);
    result := aNeedNewValue();
    fCache.Add(aName, result);
  end;
end;

Using the singleton is simple, GlobalObjectCache.Instance gives access to all instance members of the class:

  lblSystemName.Text := GlobalObjectCache.Instance.GetOrCreate(
    'ComputerName', -> Environment.MachineName);

The latest version of this article can be found Here.

Oxygene by Example

November 23, 2011 in Uncategorized

Last week I started on a series of articles called Oxygene by Example. They’re stored in the wiki at wiki.oxygenelanguage.com/en/Oxygene_by_Example and go over different problems while providing a solution written in Prism. So far I’ve written articles about:

  • Singleton – Single instance class
  • CommandLine – Parsing command line arguments and options
  • Threading – Working with threading in Prism
  • XML – Reading and writing XML files
  • Parsing – A simple expression tokenizer and parser
  • Visitor – A Visitor/Mutator pattern that can be used to do anything with a tree

Suggestions for other things I should write about are welcome, my ideas for further articles are the activator pattern, iterators, the observer pattern, working with linq, working with reflection, sockets and binary trees.