Search Results

Search found 1843 results on 74 pages for 'delphi prism'.

Page 1/74 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Building applications with WPF, MVVM and Prism(aka CAG)

    - by skjagini
    In this article I am going to walk through an application using WPF and Prism (aka composite application guidance, CAG) which simulates engaging a taxi (cab).  The rules are simple, the app would have3 screens A login screen to authenticate the user An information screen. A screen to engage the cab and roam around and calculating the total fare Metered Rate of Fare The meter is required to be engaged when a cab is occupied by anyone $3.00 upon entry $0.35 for each additional unit The unit fare is: one-fifth of a mile, when the cab is traveling at 6 miles an hour or more; or 60 seconds when not in motion or traveling at less than 12 miles per hour. Night surcharge of $.50 after 8:00 PM & before 6:00 AM Peak hour Weekday Surcharge of $1.00 Monday - Friday after 4:00 PM & before 8:00 PM New York State Tax Surcharge of $.50 per ride. Example: Friday (2010-10-08) 5:30pm Start at Lexington Ave & E 57th St End at Irving Pl & E 15th St Start = $3.00 Travels 2 miles at less than 6 mph for 15 minutes = $3.50 Travels at more than 12 mph for 5 minutes = $1.75 Peak hour Weekday Surcharge = $1.00 (ride started at 5:30 pm) New York State Tax Surcharge = $0.50 Before we dive into the app, I would like to give brief description about the framework.  If you want to jump on to the source code, scroll all the way to the end of the post. MVVM MVVM pattern is in no way related to the usage of PRISM in your application and should be considered if you are using WPF irrespective of PRISM or not. Lets say you are not familiar with MVVM, your typical UI would involve adding some UI controls like text boxes, a button, double clicking on the button,  generating event handler, calling a method from business layer and updating the user interface, it works most of the time for developing small scale applications. The problem with this approach is that there is some amount of code specific to business logic wrapped in UI specific code which is hard to unit test it, mock it and MVVM helps to solve the exact problem. MVVM stands for Model(M) – View(V) – ViewModel(VM),  based on the interactions with in the three parties it should be called VVMM,  MVVM sounds more like MVC (Model-View-Controller) so the name. Why it should be called VVMM: View – View Model - Model WPF allows to create user interfaces using XAML and MVVM takes it to the next level by allowing complete separation of user interface and business logic. In WPF each view will have a property, DataContext when set to an instance of a class (which happens to be your view model) provides the data the view is interested in, i.e., view interacts with view model and at the same time view model interacts with view through DataContext. Sujith, if view and view model are interacting directly with each other how does MVVM is helping me separation of concerns? Well, the catch is DataContext is of type Object, since it is of type object view doesn’t know exact type of view model allowing views and views models to be loosely coupled. View models aggregate data from models (data access layer, services, etc) and make it available for views through properties, methods etc, i.e., View Models interact with Models. PRISM Prism is provided by Microsoft Patterns and Practices team and it can be downloaded from codeplex for source code,  samples and documentation on msdn.  The name composite implies, to compose user interface from different modules (views) without direct dependencies on each other, again allowing  loosely coupled development. Well Sujith, I can already do that with user controls, why shall I learn another framework?  That’s correct, you can decouple using user controls, but you still have to manage some amount of coupling, like how to do you communicate between the controls, how do you subscribe/unsubscribe, loading/unloading views dynamically. Prism is not a replacement for user controls, provides the following features which greatly help in designing the composite applications. Dependency Injection (DI)/ Inversion of Control (IoC) Modules Regions Event Aggregator  Commands Simply put, MVVM helps building a single view and Prism helps building an application using the views There are other open source alternatives to Prism, like MVVMLight, Cinch, take a look at them as well. Lets dig into the source code.  1. Solution The solution is made of the following projects Framework: Holds the common functionality in building applications using WPF and Prism TaxiClient: Start up project, boot strapping and app styling TaxiCommon: Helps with the business logic TaxiModules: Holds the meat of the application with views and view models TaxiTests: To test the application 2. DI / IoC Dependency Injection (DI) as the name implies refers to injecting dependencies and Inversion of Control (IoC) means the calling code has no direct control on the dependencies, opposite of normal way of programming where dependencies are passed by caller, i.e inversion; aside from some differences in terminology the concept is same in both the cases. The idea behind DI/IoC pattern is to reduce the amount of direct coupling between different components of the application, the higher the dependency the more tightly coupled the application resulting in code which is hard to modify, unit test and mock.  Initializing Dependency Injection through BootStrapper TaxiClient is the starting project of the solution and App (App.xaml)  is the starting class that gets called when you run the application. From the App’s OnStartup method we will invoke BootStrapper.   namespace TaxiClient { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e);   (new BootStrapper()).Run(); } } } BootStrapper is your contact point for initializing the application including dependency injection, creating Shell and other frameworks. We are going to use Unity for DI and there are lot of open source DI frameworks like Spring.Net, StructureMap etc with different feature set  and you can choose a framework based on your preferences. Note that Prism comes with in built support for Unity, for example we are deriving from UnityBootStrapper in our case and for any other DI framework you have to extend the Prism appropriately   namespace TaxiClient { public class BootStrapper: UnityBootstrapper { protected override IModuleCatalog CreateModuleCatalog() { return new ConfigurationModuleCatalog(); } protected override DependencyObject CreateShell() { Framework.FrameworkBootStrapper.Run(Container, Application.Current.Dispatcher);   Shell shell = new Shell(); shell.ResizeMode = ResizeMode.NoResize; shell.Show();   return shell; } } } Lets take a look into  FrameworkBootStrapper to check out how to register with unity container. namespace Framework { public class FrameworkBootStrapper { public static void Run(IUnityContainer container, Dispatcher dispatcher) { UIDispatcher uiDispatcher = new UIDispatcher(dispatcher); container.RegisterInstance<IDispatcherService>(uiDispatcher);   container.RegisterType<IInjectSingleViewService, InjectSingleViewService>( new ContainerControlledLifetimeManager());   . . . } } } In the above code we are registering two components with unity container. You shall observe that we are following two different approaches, RegisterInstance and RegisterType.  With RegisterInstance we are registering an existing instance and the same instance will be returned for every request made for IDispatcherService   and with RegisterType we are requesting unity container to create an instance for us when required, i.e., when I request for an instance for IInjectSingleViewService, unity will create/return an instance of InjectSingleViewService class and with RegisterType we can configure the life time of the instance being created. With ContaienrControllerLifetimeManager, the unity container caches the instance and reuses for any subsequent requests, without recreating a new instance. Lets take a look into FareViewModel.cs and it’s constructor. The constructor takes one parameter IEventAggregator and if you try to find all references in your solution for IEventAggregator, you will not find a single location where an instance of EventAggregator is passed directly to the constructor. The compiler still finds an instance and works fine because Prism is already configured when used with Unity container to return an instance of EventAggregator when requested for IEventAggregator and in this particular case it is called constructor injection. public class FareViewModel:ObservableBase, IDataErrorInfo { ... private IEventAggregator _eventAggregator;   public FareViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; InitializePropertyNames(); InitializeModel(); PropertyChanged += OnPropertyChanged; } ... 3. Shell Shells are very similar in operation to Master Pages in asp.net or MDI in Windows Forms. And shells contain regions which display the views, you can have as many regions as you wish in a given view. You can also nest regions. i.e, one region can load a view which in itself may contain other regions. We have to create a shell at the start of the application and are doing it by overriding CreateShell method from BootStrapper From the following Shell.xaml you shall notice that we have two content controls with Region names as ‘MenuRegion’ and ‘MainRegion’.  The idea here is that you can inject any user controls into the regions dynamically, i.e., a Menu User Control for MenuRegion and based on the user action you can load appropriate view into MainRegion.    <Window x:Class="TaxiClient.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism" Title="Taxi" Height="370" Width="800"> <Grid Margin="2"> <ContentControl Regions:RegionManager.RegionName="MenuRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />   <ContentControl Grid.Row="1" Regions:RegionManager.RegionName="MainRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" /> <!--<Border Grid.ColumnSpan="2" BorderThickness="2" CornerRadius="3" BorderBrush="LightBlue" />-->   </Grid> </Window> 4. Modules Prism provides the ability to build composite applications and modules play an important role in it. For example if you are building a Mortgage Loan Processor application with 3 components, i.e. customer’s credit history,  existing mortgages, new home/loan information; and consider that the customer’s credit history component involves gathering data about his/her address, background information, job details etc. The idea here using Prism modules is to separate the implementation of these 3 components into their own visual studio projects allowing to build components with no dependency on each other and independently. If we need to add another component to the application, the component can be developed by in house team or some other team in the organization by starting with a new Visual Studio project and adding to the solution at the run time with very little knowledge about the application. Prism modules are defined by implementing the IModule interface and each visual studio project to be considered as a module should implement the IModule interface.  From the BootStrapper.cs you shall observe that we are overriding the method by returning a ConfiguratingModuleCatalog which returns the modules that are registered for the application using the app.config file  and you can also add module using code. Lets take a look into configuration file.   <?xml version="1.0"?> <configuration> <configSections> <section name="modules" type="Microsoft.Practices.Prism.Modularity.ModulesConfigurationSection, Microsoft.Practices.Prism"/> </configSections> <modules> <module assemblyFile="TaxiModules.dll" moduleType="TaxiModules.ModuleInitializer, TaxiModules" moduleName="TaxiModules"/> </modules> </configuration> Here we are adding TaxiModules project to our solution and TaxiModules.ModuleInitializer implements IModule interface   5. Module Mapper With Prism modules you can dynamically add or remove modules from the regions, apart from that Prism also provides API to control adding/removing the views from a region within the same module. Taxi Information Screen: Engage the Taxi Screen: The sample application has two screens, ‘Taxi Information’ and ‘Engage the Taxi’ and they both reside in same module, TaxiModules. ‘Engage the Taxi’ is again made of two user controls, FareView on the left and TotalView on the right. We have created a Shell with two regions, MenuRegion and MainRegion with menu loaded into MenuRegion. We can create a wrapper user control called EngageTheTaxi made of FareView and TotalView and load either TaxiInfo or EngageTheTaxi into MainRegion based on the user action. Though it will work it tightly binds the user controls and for every combination of user controls, we need to create a dummy wrapper control to contain them. Instead we can apply the principles we learned so far from Shell/regions and introduce another template (LeftAndRightRegionView.xaml) made of two regions Region1 (left) and Region2 (right) and load  FareView and TotalView dynamically.  To help with loading of the views dynamically I have introduce an helper an interface, IInjectSingleViewService,  idea suggested by Mike Taulty, a must read blog for .Net developers. using System; using System.Collections.Generic; using System.ComponentModel;   namespace Framework.PresentationUtility.Navigation {   public interface IInjectSingleViewService : INotifyPropertyChanged { IEnumerable<CommandViewDefinition> Commands { get; } IEnumerable<ModuleViewDefinition> Modules { get; }   void RegisterViewForRegion(string commandName, string viewName, string regionName, Type viewType); void ClearViewFromRegion(string viewName, string regionName); void RegisterModule(string moduleName, IList<ModuleMapper> moduleMappers); } } The Interface declares three methods to work with views: RegisterViewForRegion: Registers a view with a particular region. You can register multiple views and their regions under one command.  When this particular command is invoked all the views registered under it will be loaded into their regions. ClearViewFromRegion: To unload a specific view from a region. RegisterModule: The idea is when a command is invoked you can load the UI with set of controls in their default position and based on the user interaction, you can load different contols in to different regions on the fly.  And it is supported ModuleViewDefinition and ModuleMappers as shown below. namespace Framework.PresentationUtility.Navigation { public class ModuleViewDefinition { public string ModuleName { get; set; } public IList<ModuleMapper> ModuleMappers; public ICommand Command { get; set; } }   public class ModuleMapper { public string ViewName { get; set; } public string RegionName { get; set; } public Type ViewType { get; set; } } } 6. Event Aggregator Prism event aggregator enables messaging between components as in Observable pattern, Notifier notifies the Observer which receives notification it is interested in. When it comes to Observable pattern, Observer has to unsubscribes for notifications when it no longer interested in notifications, which allows the Notifier to remove the Observer’s reference from it’s local cache. Though .Net has managed garbage collection it cannot remove inactive the instances referenced by an active instance resulting in memory leak, keeping the Observers in memory as long as Notifier stays in memory.  Developers have to be very careful to unsubscribe when necessary and it often gets overlooked, to overcome these problems Prism Event Aggregator uses weak references to cache the reference (Observer in this case)  and releases the reference (memory) once the instance goes out of scope. Using event aggregator is very simple, declare a generic type of CompositePresenationEvent by inheriting from it. using Microsoft.Practices.Prism.Events; using TaxiCommon.BAO;   namespace TaxiCommon.CompositeEvents { public class TaxiOnMoveEvent:CompositePresentationEvent<TaxiOnMove> { } }   TaxiOnMove.cs includes the properties which we want to exchange between the parties, FareView and TotalView. using System;   namespace TaxiCommon.BAO { public class TaxiOnMove { public TimeSpan MinutesAtTweleveMPH { get; set; } public double MilesAtSixMPH { get; set; } } }   Lets take a look into FareViewodel (Notifier) and how it raises the event.  Here we are raising the event by getting the event through GetEvent<..>() and publishing it with the payload private void OnAddMinutes(object obj) { TaxiOnMove payload = new TaxiOnMove(); if(MilesAtSixMPH != null) payload.MilesAtSixMPH = MilesAtSixMPH.Value; if(MinutesAtTweleveMPH != null) payload.MinutesAtTweleveMPH = new TimeSpan(0,0,MinutesAtTweleveMPH.Value,0);   _eventAggregator.GetEvent<TaxiOnMoveEvent>().Publish(payload); ResetMinutesAndMiles(); } And TotalViewModel(Observer) subscribes to notifications by getting the event through GetEvent<..>() namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { .... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; ... }   private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>() .Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>() .Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>() .Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   ... private void OnTaxiMove(TaxiOnMove taxiOnMove) { OnMoveFare fare = new OnMoveFare(taxiOnMove); Fares.Add(fare); SetTotalFare(new []{fare}); }   .... 7. MVVM through example In this section we are going to look into MVVM implementation through example.  I have all the modules declared in a single project, TaxiModules, again it is not necessary to have them into one project. Once the user logs into the application, will be greeted with the ‘Engage the Taxi’ screen which is made of two user controls, FareView.xaml and TotalView.Xaml. As you can see from the solution explorer, each of them have their own code behind files and  ViewModel classes, FareViewMode.cs, TotalViewModel.cs Lets take a look in to the FareView and how it interacts with FareViewModel using MVVM implementation. FareView.xaml acts as a view and FareViewMode.cs is it’s view model. The FareView code behind class   namespace TaxiModules.Views { /// <summary> /// Interaction logic for FareView.xaml /// </summary> public partial class FareView : UserControl { public FareView(FareViewModel viewModel) { InitializeComponent(); this.Loaded += (s, e) => { this.DataContext = viewModel; }; } } } The FareView is bound to FareViewModel through the data context  and you shall observe that DataContext is of type Object, i.e. the FareView doesn’t really know the type of ViewModel (FareViewModel). This helps separation of View and ViewModel as View and ViewModel are independent of each other, you can bind FareView to FareViewModel2 as well and the application compiles just fine. Lets take a look into FareView xaml file  <UserControl x:Class="TaxiModules.Views.FareView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" xmlns:Commands="clr-namespace:Microsoft.Practices.Prism.Commands;assembly=Microsoft.Practices.Prism"> <Grid Margin="10" > ....   <Border Style="{DynamicResource innerBorder}" Grid.Row="0" Grid.Column="0" Grid.RowSpan="11" Grid.ColumnSpan="2" Panel.ZIndex="1"/>   <Label Grid.Row="0" Content="Engage the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="1" Content="Select the State"/> <ComboBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding States}" Height="auto"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </ComboBox.ItemTemplate> <ComboBox.SelectedItem> <Binding Path="SelectedState" Mode="TwoWay"/> </ComboBox.SelectedItem> </ComboBox> <Label Grid.Row="2" Content="Select the Date of Entry"/> <Toolkit:DatePicker Grid.Row="2" Grid.Column="1" SelectedDate="{Binding DateOfEntry, ValidatesOnDataErrors=true}" /> <Label Grid.Row="3" Content="Enter time 24hr format"/> <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding TimeOfEntry, TargetNullValue=''}"/> <Button Grid.Row="4" Grid.Column="1" Content="Start the Meter" Commands:Click.Command="{Binding StartMeterCommand}" />   <Label Grid.Row="5" Content="Run the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="6" Content="Number of Miles &lt;@6mph"/> <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding MilesAtSixMPH, TargetNullValue='', ValidatesOnDataErrors=true}"/> <Label Grid.Row="7" Content="Number of Minutes @12mph"/> <TextBox Grid.Row="7" Grid.Column="1" Text="{Binding MinutesAtTweleveMPH, TargetNullValue=''}"/> <Button Grid.Row="8" Grid.Column="1" Content="Add Minutes and Miles " Commands:Click.Command="{Binding AddMinutesCommand}"/> <Label Grid.Row="9" Content="Other Operations" Style="{DynamicResource innerHeader}"/> <Button Grid.Row="10" Grid.Column="1" Content="Reset the Meter" Commands:Click.Command="{Binding ResetCommand}"/>   </Grid> </UserControl> The highlighted code from the above code shows data binding, for example ComboBox which displays list of states has it’s ItemsSource bound to States property, with DataTemplate bound to Name and SelectedItem  to SelectedState. You might be wondering what are all these properties and how it is able to bind to them.  The answer lies in data context, i.e., when you bound a control, WPF looks for data context on the root object (Grid in this case) and if it can’t find data context it will look into root’s root, i.e. FareView UserControl and it is bound to FareViewModel.  Each of those properties have be declared on the ViewModel for the View to bind correctly. To put simply, View is bound to ViewModel through data context of type object and every control that is bound on the View actually binds to the public property on the ViewModel. Lets look into the ViewModel code (the following code is not an exact copy of FareViewMode.cs, pasted relevant code for this section)   namespace TaxiModules.ViewModels { public class FareViewModel:ObservableBase, IDataErrorInfo { public List<USState> States { get { return USStates.StateList; } }   public USState SelectedState { get { return _selectedState; } set { _selectedState = value; RaisePropertyChanged(_selectedStatePropertyName); } }   public DateTime? DateOfEntry { get { return _dateOfEntry; } set { _dateOfEntry = value; RaisePropertyChanged(_dateOfEntryPropertyName); } }   public TimeSpan? TimeOfEntry { get { return _timeOfEntry; } set { _timeOfEntry = value; RaisePropertyChanged(_timeOfEntryPropertyName); } }   public double? MilesAtSixMPH { get { return _milesAtSixMPH; } set { _milesAtSixMPH = value; RaisePropertyChanged(_distanceAtSixMPHPropertyName); } }   public int? MinutesAtTweleveMPH { get { return _minutesAtTweleveMPH; } set { _minutesAtTweleveMPH = value; RaisePropertyChanged(_minutesAtTweleveMPHPropertyName); } }   public ICommand StartMeterCommand { get { if(_startMeterCommand == null) { _startMeterCommand = new DelegateCommand<object>(OnStartMeter, CanStartMeter); } return _startMeterCommand; } }   public ICommand AddMinutesCommand { get { if(_addMinutesCommand == null) { _addMinutesCommand = new DelegateCommand<object>(OnAddMinutes, CanAddMinutes); } return _addMinutesCommand; } }   public ICommand ResetCommand { get { if(_resetCommand == null) { _resetCommand = new DelegateCommand<object>(OnResetCommand); } return _resetCommand; } }   } private void OnStartMeter(object obj) { _eventAggregator.GetEvent<TaxiStartedEvent>().Publish( new TaxiStarted() { EngagedOn = DateOfEntry.Value.Date + TimeOfEntry.Value, EngagedState = SelectedState.Value });   _isMeterStarted = true; OnPropertyChanged(this,null); } And views communicate user actions like button clicks, tree view item selections, etc using commands. When user clicks on ‘Start the Meter’ button it invokes the method StartMeterCommand, which calls the method OnStartMeter which publishes the event to TotalViewModel using event aggregator  and TaxiStartedEvent. namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { ... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator;   InitializePropertyNames(); InitializeModel(); SubscribeToEvents(); }   public decimal? TotalFare { get { return _totalFare; } set { _totalFare = value; RaisePropertyChanged(_totalFarePropertyName); } } .... private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>().Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>().Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>().Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   private void OnTaxiStarted(TaxiStarted taxiStarted) { Fares.Add(new EntryFare()); Fares.Add(new StateTaxFare(taxiStarted)); Fares.Add(new NightSurchargeFare(taxiStarted)); Fares.Add(new PeakHourWeekdayFare(taxiStarted));   SetTotalFare(Fares); }   private void SetTotalFare(IEnumerable<IFare> fares) { TotalFare = (_totalFare ?? 0) + TaxiFareHelper.GetTotalFare(fares); } ....   } }   TotalViewModel subscribes to events, TaxiStartedEvent and rest. When TaxiStartedEvent gets invoked it calls the OnTaxiStarted method which sets the total fare which includes entry fee, state tax, nightly surcharge, peak hour weekday fare.   Note that TotalViewModel derives from ObservableBase which implements the method RaisePropertyChanged which we are invoking in Set of TotalFare property, i.e, once we update the TotalFare property it raises an the event that  allows the TotalFare text box to fetch the new value through the data context. ViewModel is communicating with View through data context and it has no knowledge about View, helping in loose coupling of ViewModel and View.   I have attached the source code (.Net 4.0, Prism 4.0, VS 2010) , download and play with it and don’t forget to leave your comments.  

    Read the article

  • The reasons to upgrade from Delphi 2009

    - by Serg
    I have made the question "community wiki" - it is subjective. I have upgraded to Delphi 2009 because of unicode support. I have found the anonymous methods a very interesting and useful language feature, I can't say the same about generics. The generics seemed important for me before the upgrade to Delphi 2009, but I have never used them and probably will never use. As for Delphi 2010, I don't need the attributes and I don't like the whole idea of extended RTTI - that is why Delphi 2009 is better for me. Sometimes I hit one or other annoying bug in Delphi 2009 IDE, but they are not critical and I can live with them. I have no plans to develop software for Mac or Linux. Sure sometime I will need 64-bit support, so I think about upgrading to Delphi 2012. Are where any more reasons that can force me to upgrade from Delphi 2009?

    Read the article

  • Compile Delphi component package (bpl) for different Delphi versions

    - by FractalizeR
    Hello. The situation is the following. Typically I use RAD Studio 2010 for Delphi development. I have some components I would like to redistribute in binary form (*.bpl without source). But I would like people to be able to use them despite of their Delphi version. But, for example, dcu files can be used only by compiler version, which generated them. Almost the same situation is with bpl files as I know. Every bpl file will require corresponding VCLXX.bpl library depending on Delphi version. How do I make my bpls, compiled in 2010 to be able to be used in Delphi7, 2007 etc? Is the only solution to have ALL Delphi versions installed and compile bpl files separately in each?

    Read the article

  • Getting Started with Prism (aka Composite Application Guidance for WPF and Silverlight)

    - by dotneteer
    Overview Prism is a framework from the Microsoft Patterns and Practice team that allow you to create WPF and Silverlight in a modular way. It is especially valuable for larger projects in which a large number of developers can develop in parallel. Prism achieves its goal by supplying several services: · Dependency Injection (DI) and Inversion of control (IoC): By using DI, Prism takes away the responsibility of instantiating and managing the life time of dependency objects from individual components to a container. Prism relies on containers to discover, manage and compose large number of objects. By varying the configuration, the container can also inject mock objects for unit testing. Out of the box, Prism supports Unity and MEF as container although it is possible to use other containers by subclassing the Bootstrapper class. · Modularity and Region: Prism supplies the framework to split application into modules from the application shell. Each module is a library project that contains both UI and code and is responsible to initialize itself when loaded by the shell. Each window can be further divided into regions. A region is a user control with associated model. · Model, view and view-model (MVVM) pattern: Prism promotes the user MVVM. The use of DI container makes it much easier to inject model into view. WPF already has excellent data binding and commanding mechanism. To be productive with Prism, it is important to understand WPF data binding and commanding well. · Event-aggregation: Prism promotes loosely coupled components. Prism discourages for components from different modules to communicate each other, thus leading to dependency. Instead, Prism supplies an event-aggregation mechanism that allows components to publish and subscribe events without knowing each other. Architecture In the following, I will go into a little more detail on the services provided by Prism. Bootstrapper In a typical WPF application, application start-up is controls by App.xaml and its code behind. The main window of the application is typically specified in the App.xaml file. In a Prism application, we start a bootstrapper in the App class and delegate the duty of main window to the bootstrapper. The bootstrapper will start a dependency-injection container so all future object instantiations are managed by the container. Out of box, Prism provides the UnityBootstrapper and MefUnityBootstrapper abstract classes. All application needs to either provide a concrete implementation of one of these bootstrappers, or alternatively, subclass the Bootstrapper class with another DI container. A concrete bootstrapper class must implement the CreateShell method. Its responsibility is to resolve and create the Shell object through the DI container to serve as the main window for the application. The other important method to override is ConfigureModuleCatalog. The bootstrapper can register modules for the application. In a more advance scenario, an application does not have to know all its modules at compile time. Modules can be discovered at run time. Readers to refer to one of the Open Modularity Quick Starts for more information. Modules Once modules are registered with or discovered by Prism, they are instantiated by the DI container and their Initialize method is called. The DI container can inject into a module a region registry that implements IRegionViewRegistry interface. The module, in its Initialize method, can then call RegisterViewWithRegion method of the registry to register its regions. Regions Regions, once registered, are managed by the RegionManager. The shell can then load regions either through the RegionManager.RegionName attached property or dynamically through code. When a view is created by the region manager, the DI container can inject view model and other services into the view. The view then has a reference to the view model through which it can interact with backend services. Service locator Although it is possible to inject services into dependent classes through a DI container, an alternative way is to use the ServiceLocator to retrieve a service on demard. Prism supplies a service locator implementation and it is possible to get an instance of the service by calling: ServiceLocator.Current.GetInstance<IServiceType>() Event aggregator Prism supplies an IEventAggregator interface and implementation that can be injected into any class that needs to communicate with each other in a loosely-coupled fashion. The event aggregator uses a publisher/subscriber model. A class can publishes an event by calling eventAggregator.GetEvent<EventType>().Publish(parameter) to raise an event. Other classes can subscribe the event by calling eventAggregator.GetEvent<EventType>().Subscribe(EventHandler, other options). Getting started The easiest way to get started with Prism is to go through the Prism Hands-On labs and look at the Hello World QuickStart. The Hello World QuickStart shows how bootstrapper, modules and region works. Next, I would recommend you to look at the Stock Trader Reference Implementation. It is a more in depth example that resemble we want to set up an application. Several other QuickStarts cover individual Prism services. Some scenarios, such as dynamic module discovery, are more advanced. Apart from the official prism document, you can get an overview by reading Glen Block’s MSDN Magazine article. I have found the best free training material is from the Boise Code Camp. To be effective with Prism, it is important to understands key concepts of WPF well first, such as the DependencyProperty system, data binding, resource, theme and ICommand. It is also important to know your DI container of choice well. I will try to explorer these subjects in depth in the future. Testimony Recently, I worked on a desktop WPF application using Prism. I had a wonderful experience with Prism. The Prism is flexible enough even in the presence of third party controls such as Telerik WPF controls. We have never encountered any significant obstacle.

    Read the article

  • What components and IDE add-ins do you install with Delphi?

    - by Mick
    After a clean install of Delphi, what components and IDE add-ins do you make certain that you install? What's your Delphi "rig"? Here's what I install after a clean installation: Delphi 2007 JCL / JVCL - JEDI Code Library and JEDI Visual Code Library (600+ components) JWA / JWSCL - JEDI API Library & Security Code Library GExperts - GExperts is a free set of tools built to increase the productivity of Delphi and C++Builder programmers by adding several features to the IDE. TWM's experimental GExperts code formatter - adds code formatting capabilities to Delphi Virtual TreeView - Virtual Treeview is a treeview control built from ground up. More than 5 years of development made it one of the most flexible and advanced tree controls available today. MustangPeak Components (EasyList View, Virtual ShellTools, etc) - EasyListview is a control that has no dependance on the Microsoft Listview control but has all the features of the latest version from Microsoft. Also includes 'Explorer.exe' like shell components. Synapse lightweight networking components - contains simple low level non-visual objects for easy programming without problems. (no required multi-threaded synchronization, no need for windows message processing,…) Great for command line utilities, visual projects, NT services EurekaLog - EurekaLog is a complete bug resolution tool for Delphi and C++Builder developers that gives your application the power to catch every exception and memory leak, directly on the end user PC, generating a detailed log of the call stack (with file, class, method and line number), optionally sending you a copy of each log entry via email or to a web bug-tracker. DelphiSpeedUp - DelphiSpeedUp is an IDE plugin for Delphi and C++Builder. It improves the IDE’s startup speed and increases the general speed of the whole IDE. DDevExtensions - DDevExtensions extends the Delphi/C++Builder IDE by adding some new productivity features. IDE Fix Pack - The IDE Fix Pack installs is a DLL-Expert that fixes the following RAD Studio 2007 bugs at runtime. All changes are done in memory. No file on disk is modified. TPerlRegex - Regular Expression library for Delphi How about other Delphi developers?

    Read the article

  • Upgrade to Delphi 2010, or stick with Delphi 7 "forever"?

    - by tim11g
    I am an individual user of Delphi, starting back in the early Turbo Pascal days. I have quite a bit of code developed over the years, but I have never sold software commercially or used it for business. Historically, Borland supported the non-professional users with lower cost versions, but Embarcadero does not. As I consider upgrading to Delphi 2010, I am put off by the high price. Embarcadero is also trying to "encourage" upgrading by threatening to charge "new user" prices for upgrades after Dec 31st. I have several questions for the community to help me decide whether to upgrade. 1) I have read about difficulties updating existing code to support the unicode string types. I have no need for unicode strings, and I am happy with the string support in D7. Will I have to modify existing code and components just to re-compile under D2010? Or are there compiler options to allow backward compatibility if new string types are not required? 2) The main reason I'm considering upgrading is for IDE improvements, and to get access to new APIs added to Windows since 2002. Are there any Windows 7 APIs or capabilities that would be impossible to support from my programs compiled using using Delphi 7 (assuming appropriate JEDI API libraries, for example)? 3) Is there anything else about Delphi 2010 that is really compelling for someone who is primarily interested in Win32 apps, and not working with databases? I have read that D2010 is slow to load, and other versions between D7 and D2010 have had stability issues, and the help system was "broken". What is the biggest benefit to D2010?

    Read the article

  • Error While Linking Multiple C Object files in Delphi 2007

    - by Ramnish
    Hello Everyone. I am new to delphi. I was trying to add C Object files in my Delphi project and link them directly since Delphi Supports C Object Linking. I got it working when i link a single Object file. But when i try to link multiple object files, i am getting error 'Unsatisfied forward or external declaration'. I have tried this in Delphi 2007 as well as XE.So what am i doing wrong here? Working Code: function a_function():Integer;cdecl; implementation {$Link 'a.obj'} function a_function():Integer;cdecl;external; end. Error Code: function a_function():Integer;cdecl; function b_function();Integer;cdecl; function c_function();Integer;cdecl; implementation {$LINK 'a.obj'} {$LINK 'b.obj'} {$LINK 'c.obj'} function a_function():Integer;cdecl;external; function b_function();Integer;cdecl;external; function c_function();Integer;cdecl;external; end.

    Read the article

  • Will you use Delphi Prism

    - by Mohammed Nasman
    CodeGear announces that their Next .Net product which is known as Delphi Prism Will be RemObjects's Oxygene. Oxygene has many nice features that not found in Delphi or C#, and I think it will be a more effective solution for .Net than Delphi .Net previous releases, but it's uses Visual Studio IDE instead of Delphi IDE. which has some cons and pros. As Delphi Developer or .Net Developer, do you consider to use Delphi Prism for .Net developmenet? Look at these Links for more info. Delphi Prism vs. CSharp Delphi Prism - Visual Studio Pascal For .NET Delphi Prims home page

    Read the article

  • Using ScriptGetProperties with Delphi

    - by Mohammed Nasman
    How can I use ScriptGetProperties API from Uniscribe Dll (usp10.dll) in Delphi I found an example in C++, but I don't know how to translate it, because I'm not good on C. const SCRIPT_PROPERTIES **g_ppScriptProperties; int g_iMaxScript; WCHAR *pwcInChars = L"Unicode string to itemize"; int cInChars = wcslen(pwcInChars); const int cMaxItems = 20; SCRIPT_ITEM si[cMaxItems + 1]; SCRIPT_ITEM *pItems = si; int cItems; ScriptGetProperties(&g_ppScriptProperties, &g_iMaxScript); HRESULT hResult = ScriptItemize(pwcInChars, cInChars, cMaxItems, NULL, NULL, pItems, &cItems); if (hResult == 0) { for (int i=0; i<cItems; i++) { if (g_ppScriptProperties[pItems[i].a.eScript]->fComplex) { // Item [i] is complex script text // requiring glyph shaping. } else { // The text may be rendered legibly without using Uniscribe. // However, Uniscribe may still be used as a means of accessing // font typographic features. } } } else { // Handle the error. } The Delphi code should be complied with Turbo Delphi 2006 or above.

    Read the article

  • Convert Delphi 7 code to work with Delphi 2009

    - by Brad
    I have a String that I needed access to the first character of, so I used stringname[1]. With the unicode support this no longer works. I get an error: [DCC Error] sndkey32.pas(420): E2010 Incompatible types: 'Char' and 'AnsiChar' Example code: //vkKeyScan from the windows unit var KeyString: string; MKey : Word; mkey:=vkKeyScan(KeyString[1]) How would I write this in modern versions of Delphi Thanks -Brad

    Read the article

  • Delphi 2010 Datasnap - Design Query

    - by Matt
    I am investigating moving a thick client SQL based Delphi application to Multi Tier thin clients, and have been looking at using Datasnap in Delphi 2010. I have worked through the White Paper written by Bob Swart and extended this further. My main question really is that I want to make the server side efficient in terms of connections and SQL Queries due to multiple queries being run and remaining open at the same time to interrogate data, can anyone point me in a direction for guidance on how to design a real world Datasnap Server application, as the demo's don't go into enough detail. Thanks Matt

    Read the article

  • Upgrade from Delphi 2007 to Delphi 2010?

    - by Nik
    What should I worry about if I move to Delphi 2007 to 2010? I've checked this article and there was a lot of interesting stuff but not precisely for this jump that I need. To clarify my question and situation: I have all 3td party components' code. I will need the unicode, but not this year. I need win 7 support - themes, form resize problems and etc. I will be happy to have a dissent help system. Is ADO (dbGO) improved? What headache to expect? Thanks!

    Read the article

  • delphi prism online resources

    - by omair iqbal
    google search on ''delphi prism' , ''delphi prism resources'' or ''delphi prism code snippets'' reveal almost no good site at all are there any good programming site(s) with some good amount of code snippets and tutorials on delphi prism thanks in advance

    Read the article

  • open default browser with a post in Delphi

    - by Brad
    I know in delphi you can open the default browser with: ShellExecute(self.WindowHandle,'open','www.website.com',nil,nil, SW_SHOWNORMAL); but I'm wanting to know if there is a way to automatically post data on the new opened brower window OR auto fill the login data (even in firefox, safari,etc) Thanks -Brad

    Read the article

  • Firefox Using Prism Website Icon instead of Firefox Icon in Taskbar

    - by Yaakov Ellis
    A while back, I created a website shortcut using the now discontinued Prism extension for Firefox. This worked fine at the time. However, now that Prism has been discontinued, whenever I open Firefox, when the shortcut for FF shows up my Windows taskbar, it does so with the website favico for the old Prism shortcut site that I created. If I right-click on the taskbar shortcut, it shows the old shortcut to the Prism app (even though I deleted its entry manually from C:\Users\USERNAME\AppData\Roaming\WebApps). If I then click on [Pin to Taskbar] and then right click and [Unpin from Taskbar], the icon will switch back to the FF icon. If I righ-click on it a third time, it will switch back to the Prism site favico. I assume that if I were able to install Prism, then it would give me some way to remove the site. However, since Prism is discontinued and incompatible with the current version of FF, that is not an option. What I would like to do: completely remove references to the Prism app from my computer: Disassociate the prism website Favico from Firefox, so that it never replaces the FF icon in the Windows taskbar Shortcut to the Prism site will never shot up in the right-click menu for FF

    Read the article

  • Unicode problems with Delphi 2009 / 2010 and windows API calls

    - by Charles Faiga
    Hi I have been using this function in Delphi 2006, but now with D2010 it throws an error. I think it is related to the switch to Unicode. Function TWinUtils.GetTempFile(Const Extension: STRING): STRING; Var Buffer: ARRAY [0 .. MAX_PATH] OF char; Begin Repeat GetTempPath(SizeOf(Buffer) - 1, Buffer); GetTempFileName(Buffer, '~~', 0, Buffer); Result := ChangeFileExt(Buffer, Extension); Until not FileExists(Result); End; What should I do to make it work? EDIT I get an 'access violation' when the ChangeFileExt is called

    Read the article

  • create a plugin in Delphi Prism using Hydra (Remobjects)

    - by simon
    Hi, I have to create a plugin in Delphi Prism for Application that is already in Delphi. I have read all about Hydra 3.0 in www.remobjects.com and have some queries. Can you please give me an example how to create custom Interfaces for communication between Delphi Host and .Net Plugin.(either in C# or Delphi Prism) what is the role of ModuleController in Hydra plugin and how it works there? Role of Manager Component? Many Thanks in Advance.

    Read the article

  • Delphi Indy IDHTTP question

    - by user327175
    I am trying to get the captcha image from a AOL, and i keep getting an error 418. unit imageunit; /// /// h t t p s://new.aol.com/productsweb/ /// interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdIntercept, IdZLibCompressorBase, IdCompressorZLib, IdCookieManager, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,jpeg,GIFImg, ExtCtrls; type TForm2 = class(TForm) IdHTTP1: TIdHTTP; IdCookieManager1: TIdCookieManager; IdCompressorZLib1: TIdCompressorZLib; IdConnectionIntercept1: TIdConnectionIntercept; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; Panel1: TPanel; Image1: TImage; Panel2: TPanel; Button1: TButton; Edit1: TEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm2.Button1Click(Sender: TObject); var JPI : TJPEGImage; streamdata:TMemoryStream; begin streamdata := TMemoryStream.Create; try idhttp1.Get(edit1.Text, Streamdata); Except { Handle exceptions } On E : Exception Do Begin MessageDlg('Exception: '+E.Message,mtError, [mbOK], 0); End; End; //h t t p s://new.aol.com/productsweb/WordVerImage?20890843 //h t t p s://new.aol.com/productsweb/WordVerImage?91868359 /// /// gives error 418 unused /// streamdata.Position := 0; JPI := TJPEGImage.Create; Try JPI.LoadFromStream ( streamdata ); Finally Image1.Picture.Assign ( JPI ); JPI.Free; streamdata.Free; End; end; end. Form: object Form2: TForm2 Left = 0 Top = 0 Caption = 'Form2' ClientHeight = 247 ClientWidth = 480 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel Left = 0 Top = 41 Width = 480 Height = 206 Align = alClient TabOrder = 0 ExplicitLeft = -8 ExplicitTop = 206 ExplicitHeight = 41 object Image1: TImage Left = 1 Top = 1 Width = 478 Height = 204 Align = alClient ExplicitLeft = 5 ExplicitTop = 17 ExplicitWidth = 200 ExplicitHeight = 70 end end object Panel2: TPanel Left = 0 Top = 0 Width = 480 Height = 41 Align = alTop TabOrder = 1 ExplicitLeft = 40 ExplicitTop = 32 ExplicitWidth = 185 object Button1: TButton Left = 239 Top = 6 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 0 OnClick = Button1Click end object Edit1: TEdit Left = 16 Top = 8 Width = 217 Height = 21 TabOrder = 1 end end object IdHTTP1: TIdHTTP Intercept = IdConnectionIntercept1 IOHandler = IdSSLIOHandlerSocketOpenSSL1 MaxAuthRetries = 100 AllowCookies = True HandleRedirects = True RedirectMaximum = 100 ProxyParams.BasicAuthentication = False ProxyParams.ProxyPort = 0 Request.ContentLength = -1 Request.Accept = 'image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-s' + 'hockwave-flash, application/cade, application/xaml+xml, applicat' + 'ion/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-' + 'application, /' Request.BasicAuthentication = False Request.Referer = 'http://www.yahoo.com' Request.UserAgent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.1) Gecko/201001' + '22 firefox/3.6.1' HTTPOptions = [hoForceEncodeParams] CookieManager = IdCookieManager1 Compressor = IdCompressorZLib1 Left = 240 Top = 80 end object IdCookieManager1: TIdCookieManager Left = 360 Top = 136 end object IdCompressorZLib1: TIdCompressorZLib Left = 368 Top = 16 end object IdConnectionIntercept1: TIdConnectionIntercept Left = 304 Top = 72 end object IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL Intercept = IdConnectionIntercept1 MaxLineAction = maException Port = 0 DefaultPort = 0 SSLOptions.Mode = sslmUnassigned SSLOptions.VerifyMode = [] SSLOptions.VerifyDepth = 0 Left = 192 Top = 136 end end If you go to: h t t p s://new.aol.com/productsweb/ you will notice the captcha image has a url like: h t t p s://new.aol.com/productsweb/WordVerImage?91868359 I put that url in the edit box and get an error. What is wrong with this code.

    Read the article

  • Delphi Prism and LINQ to SQL / Entity Framework

    - by Vegar
    I have found many posts and examples of using LINQ-syntax in Delphi Prism (Oxygene), but I have never found anything on LINQ to SQL or Entity Framework. Is it possible to use LINQ to SQL or Entity Framework together with Prism? Where can I found such an example? Update: Olaf is giving an answer through his blog The question is now if any visual tools and code generation is provided, or if everything must be done by hand... Second update: Olaf has answered the tool/code generation-question in a comment on his site: The class designer is there, but there is no Pascal code gen. According to marc hoffman that is currently not on their list. For now you have to live with manual mapping. I guess, if you had Visual Studio (not just the VS shell), that you could add a C# library project to your solution, reference that from your Prism project. Then create the Table-Class mapping in the C# project using the visual designer. Maybe somewhat ugly, but possibly the key to get the Designer + CodeGen integrated into Prism. Who cares what language is used for the mapping . I will say this is a 1 - 0 to c# vs prism. If I did not care which language is used for the mapping - why should I care about which language is used for the rest?

    Read the article

  • Delphi - ListView Question

    - by Brad
    Is there a ListView (ListBox) or similar component that allows me to easily drop another component in a specific column. (Multiple columns)? Like a checkbox, button or drop down list or all the above. (It would be nice to be able to sort via the header also) If not does anyone know of a resource on how to custom draw something like this? Thanks -Brad

    Read the article

  • Delphi - Is there a better way to get state abbreviations from state names

    - by Bill
    const states : array [0..49,0..1] of string = ( ('Alabama','AL'), ('Montana','MT'), ('Alaska','AK'), ('Nebraska','NE'), ('Arizona','AZ'), ('Nevada','NV'), ('Arkansas','AR'), ('New Hampshire','NH'), ('California','CA'), ('New Jersey','NJ'), ('Colorado','CO'), ('New Mexico','NM'), ('Connecticut','CT'), ('New York','NY'), ('Delaware','DE'), ('North Carolina','NC'), ('Florida','FL'), ('North Dakota','ND'), ('Georgia','GA'), ('Ohio','OH'), ('Hawaii','HI'), ('Oklahoma','OK'), ('Idaho','ID'), ('Oregon','OR'), ('Illinois','IL'), ('Pennsylvania','PA'), ('Indiana','IN'), ('Rhode Island','RI'), ('Iowa','IA'), ('South Carolin','SC'), ('Kansas','KS'), ('South Dakota','SD'), ('Kentucky','KY'), ('Tennessee','TN'), ('Louisiana','LA'), ('Texas','TX'), ('Maine','ME'), ('Utah','UT'), ('Maryland','MD'), ('Vermont','VT'), ('Massachusetts','MA'), ('Virginia','VA'), ('Michigan','MI'), ('Washington','WA'), ('Minnesota','MN'), ('West Virginia','WV'), ('Mississippi','MS'), ('Wisconsin','WI'), ('Missouri','MO'), ('Wyoming','WY') ); function getabb(state:string):string; var I:integer; begin for I := 0 to length(states) -1 do if lowercase(state) = lowercase(states[I,0]) then begin result:= states[I,1]; end; end; function getstate(state:string):string; var I:integer; begin for I := 0 to length(states) -1 do if lowercase(state) = lowercase(states[I,1]) then begin result:= states[I,0]; end; end; procedure TForm2.Button1Click(Sender: TObject); begin edit1.Text:=getabb(edit1.Text); end; procedure TForm2.Button2Click(Sender: TObject); begin edit1.Text:=getstate(edit1.Text); end; end. Is there a bette way to do this?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >