Search Results

Search found 278 results on 12 pages for 'prism'.

Page 1/12 | 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

  • 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

  • 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

  • Open Source Mozilla Prism Alternative

    - by Patrick Klingemann
    Here is what I want to do, very simply: I want to put a URL into a Mozilla Prism (or some alternative), then be provided with an icon on my desktop that when I click it a window opens and the page is displayed. The process for this instance of Prism should be completely independent of any other Prism "applications" that are running. Prism looks like it does this exactly, but I'm running Fedora 12 x86_64 and I can't get it to work, so I'm wondering if there are any alternatives to Prism.

    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

  • MEF and Prism integration

    - by Wasim
    Hi all , I need your advice deciding on a new project architecture I'm going to implement. Can I use MEF and Prism side by side? Is it too complex to accomplish this? Can make the same stuff Prism does with MEF? Right now, two features Prism gives, but are not in MEF are Regions and the Event Aggregator. Can I do everything else with MEF, rather than Prism? Thanks in advance ...

    Read the article

  • Choosing Between Prism and Caliburn

    - by Innogetics
    I have been using Prism 2.0 for a personal project for a few months now. I have recently heard of Caliburn and am wondering if there are compelling reasons for me to consider that instead. I like Prism's dynamic module loading capability. I intend to build modules for my application and would like to be able to deploy them in a modular manner. Is that also possible with Caliburn? What are the advantages of Caliburn over Prism? (I read that Prism will also have a new version by September 2010 that will leverage .Net 4.0. and am keeping my application flexible to be updated by then as well.)

    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

  • Proper implementation of NLog and Prism

    - by WiT8litZ
    What would be the best way to implement NLog in my Prism / CAL WPF application. This might be an amateur question, I am a bit new to the whole Prism framework :) I thought about putting the reference to the NLog dll in the Infrastructure module and make a wrapper singleton class e.g. MyLogger. My thinking was to be able to have the reference to 1 logger implementation somewhere in a central place that everything has reference to, and the only thing that I know of in Prism would be your Infrastructure module. The obvious other way is to add a reference to NLog to each module but I think that would defeat the purpose of decoupling and all of that. Any ideas would be most helpful Regards

    Read the article

  • Silverlight 4.0 with PRISM

    - by patelsan
    Anybody has experience of building Silverlight with PRISM for LoB applications? If so, please share your experiences. I am planning to use PRISM with SL 4, in past I used Silverlight.FX with SL 3.

    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

  • Prism - loading modules causes activation error

    - by Noich
    I've created a small Prism application (using MEF) with the following parts: - Infrastructure project, that contains a global file of region names. - Main project, that has 2 buttons to load other modules. - ModulesInterfaces project, where I've defined an IDataAccess interface for my DataAccess module. - DataAccess project, where there are several files but one main DataAccess class that implements both IDataAccess and IModule. When the user click a button, I want to show him a list of employees, so I need the DataAccess module. My code is as follows: var namesView = new EmployeesListView(); var namesViewModel = new EmployeesListViewModel(employeeRepository); namesView.DataContext = namesViewModel; namesViewModel.EmployeeSelected += EmployeeSelected; LocateManager(); manager.Regions["ContentRegion"].Add(new NoEmployeeView(), "noEmployee"); manager.Regions["NavigationRegion"].Add(namesView); I get an exception in my code when I'm trying to get DataAccess as a service (via ServiceLocator). I'm not sure if that's the right way to go, but trying to get it from the ModuleCatalog (as a type IDataAccess returns an empty enumeration). I'd appreciate some directions. Thanks. The problematic code line: object instance = ServiceLocator.Current.GetInstance(typeof(DataAccess.DataAccess)); The exact exception: Activation error occured while trying to get instance of type DataAccess, key "" The inner exception is null, the stack trace: at Microsoft.Practices.Prism.MefExtensions.MefServiceLocatorAdapter.DoGetInstance(Type serviceType, String key) in c:\release\WorkingDir\PrismLibraryBuild\PrismLibrary\Desktop\Prism.MefExtensions\MefServiceLocatorAdapter.cs:line 76 at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) Edit The same exception is thrown for: container = (CompositionContainer)ServiceLocator.Current.GetInstance(typeof(CompositionContainer));

    Read the article

  • Using Prism with Ninject

    - by stiank81
    Is anyone out there using the Prism framework with Ninject instead of Unity? I need some functionality Unity isn't supporting yet, and I've decided to switch the IoC container to Ninject. I'm struggling a bit with the replace though.. What I need to use from Prism is the EventAggregator and the RegionManager. I have seen this sample that actually does the replace, but this is written for an older version of Prism, and several of the classes seems to have changed etc. So I ended up all confused after looking doing some effort in trying to rewrite it. So - my question is basically: How can I replace Unity with Ninject? What are the necessary steps? Initially I assumed I could write a simple bootstrapper that creates and configures a Ninject container and uses this to resolve all other objects. I bind IEventAggregator to EventAggregator and IRegionManager to RegionManager, but it fails when creating the Shell and the RegionManager.CreateRegion is called. Problem is that it seems like I need to set a ServiceLocator somewhere as it fails on this line: IServiceLocator locator = ServiceLocator.Current; Any ideas and tips along the way?

    Read the article

  • Delphi Prism getting Unknown Identifier "DllImport" error

    - by Robo
    I'm trying to call Window's SendMessage method in Delphi Prism, I've declared the class as follow: type MyUtils = public static class private [DllImport("user32.dll", CharSet := CharSet.Auto)] method SendMessage(hWnd:IntPtr; Msg:UInt32; wParam:IntPtr; lParam:IntPtr):IntPtr; external; protected public end; When I tried to compile, I get the error Unknown identifier "DllImport" I used this as an example, http://stackoverflow.com/questions/2708520/how-to-call-function-createprocess-in-delphi-prism and the syntax looks the same. Is there a setting I need to enable, or do I have a syntax error?

    Read the article

  • Smart Client Guidance = Prism? Vs 2010

    - by mark smith
    Hi there, I have found this link http://smartclient.codeplex.com/ which has some updates for vs 2010 .... I don't know but i always seem to get confused i.e. lack of documentation etc..... but is this the same as Prism?? If not can anyone tell me where the differences are... It appears to be a link for designing smartclient so i presume its composite Or am i wrong? If i am indeed wrong, where is the link to prism and the vs 2010 templates? Any help would be really appreciated

    Read the article

  • How can I make a Prism webapp look like Firefox to a website? (user agent spoofing)

    - by Alex Aaron Goven
    I thought it would be cool to use Mozilla's Prism to create a webapp for min.us, but drag and drop is disallowed because the site doesn't see the program as Firefox, Chrome or Safari, those of which are apparently the only browsers allowed to do drag and drop for fear that something will be horribly broken. I'm pretty sure Prism runs on the same engine as Firefox, yet I wouldn't doubt it if Prism is running on an older version since it's kind of a forgotten beta. Anyways, like the title says, I want to be able to make Prism webapps appear look like Firefox to websites to unlock awesome features. Also, if it can only be done with Fluid, then I answers regarding that will be fine. I'm not sure what engine it's running though.

    Read the article

  • Delphi Prism 2011 arrive le mois prochain, la plateforme pour développer des applications .NET en De

    Delphi Prism 2011 arriverait le mois prochain La plateforme pour développer des applications .NET en Delphi sera compatible avec Visual Studio 2010 Delphi Prism est une plateforme imaginée par Embarcadero qui permet de développer des applications .NET en Delphi. Il s'agit donc, en résumé, d'un compilateur Delphi (le langage Pascal Objet adapté pour les composants et le développement RAD) qui génère des applications utilisant la plateforme Microsoft .NET. Son environnement de développement était jusqu'ici Visual Studio 2008 Shell. Avec l'arrivée le mois prochain de Delphi Prism 2011, la plateforme pourra à présent être utilisée avec

    Read the article

  • Problems with Prism hosted in a WinForm ElementHost

    - by rabozo
    I am having problems with hosting a WPF prism app in an ElementHost control and am desparate for help. The PRISM app runs fine in silverlight and in a standalone WPF. The main Shell seems to setup fine in the elementHost on a WinForm however other views only load with the “RegisterViewWithRegion” and not the “Add,Activate” procedure. I need “Add,Activate” for scoping. However I beleive the problem is that I am loading my shell twice … not on purpose. I cannot find a way to call the bootsrapper and set the elementHot without calling “Resolve” twice. Here is the code for my WinForm and my bootstrapper. Again everything works when using "RegisterViewWithRegion". Here is the Winform Constructor: public Form1() { InitializeComponent(); if (System.Windows.Application.Current == null) { new MyApp(); } Bootstrapper bootStrapper = new Bootstrapper(); bootStrapper.Run(); var shellElement = bootStrapper.Container.Resolve<ShellContainer>(); //Attach the WPF control to the host elementHost.Child = shellElement; } Here is the bootstrapper: public class Bootstrapper : UnityBootstrapper { protected override DependencyObject CreateShell() { return Container.Resolve<ShellContainer>(); } protected override void InitializeModules() { IModule moduleSurvey = Container.Resolve<SurveyModule>(); moduleSurvey.Initialize(); } }

    Read the article

  • Trace PRISM / CAL events (best practice?)

    - by Christian
    Ok, this question is for people with either a deep knowledge of PRISM or some magic skills I just lack (yet). The Background is simple: Prism allows the declaration of events to which the user can subscribe or publish. In code this looks like this: _eventAggregator.GetEvent<LayoutChangedEvent>().Subscribe(UpdateUi, true); _eventAggregator.GetEvent<LayoutChangedEvent>().Publish("Some argument"); Now this is nice, especially because these events are strongly typed, and the declaration is a piece of cake: public class LayoutChangedEvent : CompositePresentationEvent<string> { } But now comes the hard part: I want to trace events in some way. I had the idea to subscribe using a lambda expression calling a simple log message. Worked perfectly in WPF, but in Silverlight there is some method access error (took me some time to figure out the reason).. If you want to see for yourself, try this in Silverlight: eA.GetEvent<VideoStartedEvent>().Subscribe(obj => TraceEvent(obj, "vSe", log)); If this would be possible, I would be happy, because I could easily trace all events using a single line to subscribe. But it does not... The alternative approach is writing a different functions for each event, and assign this function to the events. Why different functions? Well, I need to know WHICH event was published. If I use the same function for two different events I only get the payload as argument. I have now way to figure out which event caused the tracing message. I tried: using Reflection to get the causing event (not working) using a constructor in the event to enable each event to trace itself (not allowed) Any other ideas? Chris PS: Writing this text took me most likely longer than writing 20 functions for my 20 events, but I refuse to give up :-) I just had the idea to use postsharp, that would most likely work (although I am not sure, perhaps I end up having only information about the base class).. Tricky and so unimportant topic...

    Read the article

  • PRISM - Creating mouseoverbehavior causes a Silverlight library to not be visible in main Silverligh

    - by RHLopez
    Created a simple Silverlight 4 application (SimpleApp) then added a Silverlight 4 library (LibraryA). Added code to the library (LibraryA) to implement MouseOverBehavior by inheriting from CommandBaseBehavior along with the appropriate attached property class/methods. Added reference in SimpleApp to LibraryA and went to MainPage.xaml to add namespace reference but it does not show up with Intellisense. Typing the namespace manually and then adding the attached MouseOver command works as it should as far as intellisense showing my attached property name, i.e. ... commands:MouseOver.Command="{Binding MousedOver}". However when I try to run it I get a XAML parser error saying that the "Command" attached property does not exist in MouseOver. If I move my class definitions from LibraryA to SimpleApp then everything works. I removed everything from LibraryA and just put one class with this in it: public class MouseOverBehavior : CommandBehaviorBase<Control> { public MouseOverBehavior(Control element) : base(element) {} } With this simple class in LibraryA it will not show up in XAML intellisense in SimpleApp. XAML intellisense works with other libraries that I have written that don't use PRISM. Don't know what I am missing hopefully it's something simple. I am using the latest SL4 build for PRISM change set 42969. Visual Studio 2010 RTM Professional in Windows 7 Ultimate 64-bit.

    Read the article

  • Using ASP.NET session state with Silverlight (PRISM)

    - by Jon Andersen
    Hi, The scenario: I have a PRISM application developed in Silverlight (4), and I'm using a ASP.NET server side application to host several web-services (which, in turn, accesses WCF-services, but that's not really important here). The Silverlight application must be able to call the web services cross-domain (meaning that the web services isn't necessarily on the same server hosting the silverlight application). The Silverlight application consists of several modules, each accessing the ASP.NET web-services. I do not have much experience with Silverlight and PRISM, but as far as I can see, this is not a very unusual scenario... The problem: My challange is, that when 2 different modules access the web-services, I get 2 new sessions on the web-server. I would have thought that since both modules live on the same HTML-page (and then also in the same browser session), they would get the same session on the web-server...? I have tried to make the web-service Proxy-client globally available in the container (using Unity), by registering an instance (using Container.RegisterInstance), and then getting this instance whenever a module needs to make a web-service call (using Container.Resolve), but this doesn't seem to help. However, any calls made within the same module always gets the same session on the server. Can anyone see what I'm missing here...? Thanks! Jon

    Read the article

  • WPF Prism's delegatecommand not refreshing

    - by gkar
    I am building wpf edit form, that has two buttons, BeginEdit and Save And the form is bound to ViewModel that inherits from Prism's NotificationObject. There is a property called IsReadOnly And there are two commands that are Prism's DelegateCommands BeginEdit command and save command The code is here private DelegateCommand _beginEdit; public DelegateCommand BeginEdit { get { return _beginEdit ?? (_beginEdit = new DelegateCommand(() => this.IsReadOnly = false , () => IsReadOnly)); } } private bool _isReadOnly; public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; RaisePropertyChanged("IsReadOnly"); } } private DelegateCommand _saveEdit; public DelegateCommand SaveEdit { get { return _saveEdit ?? (_saveEdit = new DelegateCommand(() => this.IsReadOnly = true , () => !IsReadOnly)); } } So, as you see, the command will set IsReadOnly property to true or false, and CanExecute should get its value from the same property as well. It works when I start the form. But after I press BeginEdit, the buttons stays as the same, and the canExecute is not reflecting the new value of IsReadOnly

    Read the article

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