Showing posts with label Delphi Prism. Show all posts
Showing posts with label Delphi Prism. Show all posts

Sunday, 21 March 2010

Silverlight back from the dead.

Microsoft have probably just saved Silverlight. Their recent announcement of the Windows Phone 7 Series, and more importantly the development platform for that phone (Silverlight of course) means Silverlight is important now. I was always pretty sure WPF would become the defacto standard for desktop applications (and what with Visual Studio now being written in WPF, perhaps it will), but I couldn’t quite see a compelling reason behind Silverlight. Now there is one!

Have Embarcadero backed the wrong horse (again…)? They’re targeting the MAC with their next compiler. Probably because they think that is where the future is. Perhaps the future is with Seattle and not Cupertino!

They have Delphi Prism of course, and you can develop for Windows Phone using that. Having said that, no one has ever answered my question? Why should I use Delphi Prism and not C#? Now before I get a 1000 comments telling me that Pascal is easier to read than C#, I just want to say I agree. I love Prism! I wish I could use it every day. It’s awesome. Can I praise it anymore? I need a reason to use it though. One I can go to my boss with. I’d like to be able to go to him and say, “you know that project we were about to develop in C# (the one we decided to NOT use Delphi native Win32 for!), well I think we should use Delphi Prism because….”

If anyone can complete that sentence for me, I’d love to be able to use it. I wish Microsoft had approached Remobjects and partnered with them rather than Embarcadero. The only way my boss would agree to Delphi Prism would be if it sat along side C# and VB.NET in the default install of Visual Studio. That wouldn’t guarantee anything, but I’m sure the added exposure would garner quite a few new followers.

Monday, 10 August 2009

Delphi Love

I was rather surprised at the comments to my last post. Some were pretty heated. Delphi developers are extremely protective of their baby, but I knew that already. I didn’t actually think my post was that provocative, but perhaps it was.

A good number commented that what has been released so far is only the tip of the iceberg, and that beta testers were not allowed to reveal more yet. That’s all well and good, but I can only comment on what I have seen. When more is revealed, I no doubt will add further comments.

Actually, I never said 2010 sucks. I just said that I’m not that excited yet. I didn’t say others wouldn’t be excited. I just said that I, personally, in my humble opinion, need more than IDE changes to get my blood stirring.

Each release of Delphi Prism excites me for example. They seem to be forever adding little goodies to the compiler. Perhaps it’s easier to do with the .NET platform?

Monday, 19 January 2009

Some are more equal than others!

I've been trying to evaluate some scripting solutions for a Delphi application I'm working on. One of the things we do a lot of is repetitive calculations. So we wrote a small test example to try this out. It's a very contrived example, but it should give us an idea of how fast these solutions are. We basically nested two loops, and did some random mathematical functions inside the inner loop and put the results into an array of doubles. The details are not too important, but the first thing that stood out is how blindingly fast Delphi is. And by contrast how excruciatingly slow these scripting solutions can be. Some were better than others, but all were magnitudes slower than the native code. I kind of expected that, but not by such a margin. The best solution was surprisingly VBA at five times slower than native Delphi. Not sure if Microsoft still licence it though. I guess we may have to rethink how scripting will work in our application.

Now to the title. What's equal to what? Well, I was wondering how fast the same code would be if I wrote it in .NET. I chose C#, and was surprised to find it marginally faster than native Delphi code. Well, not that surprised. I expected it to be fast, maybe as fast as, but not faster than Delphi though. It wasn't by a lot, but it was impressive nonetheless. I guess the optimisation's that are now possible when using a JIT compiler are beginning to outweigh native codes inherent speed. I'm sure there are some things always suited to native code, but for most things, the fear that .NET is going to be slow is unfounded.

Just for the sake of it, I decided to rewrite it in VB.NET, expecting the same result. Wow, almost twice as slow. I wonder why. And the executable is more than twice the size of the C# equivalent. Ok, now I was really interested, so I wrote the whole thing in Delphi Prism. Syntax wise, apart from the usual begins and ends, the Delphi Prism version feels more like the C# version than the .NET version, and the performance is almost exactly the same as the C# version. The executable is 4 times the size of the C# one though. I managed to get it slightly smaller by getting rid of the icon, but it's still larger. Why? I'll investigate later with reflector.

Finally, I wanted to try and use the asynchronous features of Delphi Prism. Nothing too complicated. So I just split up the outer loop into ranges, and used Delphi Prisms async keyword.

var x := async ExecuteIt(0, 2000);
x; //Waits for the async method to execute

Since I was timing how long the whole process took, I used the waitable result of the asynchronous statement to make sure each of my chunks were ready before I stopped the clock (but I made sure they didn't wait on each other). On my dual core CPU, the resultant application ran almost twice as fast as the synchronous version. The extra method call, plus switching overhead making sure it wasn't exactly double. Pretty cool stuff, and I've only just touched the surface.

Thursday, 8 January 2009

Delphi Prism Web Templates

I've been trying to do a few Silverlight examples with Delphi prism, and I keep getting all kinds of errors when creating the projects. I've noticed though, that it only happens if I try and create an ASP.NET test project for the Silverlight application. Then I noticed I have no ASP.NET template for Prism. Does anybody know why Delphi Prism (my copy at least) has no web templates? I think Oxygene did have them, but I can't remember for sure?







Can I get the templates from somewhere?

Friday, 26 December 2008

Bizspark – Where’s Embarcadero’s equivalent?

Let’s imagine a hypothetical situation. It’s hypothetical because I’m just speculating, but it’s one that could happen, and I’m sure happens all the time.

Right, I’m a Delphi developer. I’ve been working 9-5 for the boss for a long time. I have had a great idea for a product, and would like to try and develop that product independently, and market it. Being a Delphi developer, I naturally would like to develop that product in Delphi. Makes sense. Ok, so what do I need? I have a pc (or 3), so I now need the IDE. Ok so what are my options? I’d like the latest, and greatest. No point in making my mouth water with features such as Generics and Anonymous methods and expect me to settle for less. So  I go to the Codegear (UK) website, and check out the prices. WOW. £979 excluding VAT (currently 15%). I may be able to get a better deal somewhere, but it’s not going to be much cheaper. My product idea is great and all that, but you never know. I need to keep my costs down, and £979 (don’t forget the VAT) is a lot of money for something which may or may not succeed. There’s no such thing as a free lunch you say!

Well maybe there is. Let’s look at the competition. In particular Microsoft. Microsoft have what they call Bizspark. Basically, they’ll give you a whole load of their products, for free if you are a startup. If your revenues are less than a million dollars a year, and you’ve been in business for less than three years that is. Well, if my product starts making a million a year, then I wouldn’t mind paying £979, but right now that’s a little too much. So if I choose to use C# instead of Delphi, I can save myself £979. Actually it’s a lot more than that, because not only do I get Visual Studio, but I also get a whole lot more than that. In fact it will cost me a simple $100 after 3 years. I’ll have tried my product idea with little or no risk, and Microsoft have gained a developer for a cost of $100 to them. By giving me thousands of dollars worth of software for a measly $100, they haven’t lost any sales, because I would never have bought them in the first place.

I mean forget Bizspark. If I really want I can go and download Visual C# Express, and use SQL Server Express as my backend. That’s more than enough for my product. What has Codegear to offer? Turbo Delphi? That’s Delphi 2005 I think. Whatever it is, it’s not Delphi 2009. What about Prism? Do they have a Delphi Prism Express? Nope, not that I can see. Not much of a decision really, is it? I’m a Delphi developer, but C# holds absolutely no fears for me. Codegear have just lost another developer. More importantly, maybe my product idea is a success. Maybe in a year’s time I need to employ a few developers. Codegear have just lost a few more developers. Ok, my product is now really successful. I can afford the £979 for each of my 10 developers. Am I going to switch? Somehow I doubt it?

So Delphi, which used to be the obvious choice for your one man startups, is no longer a viable option. It has always been expensive, but when compared to the opposition, it was still value for money. It no longer is. How much of Codegear’s sales are Delphi 2005/2006/2007 shops upgrading to the latest, and how much are new developers? Or old developers branching out? My guess is that it’s very close to 100% Delphi shops looking to go to the latest offering.

If by some chance, Codegear do have some Bizspark equivalent, well done, but if that’s the case, then it’s very well hidden. I appreciate that Microsoft can afford to give away their products. Can Codegear afford not too?

Thursday, 18 December 2008

Delphi Prism – Class Contracts

One of the new features of Delphi Prism, which you may not have heard about is native support for Class Contracts. Class Contracts are Delphi Prism’s implementation of design by contract.

The whole premise of Design by Contract is that components of a software system interact with each other on the basis of mutual obligations (a contract). Therefore a method of any class may :

  • Insist that any client calling the method must adhere to a certain pre-condition.
  • Guarantee a certain post-condition on exit.
  • or will commit to maintain a certain property (Invariants).

Pre-Conditions

A pre-condition frees the method from having to maintain any checking code as it can be certain that the pre-condition will be met. Delphi Prism implements pre-conditions using the require keyword.

method MyClass.ToString(const aIndex : Integer) : string;
require
aIndex >= 0;
begin
result := fStrings[aIndex];
end;


Pre-Conditions are evaluated before the method is executed.


Post-Conditions

A post-condition ensures that the client knows what to expect from the method after it has executed. Delphi Prism implements post-conditions using the keyword ensure.


method MyClass.ToString(const aIndex : Integer) : string;
require
aIndex >= 0;
begin
result := fStrings[aIndex];
ensure
result.Length > 0;
end;


The old scope prefix can be used in the ensure section for local variables and parameters,  and refers to the values as they were before the method executed.


method MyClass.Add(aValue : string);
require
aValue <> ‘’;
begin
fStrings.Add(aValue);
ensure
Count = old Count+1;
end;

The old construct is only supported for integers and value types of both parameters and local variables. The compiler saves the value before execution of the method.


Class Invariants

Class invariants ensure that certain properties or fields of an object comply with a fixed state. Class invariants may be either private or public. We need to be careful here, as the way these work may initially seem counter intuitive. Public invariants, are checked after every public method only. (Actually, after the ensure clause, if it exists), while private invariants, are checked after both public and private methods. Another point to make is that both public and private invariants have access to all fields of the class. The public and private scope modifiers only indicate on which methods the invariants will apply.



  TestClass = public class
private
fValue : Integer;
private invariants
fValue > 0;
public invariants
fValue > 35;
public
//public methods
end;

Since public fields can be accessed from outside the class, they cannot be used in invariants as there is no way to restrict what goes on outside of the class. Having said that, public fields are never advisable anyway, so it’s not that much of a restriction

If any of the contracts above are not upheld, an assertion is raised. Assertions are by default enabled for the debug configuration, and disabled for the release configuration.


The Future

So what could be added in future to make class contracts even more useful than they already are?


  • Pre and Post conditions for interfaces

ITest = interface
method Test(const aValue : Integer) : string; requires aValue >= 0 ensures result <> '';
end;

With this syntax, we not only specify what the implementation must look like, but we also specify how it must behave.


  • Exceptional Post-Conditions

The ability to specify what exceptions a method can/should raise.


method Test; raises System.OverflowException;

  • Frame Conditions

Frame conditions restricts what a method can modify. Sample syntax could look like

  method Test; modifies fValue; 

Conclusion

Class constructs are not one of those features that you cannot live without. You could happily go on writing code and never use them once. However, by adding class contracts to your code, you make it clearer what the class does, and how it does it. Class contracts remove some of the ambiguity and a lot of the guessing. Up until now, we have used method signatures to indicate how class users can go about using our classes. We have also had to document a lot of other information so the user knows what is expected of him/her, and what he/she can expect from the class. With class contracts, a lot of that documentation is now part of the class, and can be checked at run-time to ensure the application is doing what we intended it to do in the first place.

Friday, 12 December 2008

WPF like effects in your Win32 forms

Are you still developing native applications? Would you like to do some cool tricks with your forms? How about making your windows fade in and out?

The Win32 API to the rescue! The function AnimateWindow can be used to blend in and out the form. To the FormShow event handler, add the following code :

AnimateWindow(Self.Handle, 1000, AW_ACTIVATE or AW_BLEND);

To reverse the effect, add the following code to the FormClose event :

AnimateWindow(Self.Handle, 1000, AW_HIDE or AW_BLEND);


You can also get the form to slide in, rather than blend, by changing the flags to AW_SLIDE or AW_HOR_POSITIVE to get the slide to come in from the left for example.



The same approach can be used in Delphi Prism, when using WinForms. While Delphi Win32 imports the AnimateWindow method for you, in windows.pas, in Delphi Prism you have to do it yourself using P/Invoke. (As you would with C# or VB.NET may I add). So in your WinForm, add the following code to the private declaration :



private
const AW_HIDE = $10000;
const AW_ACTIVATE = $20000;
const AW_HOR_POSITIVE = $1;
const AW_HOR_NEGATIVE = $2;
const AW_SLIDE = $40000;
const AW_BLEND = $80000;
[DllImport("user32.dll", CharSet := CharSet.Auto)]
class method AnimateWindow(hwand : IntPtr; dwTime : Integer; dwFlags : Integer) : Integer;external;


Remember to add System.Runtime.InteropServices to the uses clause of your form. Now, you can add the same code as before (it's all object pascal, so the same syntax), to the Load and FormClosing events of your form.



  method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs);
begin
AnimateWindow(Self.Handle, 1000, AW_ACTIVATE or AW_BLEND);
end;

method MainForm.MainForm_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs);
begin
AnimateWindow(Self.Handle, 1000, AW_HIDE or AW_BLEND);
end;

So there you have it, forms that fade in and out.

Monday, 17 November 2008

Anonymous Methods

Both Delphi 2009, and the upcoming Delphi Prism have support for anonymous methods. Now while I am very excited about other features, notably generics, I just couldn’t get excited about anonymous methods. I just didn’t get them. I understood the syntax, but to me they looked like inline methods. My biggest question was why should I use an anonymous method, and not a procedural types, like we’ve always done in Delphi? Ok, I save having to write a separate method, but what’s wrong with separate. It’s probably more readable that way anyway.

I read blogs the blogs and articles.  I studied examples, which always seemed to be artificial, or just too complicated to actually explain the concepts. I read the Wikipedia entry on closures, which are what everybody else seems to call them, but still no joy. All I really want is to be able to understand the concept, enough that during my everyday work, I can identify areas where an anonymous methods would fit nicely, and where they would be the best choice.

Being a recent convert to Stackoverflow.com, I asked a question there. Can someone explain Anonymous methods to me? I got quite a few answers, some with yet more code examples. I still couldn’t see how any of this was going to make my day to day coding any easier, or even a little bit more exciting! That is until I got one answer which made me go Aha. Actually it was one line within that answer.

Just think of typical callback code where you need to have data available to the callback.

So I looked at some code I’d recently written, which used a callback, and replaced that callback(literally a method pointer) with an anonymous method.  The code I had recently written was an implementation of a Direct Acyclic Graph. Basically a way to represent a number of objects (vertices), and the relationships(edges) that exist between those objects. Think cities(the vertices) with possible flights between them(the edges). Then using certain well-defined algorithms, you can traverse those vertices in various ways. So going back to the cities and flights example, it would be possible to find the shortest route between any two cities for example.

I’d originally implemented these traversals using procedural types.


type
TTraversalMethod = procedure(v: TVertex);

TGraph = class(TObject)
private
public
procedure LinearTraversal(aMethod :
TTraversalMethod);
end;

procedure TGraph.LinearTraversal(aMethod :
TTraversalMethod);
var
v : TVertex;
begin
for v in Vertices do
aMethod(v);
end;

So basically LinearTraversal does nothing special except traverse all the vertices in a linear fashion. Not too exciting. So let’s say we now have a graph and we want to display the vertex names as a string, which we’ll implement using a TStringList;

procedure TMyClass.TraverseMethod(v : TVertex);
begin
  fStringList.Add(V.Name);
end;

procedure TMyClass.ShowGraphAsText(aGraph : TGraph);
begin
  fStringList.Clear;
  aGraph.LinearTraversal(TraverseMethod);
  ShowMessage(fStringList.Text);
end;

You’ll notice that we need two methods, one to actually prepare the call, and the other is the function called on each vertex. We also need a stringlist which must be visible from both methods. Unfortunately even if we make it private to the class, it’s still visible to all other methods in the class. What if some other method is expecting some other list to be stored in that stringlist? A year down the line how can we possibly remember not to touch that stringlist?


What would be ideal is if we could make the stringlist local to the ShowGraphAsText method. Well it turns out we can. I’m going to rewrite the above using anonymous methods. I’ll use Delphi Prism/Oxygene as that’s what I’ve got at hand, but Delphi 2009 would work just as well.


type
  TTraversalMethod = public method(v : TVertex);


  TGraph = public class
    …
    …
  public
   method LinearTraversal(aMethod : TTraversalMethod);
  end;

method TGraph.LinearTraversal(aMethod : TTraversalMethod);
begin
for each v in Vertices do //the type of v is inferred
    aMethod(v);
end;

The actual code for the traversal looks pretty similar. There are a few Delphi Prism constructs. method instead of procedure, and for each in instead of for in. Also note the type inference in the LinearTraversal method.

It’s the calling code that things get interesting.


method TMyClass.ShowGraphAsText(aGraph : TGraph);
begin
var s: StringBuilder := new StringBuilder(‘’);
  Graph.LinearTraversal(
method(v : TVertex);
begin
s.Append(v.Name);
end
  );
  MessageBox.Show(s.ToString);
end;

We now only have one method (well strictly speaking two), and more importantly we have our local helper variable.

And that was my aha moment. It’s not the actual fact that you can inline an anonymous method where you need it that makes them so powerful, it’s the capture of local variables of the outer method inside the anonymous method. When you look at it like that, you see them in a whole new light. Now I can go back to all those examples I’ve seen and understand them better.