Warung Bebas

Sabtu, 03 Desember 2011

Putting the pieces together - the DSharp presentation model

Recently there have been several threads and discussions about separating GUI and business logic. Of course that is nothing new, the MVC or MVP patterns are widely known. There is just one problem especially with these two patterns: the dependency between the presenter or the controller and the view and model. Often you cannot easily change the view. Testing the model and the controller or presenter without the view is complicated or impossible.

This is where the MVVM pattern has its benefits. Of course in WPF this pattern can shine because you have XAML but also in Delphi this pattern is worth a closer look. This pattern is also known as Presentation Model. The main benefit over MVC or MVP is that view and viewmodel have no dependency on each other. You can design the GUI independently from the business logic and just bind them together later. And there is the keyword that makes this pattern work: binding.

There are several amazing frameworks for MVVM development in .Net like Caliburn Micro or Prism. Caliburn consists of several different pieces to easily build applications the MVVM way. One of them is the ModelViewBinder. It takes the view (like a form or a frame) and a viewmodel (like a datamodule or another business object) and creates bindings to connect these two using naming conventions. For example the Lastname property of the viewmodel is bound to the Lastname edit on the view, the Orders property which may be a list gets bound to a listview called Orders. You could also bind the Customer.Address.Street property to the Customer_Address_Street edit on the view. All this gets powered by a DI container that puts all the pieces together, also by convention over configuration. If you have a viewmodel called CustomerDetailsViewModel there should be a CustomerDetailsView (there are actually several different conventions and you can add more if you like).

DSharp presentation model makes it possible to use the powerful spring DI container and data bindings to easily build applications that are easy to test and to develop. It sure is just scratching the surface yet but when you take a look at the ContactManager sample in the svn repository you can get a basic idea of what is possible.

Enough with just talking theory. Let's create a simple application!

Step 1 - The View

After creating a new VCL application (FMX is pretty similar - there are just not that many controls supported out of the box yet) we add some controls on the form so it looks like this:


After saving the unit the source looks like this:

unit CalculatorViewForm;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DSharp.Bindings, DSharp.Bindings.VCLControls;

type
TCalculatorView = class(TForm)
BindingGroup1: TBindingGroup;
CalcOperator: TComboBox;
CalcResult: TEdit;
Calculate: TButton;
Label1: TLabel;
LeftOperand: TEdit;
RightOperand: TEdit;
Error: TEdit;
end;

implementation

{$R *.dfm}

initialization
TCalculatorView.ClassName;

end.

The only thing you actually have to write there after adding the components including the binding group is adding the unit DSharp.Bindings.VCLControls.pas (only if you don't have DSharp bindings VCL designtime package installed which inserts that unit automatically) and the line in the initialization part of the unit. This is necessary so the linker does not remove this class because it actually is not referenced anywhere (similar to the RegisterComponent you do if you are working with the DI container in the classic way).

Step 2 - The ViewModel

Now we create the viewmodel - the class that actually does the work and holds all the states of for the UI.

For our simple calculator we just need some fields and a method:

unit CalculatorViewModel;

interface

uses
CalculatorInterfaces,
DSharp.PresentationModel.ViewModelBase,
SysUtils;

type
TCalcOperator = (Add, Subtract, Multiply, Divide);

TCalculatorViewModel = class(TViewModelBase, ICalculatorViewModel)
private
FLeftOperand: Double;
FRightOperand: Double;
FCalcOperator: TCalcOperator;
FCalcResult: Double;
FError: string;
public
procedure Calculate;

property LeftOperand: Double read FLeftOperand write FLeftOperand;
property RightOperand: Double read FRightOperand write FRightOperand;
property CalcOperator: TCalcOperator read FCalcOperator write FCalcOperator;
property CalcResult: Double read FCalcResult write FCalcResult;
property Error: string read FError write FError;
end;

implementation

{ TCalculatorViewModel }

procedure TCalculatorViewModel.Calculate;
begin
try
case FCalcOperator of
Add: FCalcResult := FLeftOperand + FRightOperand;
Subtract: FCalcResult := FLeftOperand - FRightOperand;
Multiply: FCalcResult := FLeftOperand * FRightOperand;
Divide: FCalcResult := FLeftOperand / FRightOperand;
end;
FError := '';
except
on E: Exception do
begin
FError := E.Message;
FCalcResult := 0;
end;
end;
DoPropertyChanged('CalcResult');
DoPropertyChanged('Error');
end;

initialization
TCalculatorViewModel.ClassName;

end.

We inherit from the TViewModelBase class which has some mechanics built-in that we need for the whole thing to work (like inheriting from TComponent which is necessary for the lifetime management and implementing several interfaces the framework needs). If you are just interested in creating something similar to the passive view and constructing the classes yourself and just using DSharp bindings you can just inherit from TPropertyChangedBase or some other class and wire things up yourself (or use the ViewModelBinder to do that without the rest of the framework).

We actually have no setters for the properties in this viewmodel because the changes just happen when you click the calculate button. Did you notice we named the properties exactly like the controls? That is not by accident. As I told you earlier the ViewModelBinder looks for components and properties it can bind together and it does it by their names.

One thing here is not obvious. We added the 4 operators to the items of the combobox earlier and we named them exactly the same (not the classic hungarian notation for enums here though). This is because the ViewModelBinder binds to the Text property of a TComboBox (you can change that to ItemIndex if you like - just edit the line in DSharp.PresentationModel.VCLConventionManager.pas). Then you can name the enums and the items differently. This may also make more sense when you localize the items in the combobox but it depends on how the combobox is set up. In the future the ViewModelBinder might consider the options of the combobox.

The calculation method is actually pretty simple. At the end it sends the notifications of the changed properties: CalcResult and Error. Keep in mind that this example does not show any kind of validations. You can still write rubbish into the edits. Since internally a conversion is done from string to double (bindings have a default value converter unless you specify one yourself) the value is not sent to the viewmodel if the converter cannot convert it into a double. How validations can be done and shown in the UI can be seen in the Validations sample.

Now let's take a look at the last unit of this example:

unit CalculatorInterfaces;

interface

uses
DSharp.ComponentModel.Composition;

type
[InheritedExport]
ICalculatorViewModel = interface
['{03AF7AE1-CCDF-4F06-9074-919F6C759DBE}']
end;

implementation

end.

The InheritedExport attribute tells the DI container to register every class it finds that implements this interface. That is why we had to add the line in the initialization part of the viewmodel unit. Because that class also is referenced nowhere and the linker would just throw it out. Why not doing the registration of the class there instead? That would actually create a dependency on the DI container and you have no chance to remove that registration for unit testing without code changes.

Remember to add a guid to the interface, otherwise the DI container will complain.

But wait - that interface does not have any methods. Yes, for our example it actually does not need them. Because bindings currently can only work between objects the interface is cast to the implementing object behind the scenes. Keep in mind that you cannot do interface delegation and binding to such interfaces. Also in our example we don't call anything on that interface because the Calculate method (of the object) is bound to the button. For a more complex scenario and actually using the interface methods look at the ContactManager example.

Step 3 - Putting the pieces together and starting up

Let's take a look at the dpr file now:

program Calculator;

uses
Forms,
CalculatorViewForm in 'CalculatorViewForm.pas' {CalculatorView},
CalculatorViewModel in 'CalculatorViewModel.pas',
CalculatorInterfaces in 'CalculatorInterfaces.pas',
DSharp.PresentationModel.VCLApplication;

{$R *.res}

begin
Application.Initialize;
Application.Start<ICalculatorViewModel>;
end.

We have to make some modifications here. By adding the DSharp.PresentationModel.VCLApplication (or FMXApplication) unit we add the Start<T> method to TApplication. That is the method that starts it all up as the name implies. You have to specify the root viewmodel of your application. From there on you can build everything you like - manually or using the presentation model. We removed the other methods except Application.Initialize. I have to admit that I am not totally happy with that solution right now because it kind of breaks something in the IDE regarding editing the project options (only things like Title that result in the IDE editing the dpr file). Everything else still works, no worry. The Initialize call has to stay there because removing it would actually remove the theming from the application (another weird thing related to the source of the dpr file).

Let's start the application and look if it works (if you don't want to do all the steps by yourself you can find the source in the repository as always). For now I am not going into the implementation details - I leave that for a future post to explain how all the different pieces are working together to make it a bit clearer and less "magic".

DSharp presentation model is available for Delphi 2010 (without aspects) and higher (working on 64bit for XE2) - if you experience any problems feel free to send me an email or file an issue on the project page - I usually test it on all platforms but sometimes some of the nasty compiler or rtl bugs may break something.

Sabtu, 22 Oktober 2011

CodeRage 6 feedback and DSharp news

I think Code Rage 6 had interesting stuff for almost everyone. Thanks to the time difference I could watch the sessions live that interested me most at home after work (as I was also very interested in the Q&A):

LiveBindings (Jim Tierney)

You know I have been complaining about the LiveBindings much in the past. So the questions I had prior to these sessions were: Did I miss something when I started working with them that affected my opinion so negatively and what is the general opinion about those bindings (as the reaction of other people)?

Jim started with some console applications explaining the expression framework beneath the LiveBindings. This session was very interesting and actually motivated me putting some work into the DSharp expressions to use them in the bindings (as I started developing those after I created the bindings). More about that later.

The other two sessions actually had no surprises for me. In fact the Q&A was more interesting. Unfortunately I forgot to save the log so I have to recapitulate that from memory.
Someone asked the question I was expecting: Why using LiveBindings over the traditional way since it looks very complicated setting them up (especially when working with grids and lists). It may be just my point of view but Jim did not have the killer argument. Sure, he mentioned the separation of GUI and BL but hey it is more than that.
If easy and painless to configure bindings can completely take care of your data flow. You just have to care about computing it. Think about how much code you have written in the past to show data, get it from one place to another and much more. Almost all of that code can be removed with a good binding system or at least moved to another place where it is not in the way. When asked about things like property references his answer saddened me - there are no plans for something like that. I still hope he just did not know about it.

Dependency Injection and Unit Testing (Nick Hodges)

On Wednesday I was excited about Nicks sessions and I have to say it again: very well done, Nick! I think these two sessions got people interested in learning more about dependency injection and as I have said in the past: recent releases since 2010 (with introducing the enhanced RTTI) over XE (first version that I did not want to throw out of the window when heavily using generics) to XE2 (more bugfixes and more features for the RTTI like virtual interface - also more on that later) gave us the possibilities other languages as C# or Java have had for ages. Using modern developing techniques to be more productive and raise the code quality.

His second session was about unit testing and I have to admit, I often am more excited about implementing new things instead of testing some existing things. That often has to do with hard to test code (like existing code that respects no clean code rules and is a total mess and has dependencies all over the place). When writing code with testability in mind it actually is fun to write tests, refactor your code and find eventual mistakes within seconds. But what about more advanced unit testing frameworks in Delphi? DUnit has been around for years and with new techniques there is also the need for a more advanced unit testing framework. There are several projects around and as Nick already mentioned it would be great to get the people together to build something great for the community. I just recently read about JBehave and immediately liked the idea.

Also with the possibility to use mocks (I am still a bit jealous that Delphi Mocks by Vincent Parrett is mentioned so often compared to DSharp) there are many ways to use the new features we got in the past 2 years.

RTTI (Robert Love)

As I have been exploring the RTTI since its release Robert could not tell me anything new but his sessions actually were very interesting and inspiring to those that have not touched the RTTI yet or at least not much. There are so many ways using it and actually I already cannot think of living without them.

Actually I found something on friday that was strange - especially with having in mind what Nick did. He put an entire class into the implementation part of a unit registering it to the container in the initialization part of the unit. I mentioned the dependency on the container in that case and tried something else: using TRttiContext.GetTypes to iterate all known types looking for attributes that tell to register that type. But it did not list the class in the implementation part of the unit. The class was not thrown out by the smart linker because it was actually used. It just seems to be the case that GetTypes does not find any types in the implementation part while GetType(...) works.

New things in DSharp

You might have noticed a lot of commits in the DSharp svn repository recently. I have refactored the collectionview classes (those responsable to bind lists of objects to controls) and added some more presenters to work with the DevExpress controls (grid and treelist). The expressions that started as experiment have been improved and are part of the binding framework now. I also moved some units to their own namespace (logging and aspects). And as I mentioned earlier one feature I am very proud of:

DSharp got full AOP for interfaces.

Some weeks ago I implemented AOP for virtual methods that made it possible to patch the VMT of any class at runtime making it possible to inject aspects into every instance of a class, its descendants and every new created class automatically. With the new classes and with support for attributes it is possible to declare aspects and apply them to virtual methods, interface methods and entire interfaces and classes.

I will explain that in detail in a following article as I am currently working on an adapter for the spring DI container to work with my composition and  presentation model which I also will explain in detail soon. For now you can check out the sample and see how easy it can be using aspects like logging on your interfaces, implementing it once and using it everywhere without writing any line of code (well, except the attribute)!

Jumat, 07 Oktober 2011

Supports killing objects

Today I had a really bad "d'oh!" moment... feel free to laugh at me because I did not know better. ;)


You all may use the Supports routine - so did I without further thinking about it - until today. I shamefully have to admit that I should have looked at its code and/or the documentation earlier.

What happened? In my bindings I check the source and target objects for special interfaces (f.i. INotifyPropertyChanged). I changed some code and strange things started happening in form of access violations. So I quickly found out that the Supports call caused a Destroy on the object when it did not support the given interface. Looking at the source revealed why: Supports does not only call GetInterface with the given guid, no it also does it for IUnknown causing _AddRef and _Release calls. And we know how that ends on some refcounted object that has the initial refcount of 0.

Actually there is a comment saying: "NOTE: Calling this overload on a ref-counted object that has REFCOUNT=0 will result in it being freed upon exit from this routine." And the documentation says: "Warning [...] For objects that have a reference count of zero, this will result in the object destruction."

Just another reason why Delphi sometimes is a pain in the ass if you are using object references and interfaces. Some may say: "Just use interfaces!" No, I do not want to write interfaces for simple data objects and other things. But I want to use interfaces for certain aspects (f.i. INotifyPropertyChanged). And most important: I do not want my objects getting destroyed if they DO NOT implement the requested interface.

Actually I have no idea why this was implemented like this long ago. Anyway I wrote my own Supports overload now:

function Supports(const Instance: TObject; const IID: TGUID; out Intf): Boolean;
begin
Result := Assigned(Instance) and Instance.GetInterface(IID, Intf);
end;

If your instance is assigned for sure you just might call the GetInterface method. I know there might be cases where the other Supports returns true and this one not like when having a customized QueryInterface. But in my cases it should solve my problem of instances getting shot in the head by the Supports call.

Let me know if I missed something about this implementation.

Kamis, 29 September 2011

BROWSER FIREFOX , HASILKAN DOLLAR







Ada-ada aja nih orang luar kalau Bikin bisnis Online,
kali ini mereka membuat Browser sebagai penghasil Dollar.
Mudah kok, kita cukup install Add On pada FireFox.

Yang ane salut, nih Add On gak bikin Koneksi jadi lemot, Selain itu FireFox juga gak pernah Crash atau Error.

Penasaran...?? Coba saja langsung :
1. Daftar Dulu Jadi member Disini : MyBrowserCash
2. Kalau sudah terdaftar,

Minggu, 25 September 2011

AOP and duck typing in Delphi

AOP - something that fascinated me from the very first moment when my coworker told me about PostSharp. Unfortunately something that was almost impossible in Delphi without the proper knowledge of assembler and all the internal low level stuff. However even with Delphi 7 it was possible to a certain degree to intercept virtual methods using MeAOP.

With the recent additions (namely enhanced RTTI) it became very easy to introduce this feature in a more safe way. However this is nothing compared to a framework like PostSharp which is able to enhance almost everything using IL weaving. Currently you can intercept any virtual method that has RTTI (by default any public/published method). It is very similar to what DynamicProxy does. Delphi XE introduced the TVirtualMethodInterceptor that made it possible to intercept the virtual method calls of an existing object. This is done by creating a new VMT at runtime and attaching it to the object. I went a step further and made it possible to patch any existing class VMT so that any object of this class (and every derived class if you wish) can be intercepted. You can add any aspect to any method you like (if it is virtual and has RTTI). There is currently one built-in aspect for logging which logs entering and leaving the method, all parameters and the result if there is one. You can find a simple demonstration on how to instrument two virtual methods to show logging in the SVN repository.

Did you ever face the problem of having a dependency in your code that you could not remove so simply? Like having that class in your code that is passed around but not being part of your source code so you cannot mock it out? Well you could inherit that class and implement some interface so you just have the dependency on that interface. Yes if that class is not sealed (did you know you can use that keyword in Delphi?). To be honest I haven't seen anyone using this yet (could be because I mostly work with sourcecode written in Delphi 7). But let's say you have a class that is sealed and you want to remove the dependency. You could write an abstract wrapper class and then inherit from it to remove the dependency from your code. Sounds like a lot of work, right?  How about duck typing?





When you look at what duck typing means this is very similar to as if the class implements a specific interface. "Walks like a duck and swims like a duck and quacks like a duck" basically means it got these 3 methods. Like implementing IDuck with these 3 methods. But duck typing does not require the class to implement this interface. Prism got duck typing just recently and DSharp now got it too! (only for XE2 yet, sorry) Of course no compile time support but something similar to what the RemObject guys call soft interfaces and dynamic duck typing mode.

Here is the program from the wikipedia page in Delphi!

program DuckTypingSample;

{$APPTYPE CONSOLE}

uses
DSharp.Core.DuckTyping;

type
IDuck = interface(IInvokable)
procedure Quack;
procedure Feathers;
end;

TDuck = class(TInterfacedObject, IDuck)
public
procedure Quack;
procedure Feathers;
end;

TPerson = class
public
procedure Quack;
procedure Feathers;
procedure Name;
end;

{ TDuck }

procedure TDuck.Feathers;
begin
Writeln('The duck has white and gray feathers.');
end;

procedure TDuck.Quack;
begin
Writeln('Quaaaaaack!');
end;

{ TPerson }

procedure TPerson.Feathers;
begin
Writeln('The person takes a feather from the ground and shows it.');
end;

procedure TPerson.Name;
begin
Writeln('John Smith');
end;

procedure TPerson.Quack;
begin
Writeln('The person imitates a duck.');
end;

procedure InTheForest(duck: IDuck);
begin
duck.quack();
duck.feathers();
end;

var
donald: IDuck;
john: TPerson;
begin
donald := TDuck.Create;
john := TPerson.Create;
InTheForest(donald);
InTheForest(Duck<IDuck>(john));
john.Free;
Readln;
end.

Notice how this is different from dynamic typing you could do with invokable variants. Like the variants approach the evaluation is done at runtime. But in this case you have more type safety. Instead of just passing a variant to the InTheForest procedure and not having any type safety (you could also write duck.Bark() and compiler would not complain) you only can call methods of the IDuck interface. If the wrapped object does not have the required method (also matching parameters) it throws the not implemented exception.

What is it good for? This can open up certain parts of your application to unit testing and mocking that you could not do before because you had lots of static dependencies that could not be mocked. And of course to show that Delphi is catching up. ;)

Sabtu, 24 September 2011

DSharp Bindings vs LiveBindings

I think it's finally time to compare these two things and see which one may fit you better. This is my point of view that may not be completely objective.

When I noticed that there was actually no language support for LiveBindings I was very disappointed. I think without language support you cannot create anything that works much different from how DSharp Bindings work. And actually LiveBindings don't. I could not just change the VCL source code so I had so come up with some "hack" (using the interceptor pattern by including the VCLControls unit that subclasses the supported VCL controls). Of course the guys at Embarcadero had the power to change the VCL classes and that is why they implemented the observer pattern into TComponent I guess. Did you notice that is not that easy to connect simple TObject descendants with LiveBindings? Another thing is that you cannot just connect your Edit to some other component, set up the binding and it works. You still have to write code into your OnChange event because the observer only is activated when you use TBindLink. And this will usually set your edit to read only unless the SourceComponent implements some specific interface. I am very sure the whole BindLink part of the LiveBindings was only for enabling data sensitive controls for FireMonkey (something I have not looked much at yet).

In my opinion for simple bindings like displaying some address or customer Data the point goes to DSharp. It "just works" instead of having to write extra code which should not be required because that's the purpose of bindings.

So what about more complex data like displaying a list of objects in a grid? DSharp does not support any grids yet but it got support for listview, treeview and the virtual treeview. Supporting the stringgrid is on the list and will definitely come. How does it work? Well you just connect your list to the view property of the supported control and you specify a data template that needs to be written in delphi. In fact it turns out to be a bit more complex sometimes. When using the virtual treeview and the treeview presenter you want to specify the columns and then you can bind these columns to the properties of your objects in the list. Have you tried yet to bind a list to some listview or stringgrid using LiveBindings? I have and I failed. To be honest I gave up very quick because this was just so cumbersome and required several string based expressions. Did I mention that the documentation on the new features in XE2 especially LiveBindings sucks? Well yeah my documentation does as well, but I don't have a documentation team working for me, right?

Again DSharp Bindings are focused on doing simple things very easily without locking you out when you want to do more complex things. LiveBindings are very unintuitive to use. I think this point also goes to DSharp.

What about connecting your dataset to some controls? This is something I haven't done since ages (except when working with a grid) but this is where LiveBindings got their power - as I said earlier I think their major task is doing exactly this. Unfortunately the designtime support for this is only enabled in FireMonkey but in VCL you have the DB controls anyway. DSharp just does not support this. I have thought about implementing it but I don't see the point. If you want to use datasets just use db controls which have been working for ages. In FireMonkey you just connect your edit to a field with a few clicks.

Point for LiveBindings.

As you may know there is some expression engine sitting below the LiveBindings that can do some nice things like calculating, concatenate strings and much more. There are built-in functions that can be used (like UpperCase, Round or FormatDateTime). I am happy to tell you that DSharp got an integration with DWS just yesterday. So you can basically use everything that DWS can do in your bindings. From making your text capital letters to doing complex calculations or even evaluating business rules if you like. Since DWS is a real scripting engine you have way more power than the LiveBindings expression engine..

I am very sure with this latest addition this point goes to DSharp.

If you don't trust open source because it may not be continued in the future or does not give you the feeling of safety you may use LiveBindings. Also LiveBindings are ahead regarding designtime support - even if it is kind of cumbersome setting them up sometimes.

For being the "official solution" LiveBindings deserve this point.

So the final score is 3 to 2 for DSharp in my opinion. Again I have not been digging through tons of samples and documentation and since Embarcadero always just shows tons of fancy stuff in FireMonkey, other platforms and so on the documentation on this feature is not very present. I like simple solutions to simple problems. I totally hate full blown over-engineered solutions that are a pain to use in your daily business. And I have the feeling LiveBindings are over-engineered and not well designed. Otherwise they would be easy to use like throwing an edit and a button and the form and make them work, right?

If you like using data bindings in any Delphi 2010 or newer you should definitely take a look at DSharp. Also there is much more in it than just data bindings.

Minggu, 18 September 2011

Pimp your unit tests using mock objects

Have you ever faced the problem of having dependencies in your unit tests that made it hard to actually write a unit test instead of writing an integration test? Often you have that problem with bad designed code that does not follow certain principles. But also with well designed code you might end up having your one class you want to test which depends on 3 other classes which might as well depend on other classes. At this point you actually benefit from well designed code. You can use so called mock objects in your unit tests.

Wikipedia describes them as "simulated objects that mimic the behavior of real objects in controlled ways". Other programming languages like Java and C# are using them for years and in fact also for Delphi there are some mocking frameworks. The problem with the existing frameworks in Delphi are that they either rely on generated code (like Delphi Mock Wizard) or strings for defining the expected method calls (like PascalMock).

In the past I already showed you some cool things I found in Emballo (which was developed in Delphi 2009 before the new enhanced RTTI was introduced). The author used a technique similar to what was introduced in Delphi XE in form of TVirtualMethodInterceptor but in a more limited way due to the lack of TValue and generics. With his permission I used this concept to create a more advanced version of mocking for Delphi. It was also inspired by NMock and in the following I will use the example from their tutorial to show you what you can do with DSharp Mock.

First let's see what it can do and what not. As it depends on TVirtualMethodInterceptor you can only mock virtual methods that can be seen by RTTI (public and published by default). And you can only use it in Delphi XE and higher. If you are using XE2 you can also mock Interfaces that contain RTTI (inherit them from IInvokable or add the $M+ directive) and have a guid.

In the following example I will use classes and virtual methods (the example from NMock uses interfaces but I also wanted to share this with those of you using XE).

We have a very simple scenario: a class (TAccountService) that can transfer money from one account to another using different currencies. The conversion rate is provided by another class (TCurrencyService). Both classes have abstract base classes (TAccountServiceBase and TCurrencyServiceBase). We now want to unit test our TAccountService without using the concrete TCurrencyService class (which does not even is part of this unit test). Let's take a look at the code:

interface

type
TAccountService = class(TAccountServiceBase)
private
FCurrencyService: TCurrencyServiceBase;
public
constructor Create(ACurrencyService: TCurrencyServiceBase);

procedure TransferFunds(
ASource, ATarget: TAccount; AAmount: Currency); override;
end;

implementation

constructor TAccountService.Create(ACurrencyService: TCurrencyServiceBase);
begin
FCurrencyService := ACurrencyService;
end;

procedure TAccountService.TransferFunds(
ASource, ATarget: TAccount; AAmount: Currency);
begin
ASource.Withdraw(AAmount);
ATarget.Deposit(AAmount);
end;

Our currency service base class looks as simple as this:
type
TCurrencyServiceBase = class
public
function GetConversionRate(AFromCurrency,
AToCurrency: string): Double; virtual; abstract;
end;

Now let's create our test method to check if the TransferFunds method works correct.

procedure TCurrencyServiceTest.TransferFunds_UsesCurrencyService;
var
LAmericanAccount: TAccount;
LGermanAccount: TAccount;
begin
LAmericanAccount := TAccount.Create('12345', 'USD');
LGermanAccount := TAccount.Create('54321', 'EUR');
LGermanAccount.Deposit(100);

FMockCurrencyService.WillReturn<Double>(1.38)
.Once.WhenCalling.GetConversionRate('EUR', 'USD');
try
FAccountService.TransferFunds(LGermanAccount, LAmericanAccount, 100);

Verify.That(LGermanAccount.Balance, ShouldBe.EqualTo<Double>(0));
Verify.That(LAmericanAccount.Balance, ShouldBe.EqualTo<Double>(138));

FMockCurrencyService.Verify();
finally
LAmericanAccount.Free();
LGermanAccount.Free();
end;
end;

First we are setting up 2 dummy accounts and deposit 100 euro on the german account.

After that it gets interesting. We define that the currency service will return 1.38 once when the method GetConversionRate gets called with the exact arguments.

After that we are calling the method we want to test. We are transferring 100 euro from the german account to the american account.

Then we want to check if this transfer went correct. So we are checking if the balance on the german account is 0 and the american account has a balance of 138 us dollars. You could use the regular Check methods of DUnit just like I did at first. Unfortunatly I ran into the problem with comparing floating numbers and the test failed for values that should be equal. This is because the DUnit CheckEquals method doesnt have overloads for all the floating types and it does not take the imprecision into account like for example the Math.SameValue functions. Also they are not easily to read in my opinion.

There is some extension for DUnit out there called DUnitLite that does something similar. Anyway also NMock has this Verify class that makes use of fluent interface syntax to make your checks more readable - almost like a real sentence. Internally it uses the DUnit exceptions so you will see some nice message when your check fails.

You probably already noticed that we were missing the call to the currency service so the transfer went wrong and we only have 100 us dollars on that account. Our unit test is telling us: "Expected: "? = 138" Actual: 100" That is what happens if you convert prices one to one. Good thing we would never do that and we fix that in our method.

procedure TAccountService.TransferFunds(
ASource, ATarget: TAccount; AAmount: Currency);
var
LConversionRate: Double;
LConvertedAmount: Currency;
begin
ASource.Withdraw(AAmount);
LConversionRate := FCurrencyService.GetConversionRate(
ASource.Currency, ATarget.Currency);
LConvertedAmount := AAmount * LConversionRate;
ATarget.Deposit(LConvertedAmount);
end;

Now our test runs successful. But there was one more line in our unit test we did not talk about yet. The Verify method checks if all expected method calls were made and none was missing. Any unexpected method call would have caused a failure immediately. For example if we swapped the currencies by mistake.

For the full syntax provided and how to set up mocks look at the sample in the repository. I am working on writing documentation for DSharp (thanks Paul for a Documentation Insight license) so it will be easier for you to understand and use in the future.

I think this possibility of writing your unit tests in a more declarative way without having to write a whole bunch of code just to mock dependencies makes writing tests more easy and less time consuming. Also reading them is much easier because you can just see what expectations are made on the dependencies and you can find out much easier what caused a test to fail.

As usual you find the source in the SVN repository.

Jumat, 02 September 2011

Delphi XE2 - heating up the hype: playing the matchmaker for VCL and FMX

To be honest, FireMonkey did not interest me much because of the fact that it is not compatible with any VCL application - says the documentation - actually that's not the truth!

To keep the long story short: You can have both in one! (Disclaimer: I did only a few tests and it worked all fine - actually I have no clue if somewhere it's incompatible but I leave that as an exercise to you).

Just create a new FireMonkey form (2D or 3D, doesn't matter) save it and then add it to your VCL application (just accept the warning). You can create your FMX form instance somewhere and just show it - no problem. But what if you want to create some nice control with animations or something and embed it into your existing VCL form? Well, put a TPanel on your VCL form and include the brandnew unit DSharp.Windows.FMXAdapter.pas after the Vcl.ExtCtrls. Then just create your FMX form somewhere and assign it to the new Form property of your Panel - and boom, there you go.

As I said, I just came up with this and it's mostly untested - but that's the case for FireMonkey anyway, isn't it? So I thought this may be very interesting for a few people - especially those that used VGScene before. So have fun creating your shiny and new FMX forms and use them in your existing VCL apps. ;)

Kamis, 01 September 2011

Delphi XE2 - features aside from the hype: TVirtualInterface

While prolly almost everyone was creating fancy FireMonkey or VCL applications for Windows (32-bit and 64-bit), OSX and/or iOS with Delphi XE2 today I took a look at one of my favorite units in the RTL - System.Rtti.pas.

When you look at the RTL Changes for XE2 you will see a new addition to the RTTI - TVirtualInterface. Along with this comes another improvement: RTTI can finally tell the implemented interfaces of a class (and its ancestors). But back to the TVirtualInterface!

Documentation says: "Provides functionality for remote procedure call marshaling. TVirtualInterface creates an implementation of an interface at run time." Wow, this sounds interesting. Further reading states that it's main purpose is SOAP messaging. A client can consume a service with several methods just by calling them through an interface which then "just calls" the remote methods of the service. I think this is awesome because it leads to clear defined interfaces (literally) when working with remote services or other things that just hide behind the interface and which are not necessary to be known. Other things I say...

Some while ago when I came across the Emballo Framework I was impressed by the DLLWrapper which basically imports exported functions of a DLL and provides them through an interface. Of course there have to be some rules like the calling conventions and the parameters have to match. But you can do define an interface like this:

type

IMyLibrary = interface

['{8B47F556-673B-44D6-8F90-09985B3C53E0}']

function SayHello: string

end;

And then simply import a DLL which exports this function and just call it. It was a bit rough and actually only supported a few types and not all calling conventions. So I am very happy to have a tool out of the box that makes it possible to write something like this:

if Supports('MyLibrary.dll', IMyLibrary, LMyLibraryIntf) then

ShowMessage(LMyLibraryIntf.SayHello());


Those of you that worked with .Net in RAD Studio 2007 may know this - it was called Virtual Library Interfaces. I have not tried yet, but I am sure if you have the correct signature in your interfaces methods you can call almost every DLL. Actually the Supports functions does not exist in Delphi but you can find it in the brand new unit DSharp.Core.Plugins.

I uploaded a simple sample how to use this (including the new unit which can also be downloaded from the svn repository).

I also added the DSharp packages for XE2 today (only 32-bit for now, 64-bit compatibility will follow soon). I know there is some issue with the asm code in the DSharp.Core.Events (that has to go for 64-bit anyway) which break bindings for now - but I am working on it. Also more about LiveBindings vs DSharp soon.

Kamis, 25 Agustus 2011

CARA MUDAH MEMBUAT ISI KONTEN BLOG YANG BERMUTU (NEWBIE AYO NGUMPULLLL)








Nih ide baru Muncul kemarin setelah berpuasa sehari penuh...hehehee apa hubungannya cobak...?? Sebagai pengingat aja, kalau ane nulis ini waktu Bulan Ramadhan...

Ok kita lanjut ke Trik...
Kali ini buat yang mau Bikin Konten keren,tapi gak punya ide buat nulis atau mungkin punya ide tapi gak tau apa yang mau di tulis

Fungsi dari Trik ini :
1. Anti Duplikat Konten
2. Konten Blog

Minggu, 21 Agustus 2011

TRIK DAPAT DOLLAR DENGAN MENYEBAR GAMBAR





Mungkin udah jadul,
tapi apa salahnya berbagi ..kali aja ada yang belum tahu... ^_^
Kali ini kita cari minimal $100 perbulan....Jiah langsung semangat dengar $100,..hehehe tapi itu beneran

Target kita kali ini  "Share picture", kita dibayar kalau gambar kita di klik , bukan itu saja, kita juga bisa mendapatkan pembayaran dobel, kalau gambar kita di digabung dengan iklan dari "

Rabu, 17 Agustus 2011

LiveBindings - what do you expect?

Since the start of the RAD Studio XE2 World Tour the word is out. Delphi XE2 will have 64-bit compiler, support for OSX and iOS applications with their new FireMonkey GUI framework and LiveBindings. If you haven't read the detailed RAD STUDIO XE2: Launch Event Report yet - now is the time to do it.

When I heared about some built-in data binding architecture for the first time I was very excited. It was just a headword on the roadmap for Project "Wheelhouse" but now we know it will be coming with XE2!

Unfortunately there have been much more informations and speculations about the 64-bit compiler, the support for other operating systems and the FireMonkey framework than for those LiveBindings.

On the official Embarcadero forums there has been some discussion about what to expect. WPF and Cocoa have been mentioned. It has also been mentioned in Auckland that there will be some expression engine to do more than just simply add the TCustomer.LastName property to some TEdit.Text but use some kind of scripting. How will this work? Will there be some designtime support for it to make sure you don't have typos in it (one of the major drawbacks in my current implementation)? Also will the whole binding architecture be supported by new language features to make it save at compile time (like property references or built-in change notifications)?

Lots of questions but only few informations (yet). But we can guess, speculate and wish. So please feel free and leave a comment about what you expect from LiveBindings in Delphi XE2.

Selasa, 16 Agustus 2011

recetas de minercraft

Recetas Básicas









Nombre Ingredientes Entra » Sale Descripción
Madera Troncos CraftingWoodIO.png Usado para construcciones de todo tipo, puede usarse para elaborar multitud de cosas.
Palos Madera CraftingStickIO.png Usado para elaborar antorchas, flechas, carteles, escaleras, vallas y mangos de herramientas.
Antorchas Palo + Carbón CraftingTorchIO.png Usado para crear luz. Las antorchas también funden la nieve y el hielo.
Banco de trabajo Madera CraftingWorkbenchIO.png Permite acceder al grid de elaboración de 3x3.
Horno Piedra CraftingFurnaceIO.png Permite al jugador Fundir cosas.
Cofre Madera CraftingChestIO.png Permite guardar bloques y objetos dentro.

Recetas de Bloques















Nombre Ingredientes Entra » Sale Descripción
Bloques de mineral Lingotes de oro o
Lingotes de hierro o
Gemas de Diamante
CraftingBlocksIOanim.gif Permite elaborar bloques a partir de lingotes o gemas de minerales, útiles para un almacenamiento más compacto.
Piedra Brillante Arena de Piedra BrillanteCraftingBrittleGoldBlock.png Tiene las mismas propiedades de luz que los bloques naturales. Romperla devuelve una sola unidad de energía. Nota: Este bloque actúa como una antorcha, y fundirá la nieve y el hielo.
Bloque de tela Hilo CraftingClothIO.png Usado como material de construcción. La tela puede ser obtenida también de las ovejas.
Bloque de TNT Sulfuro + Arena CraftingTNTIO.png Se usa para provocar explosiones, solo 1 de cada 4 de los minerales destrozados con TNT, daran un bloque
Losa de piedra Piedra CraftingStepsIO.png Se usa para hacer escaleras largas. Dos escalones colocados uno sobre otro produce un bloque completo.
Escalones Madera o Piedra CraftingStairsIOanim.gif Usado para hacer escaleras completas.
Bloque de nieve Bolas de nieve CraftingSnowBlockIO.png Se usa para almacenar bolas de nieve o como material de construcción.
Bloque de arcilla Arcilla CraftingClayBlockIO.png Se usa para almacenar arcilla o como material de construcción.
Bloque de ladrillo Ladrillos de arcilla CraftingBrickBlockIO.png Se usa como material de construcción.
Librearía Madera + Libros CraftingBookcaseIO.png Se usa como elemento decorativo.
Caja de Música Madera + Gema de diamante CraftingJukebox.png Reproduce grabaciones.
Jack-O-Lantern Calabaza + Antorcha CraftingJackOLantern.png Funciona como una antorcha, excepto porque sigue brillando debajo del agua.

Recetas de Herramientas














Nombre Ingredientes Entra » Sale Descripción
Hacha Palo + Madera , Cobblestone , Metal , Oro o DiamantesCraftingAxesIOanim.gif Utilizado para talar arboles mas deprisa.
Pico Palo + Madera , Cobblestone , Metal , Oro o DiamantesCraftingPickaxesIOanim.gif Utilizado para destruir rocas y minerales.
Pala Palo + Madera , Cobblestone , Metal , Oro o DiamantesCraftingShovelsIOanim.gif Utilizado excavar tierra, arena, grava, Etc.
Azada Palo + Madera , Cobblestone , Metal , Oro o DiamantesCraftingHoesIOanim.gif Utilizado arar la tierra que permite plantar semillas en ella.
Flint & Steel Flint + Lingote de MetalFlintsteel2.JPG Utilizado para iniciar fuego.
Balde Lingotes de MetalBalde.JPG Utilizado para recojer Agua/Lava/Leche.
Brújula Lingotes de Metal + Polvo de Redstone Brujula.JPG Utilizado para guiarse hacia el Spawn point.
Mapa portátil Papel + Brújula Mapa.jpg Memoriza las áreas que has explorado en el mundo.
Reloj Lingotes de Oro + Polvo de Redstone Reloj.JPG Utilizado para consultar la hora del Dia/Noche.
Caña de Pesca Palo + Hilo de araña Caña.JPG Utilizado para pescar en las Aguas de Minecraft.
Podadora Lingotes de Metal Podadora.JPG Utilizado para extraer lana de las ovejas.

Recetas de Armas






Nombre Ingredientes Entra » Sale Descripción
Espadas Palo + Madera , Cobblestone , Metal , Oro o Diamantes CraftingSwordsIOanim.gif Espada para luchar contra los enemigos de Minecraft.
Arco Palo + Hilo de araña Arco.JPG Arco que permite lanzar flechas contra los enemigos.
Flechas Palo + Flint + Pluma Flechas.JPG Flechas que pueden ser lanzadas por Arcos.

Recetas de Armaduras







Nombre Ingredientes Entra » Sale Descripción
Casco Cuero , Metal , Oro o Diamante CraftingHelmetsIOanim.gif Casco para protejerse de los Enemigos de Minecraft.
Pechera Cuero , Metal , Oro o Diamante Pechera.gif Pechera para protejerse de los Enemigos de Minecraft.
Pantalones Cuero , Metal , Oro o Diamante Pantalones.gif Pantalones para protejerse de los Enemigos de Minecraft.
Botas Cuero , Metal , Oro o Diamante Botas.gif Botas para protejerse de los Enemigos de Minecraft.

Recetas de Transporte








Nombre Ingredientes Entra » Sale Descripción
Minecart Lingotes de Metal Minecart.JPG Utilizado para transportar jugadores o Animales a traves de la pista.
Minecart Impulsador Minecart + Horno Pwminecart.JPG Utilizado para impulsar otros Minecarts.
Minecart Contenedor Minecart + Baúl Cminecart.JPG Utilizado para almacenar objetos dentro del Minecart.
Vias de Minecarts Lingotes de Metal + Palo Minecarts.JPG Utilizado para coordinar la ruta de los Minecarts.
Barco Madera Bote.JPG Utilizado para viajar por el agua.

Recetas de Mecanismos















Nombre Ingredientes Entra » Sale Descripción
Puertas Lingotes de Metal o Madera Puertas.gif Las puertas de madera pueden ser abiertas mediante un Click. Las puertas de Acero pueden ser abiertas por un interruptor y/o Carga electronica (Polvo de Redstone)
Placas de Presión Roca o Madera Pressure.gif Utilizado para enviar una carga electrica cuando esté parado un jugador o un Mob
Escotilla Madera Escotilla.jpg Las escotillas pueden ser abiertas mediante un click.
Botón de piedra Roca Boton.JPG Utilizado para enviar una carga electrica al presionarlo
Antorcha de Redstone Polvo de Redstone + Palo Redstonet.JPG Envia cargas electricas. Tambien puede ser usado para una antorcha de baja iluminación.
Palanca Palo + Cobblestone Palanca.JPG Envia cargas electricas, se turna en Encendido o Apagado.
Bloque de Notas Madera + Polvo de Redstone Bloquedenotas.JPG Toca notas musicales. Haz click izquiero para tocar una misma nota. Click derecho para cambiar el tono. Nota: El sonido de el bloque de notas puede variar sobre que superficie este colocado.
Jukebox Madera + Diamante Jukebox.JPG Reproduce discos. (Nota: Estos pueden ser encontrados al eliminar Mobs)
Dispensador Cobblestone + Arco + Polvo de Redstone Dispensador.JPG El dispensador mantiene objetos en casillas de 3 x 3. Cuando es utilizado con Polvo de Redstone, este lanza objetos como huevos, bolas de nieve, e incluso flechas como si fuese un arco
Repetidor de Redstone Antorcha de Redstone + Roca + Polvo de Redstone Repetidor de Redstone.jpg Funciona como renovador de la corriente eléctrica.
Pistón Madera + Cobblestone + Polvo de Redstone + Lingotes de Metal Pistón.jpg Empuja un bloque. Funciona mediante un interruptor y/o una carga eléctrica.
Pistón Adhesivo Pistón + Slime Ball Pistón Adhesivo.jpg Funciona de misma manera que un pistón regular, pero el bloque queda adherido al pistón.

Recetas de Comida










Nombre Ingredientes Entra » Sale Descripción
Bol Madera Bol.PNG Utilizado para hacer sopa de Hongos
Sopa de Hongos Hongo rojo + Hongo marrón + Bol Sopa.PNG Cura 5 corazones al jugador.
Pan Trigo Pan.PNG Cura 2.5 corazones al jugador.
Azucar Caña de azucar Azucar.PNG Utilizado para hacer Tortas
Tortas Balde de Leche + Azucar + Huevos + Trigo Torta.PNG Se coloca en una superficie. Cura 1.5 Corazones al jugador, puede ser utilizado 6 veces. Los baldes no se pierden en el proceso
Manzana de Oro Bloques de oro + Manzana Manzana.PNG Cura 10 corazones al jugador.
Galleta Trigo + Cacao Galleta.jpg Cada galleta cura la mitad de un corazón.

Recetas de Miscelanéa











Nombre Ingredientes Entra » Sale Descripción
Minerales Bloque de metal o Bloque de oro o Bloque de diamantes o Bloque de Lapiz Lazuli Mineral.gif Extrae los minerales de los bloques.
Pintura Palo +Lana Pintura.PNG Utilizado para decorar la pared.
Cartel Madera + Palo Cartel.PNG Utilizado para colocar textos en los Carteles.
Escalera de mano Palo Escalera.PNG Utilizado para trepar en superficies verticales.
Papel Caña de azucar Papel.PNG Utilizado para crear Libros.
Libro Papel Libro.PNG Utilizado para estantes de Libros.
Vallas Palo Vallas.PNG Utilizado como barrera. La mayoria de los Mobs no pueden saltar sobre el, excepto las arañas.
Cama Madera + Lana Cama.jpg Utilizado para adelantar el paso del tiempo durante la noche y se establece como un nuevo Spawn point.
 

Indah Hidup Copyright © 2012 Fast Loading -- Powered by Blogger