Search Results

Search found 63 results on 3 pages for 'viewmodelbase'.

Page 1/3 | 1 2 3  | Next Page >

  • Dynamic/Generic ViewModelBase?

    - by Shimmy
    I am learning MVVM now and I understand few things (more than but few are here..): Does every model potentially exposed (thru a VM) to the View is having a VM? For example, if I have a Contact and Address entity and each contact has an Addresses (many) property, does it mean I have to create a ContactViewModel and an AddressViewModel etc.? Do I have to redeclare all the properties of the Model again in the ViewModel (i.e. FirstName, LastName blah blah)? why not have a ViewModelBase and the ContactViewMode will be a subclass of ViewModelBase accessing the Entity's properties itself? and if this is a bad idea that the View has access to the entity (please explain why), then why not have the ViewModelBase be a DynamicObject (view the Dictionary example @ the link page), so I don't have to redeclare all the properties and validation over and over in the two tiers (M & VM) - because really, the View is anyway accessing the ViewModel's fields via reflection anyway. I think MVVM was the hardest technology I've ever learned. it doesn't have out-the-box support and there are to many frameworks and methods to achieve it, and in the other hand there is no arranged way to learn it (as MVC for instance), learning MVVM means browsing and surfing around trying to figure out what's better. Bottom line, what I mean by this section is please go and vote to MSFT to add MVVM support in the BCL and generators for VMs and Vs according to the Ms. Thanks

    Read the article

  • Adventures in MVVM – My ViewModel Base

    - by Brian Genisio's House Of Bilz
    More Adventures in MVVM First, I’d like to say: THIS IS NOT A NEW MVVM FRAMEWORK. I tend to believe that MVVM support code should be specific to the system you are building and the developers working on it.  I have yet to find an MVVM framework that does everything I want it to without doing too much.  Don’t get me wrong… there are some good frameworks out there.  I just like to pick and choose things that make sense for me.  I’d also like to add that some of these features only work in WPF.  As of Silveright 4, they don’t support binding to dynamic properties, so some of the capabilities are lost. That being said, I want to share my ViewModel base class with the world.  I have had several conversations with people about the problems I have solved using this ViewModel base.  A while back, I posted an article about some experiments with a “Rails Inspired ViewModel”.  What followed from those ideas was a ViewModel base class that I take with me and use in my projects.  It has a lot of features, all designed to reduce the friction in writing view models. I have put the code out on Codeplex under the project: ViewModelSupport. Finally, this article focuses on the ViewModel and only glosses over the View and the Model.  Without all three, you don’t have MVVM.  But this base class is for the ViewModel, so that is what I am focusing on. Features: Automatic Command Plumbing Property Change Notification Strongly Typed Property Getter/Setters Dynamic Properties Default Property values Derived Properties Automatic Method Execution Command CanExecute Change Notification Design-Time Detection What about Silverlight? Automatic Command Plumbing This feature takes the plumbing out of creating commands.  The common pattern for commands in a ViewModel is to have an Execute method as well as an optional CanExecute method.  To plumb that together, you create an ICommand Property, and set it in the constructor like so: Before public class AutomaticCommandViewModel { public AutomaticCommandViewModel() { MyCommand = new DelegateCommand(Execute_MyCommand, CanExecute_MyCommand); } public void Execute_MyCommand() { // Do something } public bool CanExecute_MyCommand() { // Are we in a state to do something? return true; } public DelegateCommand MyCommand { get; private set; } } With the base class, this plumbing is automatic and the property (MyCommand of type ICommand) is created for you.  The base class uses the convention that methods be prefixed with Execute_ and CanExecute_ in order to be plumbed into commands with the property name after the prefix.  You are left to be expressive with your behavior without the plumbing.  If you are wondering how CanExecuteChanged is raised, see the later section “Command CanExecute Change Notification”. After public class AutomaticCommandViewModel : ViewModelBase { public void Execute_MyCommand() { // Do something } public bool CanExecute_MyCommand() { // Are we in a state to do something? return true; } }   Property Change Notification One thing that always kills me when implementing ViewModels is how to make properties that notify when they change (via the INotifyPropertyChanged interface).  There have been many attempts to make this more automatic.  My base class includes one option.  There are others, but I feel like this works best for me. The common pattern (without my base class) is to create a private backing store for the variable and specify a getter that returns the private field.  The setter will set the private field and fire an event that notifies the change, only if the value has changed. Before public class PropertyHelpersViewModel : INotifyPropertyChanged { private string text; public string Text { get { return text; } set { if(text != value) { text = value; RaisePropertyChanged("Text"); } } } protected void RaisePropertyChanged(string propertyName) { var handlers = PropertyChanged; if(handlers != null) handlers(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } This way of defining properties is error-prone and tedious.  Too much plumbing.  My base class eliminates much of that plumbing with the same functionality: After public class PropertyHelpersViewModel : ViewModelBase { public string Text { get { return Get<string>("Text"); } set { Set("Text", value);} } }   Strongly Typed Property Getters/Setters It turns out that we can do better than that.  We are using a strongly typed language where the use of “Magic Strings” is often frowned upon.  Lets make the names in the getters and setters strongly typed: A refinement public class PropertyHelpersViewModel : ViewModelBase { public string Text { get { return Get(() => Text); } set { Set(() => Text, value); } } }   Dynamic Properties In C# 4.0, we have the ability to program statically OR dynamically.  This base class lets us leverage the powerful dynamic capabilities in our ecosystem. (This is how the automatic commands are implemented, BTW)  By calling Set(“Foo”, 1), you have now created a dynamic property called Foo.  It can be bound against like any static property.  The opportunities are endless.  One great way to exploit this behavior is if you have a customizable view engine with templates that bind to properties defined by the user.  The base class just needs to create the dynamic properties at runtime from information in the model, and the custom template can bind even though the static properties do not exist. All dynamic properties still benefit from the notifiable capabilities that static properties do. For any nay-sayers out there that don’t like using the dynamic features of C#, just remember this: the act of binding the View to a ViewModel is dynamic already.  Why not exploit it?  Get over it :) Just declare the property dynamically public class DynamicPropertyViewModel : ViewModelBase { public DynamicPropertyViewModel() { Set("Foo", "Bar"); } } Then reference it normally <TextBlock Text="{Binding Foo}" />   Default Property Values The Get() method also allows for default properties to be set.  Don’t set them in the constructor.  Set them in the property and keep the related code together: public string Text { get { return Get(() => Text, "This is the default value"); } set { Set(() => Text, value);} }   Derived Properties This is something I blogged about a while back in more detail.  This feature came from the chaining of property notifications when one property affects the results of another, like this: Before public class DependantPropertiesViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); RaisePropertyChanged("Percentage"); RaisePropertyChanged("Output"); } } public int Percentage { get { return (int)(100 * Score); } } public string Output { get { return "You scored " + Percentage + "%."; } } } The problem is: The setter for Score has to be responsible for notifying the world that Percentage and Output have also changed.  This, to me, is backwards.    It certainly violates the “Single Responsibility Principle.” I have been bitten in the rear more than once by problems created from code like this.  What we really want to do is invert the dependency.  Let the Percentage property declare that it changes when the Score Property changes. After public class DependantPropertiesViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); } } [DependsUpon("Score")] public int Percentage { get { return (int)(100 * Score); } } [DependsUpon("Percentage")] public string Output { get { return "You scored " + Percentage + "%."; } } }   Automatic Method Execution This one is extremely similar to the previous, but it deals with method execution as opposed to property.  When you want to execute a method triggered by property changes, let the method declare the dependency instead of the other way around. Before public class DependantMethodsViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); WhenScoreChanges(); } } public void WhenScoreChanges() { // Handle this case } } After public class DependantMethodsViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); } } [DependsUpon("Score")] public void WhenScoreChanges() { // Handle this case } }   Command CanExecute Change Notification Back to Commands.  One of the responsibilities of commands that implement ICommand – it must fire an event declaring that CanExecute() needs to be re-evaluated.  I wanted to wait until we got past a few concepts before explaining this behavior.  You can use the same mechanism here to fire off the change.  In the CanExecute_ method, declare the property that it depends upon.  When that property changes, the command will fire a CanExecuteChanged event, telling the View to re-evaluate the state of the command.  The View will make appropriate adjustments, like disabling the button. DependsUpon works on CanExecute methods as well public class CanExecuteViewModel : ViewModelBase { public void Execute_MakeLower() { Output = Input.ToLower(); } [DependsUpon("Input")] public bool CanExecute_MakeLower() { return !string.IsNullOrWhiteSpace(Input); } public string Input { get { return Get(() => Input); } set { Set(() => Input, value);} } public string Output { get { return Get(() => Output); } set { Set(() => Output, value); } } }   Design-Time Detection If you want to add design-time data to your ViewModel, the base class has a property that lets you ask if you are in the designer.  You can then set some default values that let your designer see what things might look like in runtime. Use the IsInDesignMode property public DependantPropertiesViewModel() { if(IsInDesignMode) { Score = .5; } }   What About Silverlight? Some of the features in this base class only work in WPF.  As of version 4, Silverlight does not support binding to dynamic properties.  This, in my opinion, is a HUGE limitation.  Not only does it keep you from using many of the features in this ViewModel, it also keeps you from binding to ViewModels designed in IronRuby.  Does this mean that the base class will not work in Silverlight?  No.  Many of the features outlined in this article WILL work.  All of the property abstractions are functional, as long as you refer to them statically in the View.  This, of course, means that the automatic command hook-up doesn’t work in Silverlight.  You need to plumb it to a static property in order for the Silverlight View to bind to it.  Can I has a dynamic property in SL5?     Good to go? So, that concludes the feature explanation of my ViewModel base class.  Feel free to take it, fork it, whatever.  It is hosted on CodePlex.  When I find other useful additions, I will add them to the public repository.  I use this base class every day.  It is mature, and well tested.  If, however, you find any problems with it, please let me know!  Also, feel free to suggest patches to me via the CodePlex site.  :)

    Read the article

  • MVVM Light V4 preview 2 (BL0015) #mvvmlight

    - by Laurent Bugnion
    Over the past few weeks, I have worked hard on a few new features for MVVM Light V4. Here is a second early preview (consider this pre-alpha if you wish). The features are unit-tested, but I am now looking for feedback and there might be bugs! Bug correction: Messenger.CleanupList is now thread safe This was an annoying bug that is now corrected: In some circumstances, an exception could be thrown when the Messenger’s recipients list was cleaned up (i.e. the “dead” instances were removed). The method is called now and then and the exception was thrown apparently at random. In fact it was really a multi-threading issue, which is now corrected. Bug correction: AllowPartiallyTrustedCallers prevents EventToCommand to work This is a particularly annoying regression bug that was introduced in BL0014. In order to allow MVVM Light to work in XBAPs too, I added the AllowPartiallyTrustedCallers attribute to the assemblies. However, we just found out that this causes issues when using EventToCommand. In order to allow EventToCommand to continue working, I reverted to the previous state by removing the AllowPartiallyTrustedCallers attribute for now. I will work with my friends at Microsoft to try and find a solution. Stay tuned. Bug correction: XML documentation file is now generated in Release configuration The XML documentation file was not generated for the Release configuration. This was a simple flag in the project file that I had forgotten to set. This is corrected now. Applying EventToCommand to non-FrameworkElements This feature has been requested in order to be able to execute a command when a Storyboard is completed. I implemented this, but unfortunately found out that EventToCommand can only be added to Storyboards in Silverlight 3 and Silverlight 4, but not in WPF or in Windows Phone 7. This obviously limits the usefulness of this change, but I decided to publish it anyway, because it is pretty damn useful in Silverlight… Why not in WPF? In WPF, Storyboards added to a resource dictionary are frozen. This is a feature of WPF which allows to optimize certain objects for performance: By freezing them, it is a contract where we say “this object will not be modified anymore, so do your perf optimization on them without worrying too much”. Unfortunately, adding a Trigger (such as EventTrigger) to an object in resources does not work if this object is frozen… and unfortunately, there is no way to tell WPF not to freeze the Storyboard in the resources… so there is no way around that (at least none I can see. In Silverlight, objects are not frozen, so an EventTrigger can be added without problems. Why not in WP7? In Windows Phone 7, there is a totally different issue: Adding a Trigger can only be done to a FrameworkElement, which Storyboard is not. Here I think that we might see a change in a future version of the framework, so maybe this small trick will work in the future. Workaround? Since you cannot use the EventToCommand on a Storyboard in WPF and in WP7, the workaround is pretty obvious: Handle the Completed event in the code behind, and call the Command from there on the ViewModel. This object can be obtained by casting the DataContext to the ViewModel type. This means that the View needs to know about the ViewModel, but I never had issues with that anyway. New class: NotifyPropertyChanged Sometimes when you implement a model object (for example Customer), you would like to have it implement INotifyPropertyChanged, but without having all the frills of a ViewModelBase. A new class named NotifyPropertyChanged allows you to do that. This class is a simple implementation of INotifyPropertyChaned (with all the overloads of RaisePropertyChanged that were implemented in BL0014). In fact, ViewModelBase inherits NotifyPropertyChanged. ViewModelBase does not implement IDisposable anymore The IDisposable interface and the Dispose method had been marked obsolete in the ViewModelBase class already in V3. Now they have been removed. Note: By this, I do not mean that IDisposable is a bad interface, or that it shouldn’t be used on viewmodels. In the contrary, I know that this interface is very useful in certain circumstances. However, I think that having it by default on every instance of ViewModelBase was sending a wrong message. This interface has a strong meaning in .NET: After Dispose has been executed, the instance should not be used anymore, and should be ready for garbage collection. What I really wanted to have on ViewModelBase was rather a simple cleanup method, something that can be executed now and then during runtime. This is fulfilled by the ICleanup interface and its Cleanup method. If your ViewModels need IDisposable, you can still use it! You will just have to implement the interface on the class itself, because it is not available on ViewModelBase anymore. What’s next? I have a couple exciting new features implemented already but that need more testing before they go live… Just stay tuned and by MIX11 (12-14 April 2011), we should see at least a major addition to MVVM Light Toolkit, as well as another smaller feature which is pretty cool nonetheless More about this later! Happy Coding Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • .Net lambda expression-- where did this parameter come from?

    - by larryq
    I'm a lambda newbie, so if I'm missing vital information in my description please tell me. I'll keep the example as simple as possible. I'm going over someone else's code and they have one class inheriting from another. Here's the derived class first, along with the lambda expression I'm having trouble understanding: class SampleViewModel : ViewModelBase { private ICustomerStorage storage = ModelFactory<ICustomerStorage>.Create(); public ICustomer CurrentCustomer { get { return (ICustomer)GetValue(CurrentCustomerProperty); } set { SetValue(CurrentCustomerProperty, value); } } private int quantitySaved; public int QuantitySaved { get { return quantitySaved; } set { if (quantitySaved != value) { quantitySaved = value; NotifyPropertyChanged(p => QuantitySaved); //where does 'p' come from? } } } public static readonly DependencyProperty CurrentCustomerProperty; static SampleViewModel() { CurrentCustomerProperty = DependencyProperty.Register("CurrentCustomer", typeof(ICustomer), typeof(SampleViewModel), new UIPropertyMetadata(ModelFactory<ICustomer>.Create())); } //more method definitions follow.. Note the call to NotifyPropertyChanged(p => QuantitySaved) bit above. I don't understand where the "p" is coming from. Here's the base class: public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IXtremeMvvmViewModel { public event PropertyChangedEventHandler PropertyChanged; protected virtual void NotifyPropertyChanged<T>(Expression<Func<ViewModelBase, T>> property) { MvvmHelper.NotifyPropertyChanged(property, PropertyChanged); } } There's a lot in there that's not germane to the question I'm sure, but I wanted to err on the side of inclusiveness. The problem is, I don't understand where the 'p' parameter is coming from, and how the compiler knows to (evidently?) fill in a type value of ViewModelBase from thin air? For fun I changed the code from 'p' to 'this', since SampleViewModel inherits from ViewModelBase, but I was met with a series of compiler errors, the first one of which statedInvalid expression term '=>' This confused me a bit since I thought that would work. Can anyone explain what's happening here?

    Read the article

  • What&rsquo;s new in MVVM Light V3

    - by Laurent Bugnion
    V3 of the MVVM Light Toolkit was released during MIX10, after quite a long alpha stage. This post lists the new features in MVVM Light V3. Compatibility MVVM Light Toolkit V3 can be installed for the following tools and framework versions: Visual Studio 2008 SP1, Expression Blend 3 Windows Presentation Foundation 3.5 SP1 Silverlight 3 Visual Studio 2010 RC, Expression Blend 4 beta Windows Presentation Foundation 3.5 SP1 Windows Presentation Foundation 4 RC Silverlight 3 Silverlight 4 RC For more information about installing the MVVM Light Toolkit V3, please visit this page. For cleaning up existing installation, see this page. New in V3 RTM The following features have been added after V3 alpha3: Project template for the Windows Phone 7 series (Silverlight) This new template allows you to create a new MVVM Light application in Visual Studio 2010 RC and to run it in the Windows Phone 7 series emulator. This template uses the Silverlight 3 version of the MVVM Light Toolkit V3. At this time, only the essentials features of the GalaSoft.MvvmLight.dll assembly are supported on the phone. New in V3 alpha3 The following features have been added after V3 alpha2: New logo An awesome logo has been designed for MVVM Light by Philippe Schutz. DispatcherHelper class (in GalaSoft.MvvmLight.Extras.dll) This class is useful when you work on multi-threaded WPF or Silverlight applications. Initializing: The DispatcherHelper class must be initialized in the UI thread. For example, you can initialize the class in a Silverlight application’s Application_Startup event handler, or in the WPF application’s static App constructor (in App.xaml). // Initializing in Silverlight (in App.xaml) private void Application_Startup( object sender, StartupEventArgs e) { RootVisual = new MainPage(); DispatcherHelper.Initialize(); } // Initializing in WPF (in App.xaml) static App() { DispatcherHelper.Initialize(); } Verifying if a property exists The ViewModelBase.RaisePropertyChanged method now checks if a given property name exists on the ViewModel class, and throws an exception if that property cannot be found. This is useful to detect typos in a property name, for example during a refactoring. Note that the check is only done in DEBUG mode. Replacing IDisposable with ICleanup The IDisposable implementation in the ViewModelBase class has been marked obsolete. Instead, the ICleanup interface (and its Cleanup method) has been added. Implementing IDisposable in a ViewModel is still possible, but must be done explicitly. IDisposable in ViewModelBase was a bad practice, because it supposes that the ViewModel is garbage collected after Dispose is called. instead, the Cleanup method does not have such expectation. The ViewModelLocator class (created when an MVVM Light project template is used in Visual Studio or Expression Blend) exposes a static Cleanup method, which should in turn call each ViewModel’s Cleanup method. The ViewModel is free to override the Cleanup method if local cleanup must be performed. Passing EventArgs to command with EventToCommand The EventToCommand class is used to bind any event to an ICommand (typically on the ViewModel). In this case, it can be useful to pass the event’s EventArgs parameter to the command in the ViewModel. For example, for the MouseEnter event, you can pass the MouseEventArgs to a RelayCommand<MouseEventArgs> as shown in the next listings. Note: Bringing UI specific classes (such as EventArgs) into the ViewModel reduces the testability of the ViewModel, and thus should be used with care. Setting EventToCommand and PassEventArgsToCommand: <Grid x:Name="LayoutRoot"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseEnter"> <cmd:EventToCommand Command="{Binding MyCommand}" PassEventArgsToCommand="True" /> </i:EventTrigger> </i:Interaction.Triggers> </Grid> Getting the EventArgs in the command public RelayCommand<MouseEventArgs> MyCommand { get; private set; } public MainViewModel() { MyCommand = new RelayCommand<MouseEventArgs>(e => { // e is of type MouseEventArgs }); } Changes to templates Various changes have been made to project templates and item templates to make them more compatible with Silverlight 4 and to improve their visibility in Visual Studio and Expression Blend. Bug corrections When a message is sent through the Messenger class using the method Messenger.Default.Send<T>(T message, object token), and the token is a simple value (for example int), the message was not sent correctly. This bug is now corrected. New in V3 The following features have been added after V2. Sending messages with callback Certain classes have been added to the GalaSoft.MvvmLight.Messaging namespace, allowing sending a message and getting a callback from the recipient. These classes are: NotificationMessageWithCallback: Base class for messages with callback. NotificationMessageAction: A class with string notification, and a parameterless callback. NotificationMessageAction<T>: A class with string notification, and a callback with a parameter of type T. To send a message with callback, use the following code: var message = new NotificationMessageAction<bool>( "Hello world", callbackMessage => { // This is the callback code if (callbackMessage) { // ... } }); Messenger.Default.Send(message); To register and receive a message with callback, use the following code: Messenger.Default.Register<NotificationMessageAction<bool>>( this, message => { // Do something // Execute the callback message.Execute(true); }); Messenger.Default can be overriden The Messenger.Default property can also be replaced, for example for unit testing purposes, by using the Messenger.OverrideDefault method. All the public methods of the Messenger class have been made virtual, and can be overridden in the test messenger class. Sending messages to interfaces In V2, it was possible to deliver messages targeted to instances of a given class. in V3 it is still possible, but in addition you can deliver a message to instances that implement a certain interface. The message will not be delivered to other recipients. Use the overload Messenger.Default.Send<TMessage, TTarget>(TMessage message) where TTarget is, in fact, an interface (for example IDisposable). Of course the recipient must register to receive the type of message TMessage. Sending messages with a token Messages can now be sent through the Messenger with a token. To send a message with token, use the method overload Send<TMessage>(TMessage message, object token). To receive a message with token, use the methods Register<TMessage>(object recipient, object token, Action<TMessage> action) or Register<TMessage>(object recipient, object token, bool receiveDerivedMessagesToo, Action<TMessage> action) The token can be a simple value (int, string, etc…) or an instance of a class. The message is not delivered to recipients who registered with a different token, or with no token at all. Renaming CommandMessage to NotificationMessage To avoid confusion with ICommand and RelayCommand, the CommandMessage class has been renamed to NotificationMessage. This message class can be used to deliver a notification (of type string) to a recipient. ViewModelBase constructor with IMessenger The ViewModelBase class now accepts an IMessenger parameter. If this constructor is used instead of the default empty constructor, the IMessenger passed as parameter will be used to broadcast a PropertyChangedMessage when the method RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool broadcast) is used. In the default ViewModelBase constructor is used, the Messenger.Default instance will be used instead. EventToCommand behavior The EventToCommand behavior has been added in V3. It can be used to bind any event of any FrameworkElement to any ICommand (for example a RelayCommand located in the ViewModel). More information about the EventToCommand behavior can be found here and here. Updated the project templates to remove the sample application The project template has been updated to remove the sample application that was created every time that a new MVVM Light application was created in Visual Studio or Blend. This makes the creation of a new application easier, because you don’t need to remove code before you can start writing code. Bug corrections Some bugs that were in Version 2 have been corrected: In some occasions, an exception could be thrown when a recipient was registered for a message at the same time as a message was received. New names for DLLs If you upgrade an existing installation, you will need to change the reference to the DLLs in C:\Program Files\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\Binaries. The assemblies have been moved, and the versions for Silverlight 4 and for WPF4 have been renamed, to avoid some confusion. It is now easier to make sure that you are using the correct DLL. WPF3.5SP1, Silverlight 3 When using the DLLs, make sure that you use the correct versions. WPF4, Silverlight 4 When using the DLLs, make sure that you use the correct versions.   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • Including partial views when applying the Mode-View-ViewModel design pattern

    - by Filip Ekberg
    Consider that I have an application that just handles Messages and Users I want my Window to have a common Menu and an area where the current View is displayed. I can only work with either Messages or Users so I cannot work simultaniously with both Views. Therefore I have the following Controls MessageView.xaml UserView.xaml Just to make it a bit easier, both the Message Model and the User Model looks like this: Name Description Now, I have the following three ViewModels: MainWindowViewModel UsersViewModel MessagesViewModel The UsersViewModel and the MessagesViewModel both just fetch an ObserverableCollection<T> of its regarding Model which is bound in the corresponding View like this: <DataGrid ItemSource="{Binding ModelCollection}" /> The MainWindowViewModel hooks up two different Commands that have implemented ICommand that looks something like the following: public class ShowMessagesCommand : ICommand { private ViewModelBase ViewModel { get; set; } public ShowMessagesCommand (ViewModelBase viewModel) { ViewModel = viewModel; } public void Execute(object parameter) { var viewModel = new ProductsViewModel(); ViewModel.PartialViewModel = new MessageView { DataContext = viewModel }; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; } And there is another one a like it that will show Users. Now this introduced ViewModelBase which only holds the following: public UIElement PartialViewModel { get { return (UIElement)GetValue(PartialViewModelProperty); } set { SetValue(PartialViewModelProperty, value); } } public static readonly DependencyProperty PartialViewModelProperty = DependencyProperty.Register("PartialViewModel", typeof(UIElement), typeof(ViewModelBase), new UIPropertyMetadata(null)); This dependency property is used in the MainWindow.xaml to display the User Control dynamicly like this: <UserControl Content="{Binding PartialViewModel}" /> There are also two buttons on this Window that fires the Commands: ShowMessagesCommand ShowUsersCommand And when these are fired, the UserControl changes because PartialViewModel is a dependency property. I want to know if this is bad practice? Should I not inject the User Control like this? Is there another "better" alternative that corresponds better with the design pattern? Or is this a nice way of including partial views?

    Read the article

  • CollectionViewSource.GetDefaultView is not in Silverlight 3! What's the work-around?

    - by rasx
    The CollectionViewSource.GetDefaultView() method is not in Silverlight 3. In WPF I have this extension method: public static void SetActiveViewModel<ViewModelType>(this ViewModelBase viewModel, ViewModelType collectionItem, ObservableCollection<ViewModelType> collection) where ViewModelType : ViewModelBase { Debug.Assert(collection.Contains(collectionItem)); ICollectionView collectionView = CollectionViewSource.GetDefaultView(collection); if(collectionView != null) collectionView.MoveCurrentTo(collectionItem); } How can this be written in Silverlight 3?

    Read the article

  • Silverlight with MVVM Inheritance: ModelView and View matching the Model

    - by moonground.de
    Hello Stackoverflowers! :) Today I have a special question on Silverlight (4 RC) MVVM and inheritance concepts and looking for a best practice solution... I think that i understand the basic idea and concepts behind MVVM. My Model doesn't know anything about the ViewModel as the ViewModel itself doesn't know about the View. The ViewModel knows the Model and the Views know the ViewModels. Imagine the following basic (example) scenario (I'm trying to keep anything short and simple): My Model contains a ProductBase class with a few basic properties, a SimpleProduct : ProductBase adding a few more Properties and ExtendedProduct : ProductBase adding another properties. According to this Model I have several ViewModels, most essential SimpleProductViewModel : ViewModelBase and ExtendedProductViewModel : ViewModelBase. Last but not least, according Views SimpleProductView and ExtendedProductView. In future, I might add many product types (and matching Views + VMs). 1. How do i know which ViewModel to create when receiving a Model collection? After calling my data provider method, it will finally end up having a List<ProductBase>. It containts, for example, one SimpleProduct and two ExtendedProducts. How can I transform the results to an ObservableCollection<ViewModelBase> having the proper ViewModel types (one SimpleProductViewModel and two ExtendedProductViewModels) in it? I might check for Model type and construct the ViewModel accordingly, i.e. foreach(ProductBase currentProductBase in resultList) if (currentProductBase is SimpleProduct) viewModels.Add( new SimpleProductViewModel((SimpleProduct)currentProductBase)); else if (currentProductBase is ExtendedProduct) viewModels.Add( new ExtendedProductViewModels((ExtendedProduct)currentProductBase)); ... } ...but I consider this very bad practice as this code doesn't follow the object oriented design. The other way round, providing abstract Factory methods would reduce the code to: foreach(ProductBase currentProductBase in resultList) viewModels.Add(currentProductBase.CreateViewModel()) and would be perfectly extensible but since the Model doesn't know the ViewModels, that's not possible. I might bring interfaces into game here, but I haven't seen such approach proven yet. 2. How do i know which View to display when selecting a ViewModel? This is pretty the same problem, but on a higher level. Ended up finally having the desired ObservableCollection<ViewModelBase> collection would require the main view to choose a matching View for the ViewModel. In WPF, there is a DataTemplate concept which can supply a View upon a defined DataType. Unfortunately, this doesn't work in Silverlight and the only replacement I've found was the ResourceSelector of the SLExtensions toolkit which is buggy and not satisfying. Beside that, all problems from Question 1 apply as well. Do you have some hints or even a solution for the problems I describe, which you hopefully can understand from my explanation? Thank you in advance! Thomas

    Read the article

  • WPF MVVM UserControl Binding "Container", dispose to avoid memory leak.

    - by user178657
    For simplicity. I have a window, with a bindable usercontrol <UserControl Content="{Binding Path = BindingControl, UpdateSourceTrigger=PropertyChanged}"> I have two user controls, ControlA, and ControlB, Both UserControls have their own Datacontext ViewModel, ControlAViewModel and ControlBViewModel. Both ControlAViewModel and ControlBViewModel inh. from a "ViewModelBase" public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IDisposable........ Main window was added to IoC... To set the property of the Bindable UC, i do ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlA; ControlA, in its Datacontext, creates a DispatcherTimer, to do "somestuff".. Later on., I need to navigate elsewhere, so the other usercontrol is loaded into the container ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlB If i put a break point in the "someStuff" that was in ControlA's datacontext. The DispatcherTimer is still running... i.e. loading a new usercontrol into the bindable Usercontrol on mainwindow does not dispose/close/GC the DispatcherTimer that was created in the DataContext View Model... Ive looked around, and as stated by others, dispose doesnt get called because its not supposed to... :) Not all my usercontrols have DispatcherTimer, just a few that need to do some sort of "read and refresh" updates./. Should i track these DispatcherTimer objects in the ViewModelBase that all Usercontrols inh. and manually stop/dispose them everytime a new usercontrol is loaded? Is there a better way?

    Read the article

  • Adventures in MVVM &ndash; My ViewModel Base &ndash; Silverlight Support!

    - by Brian Genisio's House Of Bilz
    More Adventures in MVVM In my last post, I outlined the powerful features that are available in the ViewModelSupport.  It takes advantage of the dynamic features of C# 4.0 (as well as some 3.0 goodies) to help eliminate the plumbing that often comes with writing ViewModels.  If you are interested in learning about the capabilities, please take a look at that post and look at the code on CodePlex.  When I wrote about the ViewModel base class, I complained that the features did not work in Silverlight because as of 4.0, it does not support binding to dynamic properties.  Although I still think this is a bummer, I am happy to say that I have come up with a workaround.  In the Silverlight version of my base class, I include a PropertyCollectionConverter that lets you bind to dynamic properties in the ViewModelBase, especially the convention-based commands that the base class supports. To take advantage of any properties that are not statically defined, you can bind to the Properties property of the ViewModel and pass in a converter parameter for the name of the property you want to bind. For example, a ViewModel that looks like this: public class ExampleViewModel : ViewModelBase { public void Execute_MyCommand() { Set("Text", "Foo"); } } Can bind to the dynamic property and the convention-based command with the following XAML. <TextBlock Text="{Binding Properties, Converter={StaticResource PropertiesConverter}, ConverterParameter=Text}" Margin="5" /> <Button Content="Execute MyCommand" Command="{Binding Properties, Converter={StaticResource PropertiesConverter}, ConverterParameter=MyCommand}" Margin="5" /> Of course, it is not as pretty as binding to Text and MyCommand like you can in WPF.  But, it is better than having a failed feature.  This allows you to share your ViewModels between WPF and Silverlight very easily.  <BeatDeadHorse>Hopefully, in Silverlight 5.0, we will see binding to dynamic properties more directly????</BeatDeadHorse>

    Read the article

  • Yippy &ndash; the F# MVVM Pattern

    - by MarkPearl
    I did a recent post on implementing WPF with F#. Today I would like to expand on this posting to give a simple implementation of the MVVM pattern in F#. A good read about this topic can also be found on Dean Chalk’s blog although my example of the pattern is possibly simpler. With the MVVM pattern one typically has 3 segments, the view, viewmodel and model. With the beauty of WPF binding one is able to link the state based viewmodel to the view. In my implementation I have kept the same principles. I have a view (MainView.xaml), and and a ViewModel (MainViewModel.fs).     What I would really like to illustrate in this posting is the binding between the View and the ViewModel so I am going to jump to that… In Program.fs I have the following code… module Program open System open System.Windows open System.Windows.Controls open System.Windows.Markup open myViewModels // Create the View and bind it to the View Model let myView = Application.LoadComponent(new System.Uri("/FSharpWPF;component/MainView.xaml", System.UriKind.Relative)) :?> Window myView.DataContext <- new MainViewModel() :> obj // Application Entry point [<STAThread>] [<EntryPoint>] let main(_) = (new Application()).Run(myView) You can see that I have simply created the view (myView) and then created an instance of my viewmodel (MainViewModel) and then bound it to the data context with the code… myView.DataContext <- new MainViewModel() :> obj If I have a look at my viewmodel (MainViewModel) it looks like this… module myViewModels open System open System.Windows open System.Windows.Input open System.ComponentModel open ViewModelBase type MainViewModel() = // private variables let mutable _title = "Bound Data to Textbox" // public properties member x.Title with get() = _title and set(v) = _title <- v // public commands member x.MyCommand = new FuncCommand ( (fun d -> true), (fun e -> x.ShowMessage) ) // public methods member public x.ShowMessage = let msg = MessageBox.Show(x.Title) () I have exposed a few things, namely a property called Title that is mutable, a command and a method called ShowMessage that simply pops up a message box when called. If I then look at my view which I have created in xaml (MainView.xaml) it looks as follows… <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="F# WPF MVVM" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <TextBox Text="{Binding Path=Title, Mode=TwoWay}" Grid.Row="0"/> <Button Command="{Binding MyCommand}" Grid.Row="1"> <TextBlock Text="Click Me"/> </Button> </Grid> </Window>   It is also very simple. It has a button that’s command is bound to the MyCommand and a textbox that has its text bound to the Title property. One other module that I have created is my ViewModelBase. Right now it is used to store my commanding function but I would look to expand on it at a later stage to implement other commonly used functions… module ViewModelBase open System open System.Windows open System.Windows.Input open System.ComponentModel type FuncCommand (canExec:(obj -> bool),doExec:(obj -> unit)) = let cecEvent = new DelegateEvent<EventHandler>() interface ICommand with [<CLIEvent>] member x.CanExecuteChanged = cecEvent.Publish member x.CanExecute arg = canExec(arg) member x.Execute arg = doExec(arg) Put this all together and you have a basic project that implements the MVVM pattern in F#. For me this is quite exciting as it turned out to be a lot simpler to do than I originally thought possible. Also because I have my view in XAML I can use the XAML designer to design forms in F# which I believe is a much cleaner way to go rather than implementing it all in code. Finally if I look at my viewmodel code, it is actually quite clean and compact…

    Read the article

  • Master Details and collectionViewSource in separate views cannot make it work.

    - by devnet247
    Hi all, I really cannot seem to make/understand how it works with separate views It all works fine if a bundle all together in a single window. I have a list of Countries-Cities-etc... When you select a country it should load it's cities. Works So I bind 3 listboxes successfully using collection sources and no codebehind more or less (just code to set the datacontext and selectionChanged). you can download the project here http://cid-9db5ae91a2948485.skydrive.live.com/self.aspx/PublicFolder/2MasterDetails.zip <Window.Resources> <CollectionViewSource Source="{Binding}" x:Key="cvsCountryList"/> <CollectionViewSource Source="{Binding Source={StaticResource cvsCountryList},Path=Cities}" x:Key="cvsCityList"/> <CollectionViewSource Source="{Binding Source={StaticResource cvsCityList},Path=Hotels}" x:Key="cvsHotelList"/> </Window.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" Text="Countries"/> <TextBlock Grid.Column="1" Grid.Row="0" Text="Cities"/> <TextBlock Grid.Column="2" Grid.Row="0" Text="Hotels"/> <ListBox Grid.Column="0" Grid.Row="1" Name="lstCountries" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource cvsCountryList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/> <ListBox Grid.Column="1" Grid.Row="1" Name="lstCities" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource cvsCityList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/> <ListBox Grid.Column="2" Grid.Row="1" Name="lstHotels" ItemsSource="{Binding Source={StaticResource cvsHotelList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/> </Grid> Does not work I am trying to implement the same using a view for each eg(LeftSideMasterControl -RightSideDetailsControls) However I cannot seem to make them bind. Can you help? I would be very grateful so that I can understand how you communicate between userControls You can download the project here. http://cid-9db5ae91a2948485.skydrive.live.com/self.aspx/PublicFolder/2MasterDetails.zip I have as follows LeftSideMasterControl.xaml <Grid> <ListBox Name="lstCountries" SelectionChanged="OnSelectionChanged" DisplayMemberPath="Name" ItemsSource="{Binding Countries}"/> </Grid> RightViewDetailsControl.xaml MainView.xaml <CollectionViewSource Source="{Binding}" x:Key="cvsCountryList"/> <CollectionViewSource Source="{Binding Source={StaticResource cvsCountryList},Path=Cities}" x:Key="cvsCityList"/> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="3*"/> </Grid.ColumnDefinitions> <Views:LeftViewMasterControl x:Name="leftSide" Margin="5" Content="{Binding Source=}"/> <GridSplitter Grid.Column="0" Grid.Row="0" Background="LightGray"/> <Views:RightViewDetailsControl Grid.Column="1" x:Name="RightSide" Margin="5"/> </Grid> ViewModels public class CountryListVM : ViewModelBase { public CountryListVM() { Countries = new ObservableCollection<CountryVM>(); } public ObservableCollection<CountryVM> Countries { get; set; } private RelayCommand _loadCountriesCommand; public ICommand LoadCountriesCommand { get { return _loadCountriesCommand ?? (_loadCountriesCommand = new RelayCommand(x => LoadCountries(), x => CanLoadCountries)); } } private static bool CanLoadCountries { get { return true; } } private void LoadCountries() { var countryList = Repository.GetCountries(); foreach (var country in countryList) { Countries.Add(new CountryVM { Name = country.Name }); } } } public class CountryVM : ViewModelBase { private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } } public class CityListVM : ViewModelBase { private CountryVM _selectedCountry; public CityListVM(CountryVM country) { SelectedCountry = country; Cities = new ObservableCollection<CityVM>(); } public ObservableCollection<CityVM> Cities { get; set; } public CountryVM SelectedCountry { get { return _selectedCountry; } set { _selectedCountry = value; OnPropertyChanged("SelectedCountry"); } } private RelayCommand _loadCitiesCommand; public ICommand LoadCitiesCommand { get { return _loadCitiesCommand ?? (_loadCitiesCommand = new RelayCommand(x => LoadCities(), x => CanLoadCities)); } } private static bool CanLoadCities { get { return true; } } private void LoadCities() { var cities = Repository.GetCities(SelectedCountry.Name); foreach (var city in cities) { Cities.Add(new CityVM() { Name = city.Name }); } } } public class CityVM : ViewModelBase { private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } } Models ========= public class Country { public Country() { Cities = new ObservableCollection<City>(); } public string Name { get; set; } public ObservableCollection<City> Cities { get; set; } } public class City { public City() { Hotels = new ObservableCollection<Hotel>(); } public string Name { get; set; } public ObservableCollection<Hotel> Hotels { get; set; } } public class Hotel { public string Name { get; set; } }

    Read the article

  • MVVM - implementing 'IsDirty' functionality to a ModelView in order to save data

    - by Brendan
    Hi, Being new to WPF & MVVM I struggling with some basic functionality. Let me first explain what I am after, and then attach some example code... I have a screen showing a list of users, and I display the details of the selected user on the right-hand side with editable textboxes. I then have a Save button which is DataBound, but I would only like this button to display when data has actually changed. ie - I need to check for "dirty data". I have a fully MVVM example in which I have a Model called User: namespace Test.Model { class User { public string UserName { get; set; } public string Surname { get; set; } public string Firstname { get; set; } } } Then, the ViewModel looks like this: using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Windows.Input; using Test.Model; namespace Test.ViewModel { class UserViewModel : ViewModelBase { //Private variables private ObservableCollection<User> _users; RelayCommand _userSave; //Properties public ObservableCollection<User> User { get { if (_users == null) { _users = new ObservableCollection<User>(); //I assume I need this Handler, but I am stuggling to implement it successfully //_users.CollectionChanged += HandleChange; //Populate with users _users.Add(new User {UserName = "Bob", Firstname="Bob", Surname="Smith"}); _users.Add(new User {UserName = "Smob", Firstname="John", Surname="Davy"}); } return _users; } } //Not sure what to do with this?!?! //private void HandleChange(object sender, NotifyCollectionChangedEventArgs e) //{ // if (e.Action == NotifyCollectionChangedAction.Remove) // { // foreach (TestViewModel item in e.NewItems) // { // //Removed items // } // } // else if (e.Action == NotifyCollectionChangedAction.Add) // { // foreach (TestViewModel item in e.NewItems) // { // //Added items // } // } //} //Commands public ICommand UserSave { get { if (_userSave == null) { _userSave = new RelayCommand(param => this.UserSaveExecute(), param => this.UserSaveCanExecute); } return _userSave; } } void UserSaveExecute() { //Here I will call my DataAccess to actually save the data } bool UserSaveCanExecute { get { //This is where I would like to know whether the currently selected item has been edited and is thus "dirty" return false; } } //constructor public UserViewModel() { } } } The "RelayCommand" is just a simple wrapper class, as is the "ViewModelBase". (I'll attach the latter though just for clarity) using System; using System.ComponentModel; namespace Test.ViewModel { public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable { protected ViewModelBase() { } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } public void Dispose() { this.OnDispose(); } protected virtual void OnDispose() { } } } Finally - the XAML <Window x:Class="Test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:Test.ViewModel" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <vm:UserViewModel/> </Window.DataContext> <Grid> <ListBox Height="238" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="197" ItemsSource="{Binding Path=User}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=Firstname}"/> <TextBlock Text="{Binding Path=Surname}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Label Content="Username" Height="28" HorizontalAlignment="Left" Margin="232,16,0,0" Name="label1" VerticalAlignment="Top" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="323,21,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=User/UserName}" /> <Label Content="Surname" Height="28" HorizontalAlignment="Left" Margin="232,50,0,0" Name="label2" VerticalAlignment="Top" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="323,52,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding Path=User/Surname}" /> <Label Content="Firstname" Height="28" HorizontalAlignment="Left" Margin="232,84,0,0" Name="label3" VerticalAlignment="Top" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="323,86,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" Text="{Binding Path=User/Firstname}" /> <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="368,159,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=UserSave}" /> </Grid> </Window> So basically, when I edit a surname, the Save button should be enabled; and if I undo my edit - well then it should be Disabled again as nothing has changed. I have seen this in many examples, but have not yet found out how to do it. Any help would be much appreciated! Brendan

    Read the article

  • MVVM Binding To Property == Null

    - by LnDCobra
    I want to show some elements when a property is not null. What is the best way of achieving this? The following is my ViewModel: class ViewModel : ViewModelBase { public Trade Trade { get { return _trade; } set { SetField(ref _trade, value, () => Trade); } } private Trade _trade; } ViewModelBase inherits INotifyPropertyChanged and contains SetField() The Following is the Trade class: public class Trade : INotifyPropertyChaged { public virtual Company Company { get { return _company; } set { SetField(ref _company, value, () => Company); } } private Company _company; ...... } This is part of my View.xaml <GroupBox Visibility="{Binding Path=Trade.Company, Converter={StaticResource boolToVisConverter}}" /> I would like this groupbox to show only if Trade.Company is not null (so when a user selects a company). Would I need to create a custom converter to check for null and return the correct visibility or is there one in .NET?

    Read the article

  • WCF RIA Services DomainContext Abstraction Strategies–Say That 10 Times!

    - by dwahlin
    The DomainContext available with WCF RIA Services provides a lot of functionality that can help track object state and handle making calls from a Silverlight client to a DomainService. One of the questions I get quite often in our Silverlight training classes (and see often in various forums and other areas) is how the DomainContext can be abstracted out of ViewModel classes when using the MVVM pattern in Silverlight applications. It’s not something that’s super obvious at first especially if you don’t work with delegates a lot, but it can definitely be done. There are various techniques and strategies that can be used but I thought I’d share some of the core techniques I find useful. To start, let’s assume you have the following ViewModel class (this is from my Silverlight Firestarter talk available to watch online here if you’re interested in getting started with WCF RIA Services): public class AdminViewModel : ViewModelBase { BookClubContext _Context = new BookClubContext(); public AdminViewModel() { if (!DesignerProperties.IsInDesignTool) { LoadBooks(); } } private void LoadBooks() { _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, null); } private void LoadBooksCallback(LoadOperation<Book> books) { Books = new ObservableCollection<Book>(books.Entities); } } Notice that BookClubContext is being used directly in the ViewModel class. There’s nothing wrong with that of course, but if other ViewModel objects need to load books then code would be duplicated across classes. Plus, the ViewModel has direct knowledge of how to load data and I like to make it more loosely-coupled. To do this I create what I call a “Service Agent” class. This class is responsible for getting data from the DomainService and returning it to a ViewModel. It only knows how to get and return data but doesn’t know how data should be stored and isn’t used with data binding operations. An example of a simple ServiceAgent class is shown next. Notice that I’m using the Action<T> delegate to handle callbacks from the ServiceAgent to the ViewModel object. Because LoadBooks accepts an Action<ObservableCollection<Book>>, the callback method in the ViewModel must accept ObservableCollection<Book> as a parameter. The callback is initiated by calling the Invoke method exposed by Action<T>: public class ServiceAgent { BookClubContext _Context = new BookClubContext(); public void LoadBooks(Action<ObservableCollection<Book>> callback) { _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, callback); } public void LoadBooksCallback(LoadOperation<Book> lo) { //Check for errors of course...keeping this brief var books = new ObservableCollection<Book>(lo.Entities); var action = (Action<ObservableCollection<Book>>)lo.UserState; action.Invoke(books); } } This can be simplified by taking advantage of lambda expressions. Notice that in the following code I don’t have a separate callback method and don’t have to worry about passing any user state or casting any user state (the user state is the 3rd parameter in the _Context.Load method call shown above). public class ServiceAgent { BookClubContext _Context = new BookClubContext(); public void LoadBooks(Action<ObservableCollection<Book>> callback) { _Context.Load(_Context.GetBooksQuery(), (lo) => { var books = new ObservableCollection<Book>(lo.Entities); callback.Invoke(books); }, null); } } A ViewModel class can then call into the ServiceAgent to retrieve books yet never know anything about the DomainContext object or even know how data is loaded behind the scenes: public class AdminViewModel : ViewModelBase { ServiceAgent _ServiceAgent = new ServiceAgent(); public AdminViewModel() { if (!DesignerProperties.IsInDesignTool) { LoadBooks(); } } private void LoadBooks() { _ServiceAgent.LoadBooks(LoadBooksCallback); } private void LoadBooksCallback(ObservableCollection<Book> books) { Books = books } } You could also handle the LoadBooksCallback method using a lambda if you wanted to minimize code just like I did earlier with the LoadBooks method in the ServiceAgent class.  If you’re into Dependency Injection (DI), you could create an interface for the ServiceAgent type, reference it in the ViewModel and then inject in the object to use at runtime. There are certainly other techniques and strategies that can be used, but the code shown here provides an introductory look at the topic that should help get you started abstracting the DomainContext out of your ViewModel classes when using WCF RIA Services in Silverlight applications.

    Read the article

  • Silverlight unit testing. Error while running tests.

    - by 1gn1ter
    I'm using VS2010. Silverlight 4, NUnit 2.5.5, and TypeMock TypemockIsolatorSetup6.0.3.619.msi In the test project MVVM is implemented, PeopleViewModel is a ViewModel which I want to test. Please advise if you use other products for unit testing of MVVM Silverlight. Or please help to win this TypeMock. TIA This is the code of the test: [Test] [SilverlightUnitTest] public void SomeTestAgainstSilverlight() { PeopleViewModel o = new PeopleViewModel(); var res = o.People; Assert.AreEqual(15, res.Count()); } While running the test in ReSharper i get the following error: TestA.SomeTestAgainstSilverlight : Failed****************************************** *Loading Silverlight Isolation Aspects...* ****************************************** TEST RESULTS: --------------------------------------------- System.MissingMethodException : Method not found: 'hv TypeMock.ArrangeActAssert.Isolate.a(System.Delegate)'. at a4.a(ref Delegate A_0) at a4.a(Boolean A_0) at il.b() at CThru.Silverlight.SilverlightUnitTestAttribute.Init() at CThru.Silverlight.SilverlightUnitTestAttribute.Execute() at TypeMock.MockManager.a(String A_0, String A_1, Object A_2, Object A_3, Boolean A_4, Object[] A_5) at TypeMock.InternalMockManager.getReturn(Object that, String typeName, String methodName, Object methodParameters, Boolean isInjected) at Tests.TestA.SomeTestAgainstSilverlight() in TestA.cs: line 21 While running test in NUnit i get: Tests.TestA.SomeTestAgainstSilverlight: System.DllNotFoundException : Unable to load DLL 'agcore': The specified module could not be found. (Exception from HRESULT: 0x8007007E) at MS.Internal.XcpImports.Application_GetCurrentNative(IntPtr context, IntPtr& obj) at MS.Internal.XcpImports.Application_GetCurrent(IntPtr& pApp) at System.Windows.Application.get_Current() at ViewModelExample.ViewModel.ViewModelBase.get_IsDesignTime() in C:\Documents and Settings\USER\Desktop\ViewModelExample\ViewModelExample\ViewModel\ViewModelBase.cs:line 20 at ViewModelExample.ViewModel.PeopleViewModel..ctor(IServiceAgent serviceAgent) in C:\Documents and Settings\USER\Desktop\ViewModelExample\ViewModelExample\ViewModel\PeopleViewModel.cs:line 28 at ViewModelExample.ViewModel.PeopleViewModel..ctor() in C:\Documents and Settings\USER\Desktop\ViewModelExample\ViewModelExample\ViewModel\PeopleViewModel.cs:line 24 at Tests.TestA.SomeTestAgainstSilverlight() in C:\Documents and Settings\USER\Desktop\ViewModelExample\Tests\TestA.cs:line 22

    Read the article

  • C# MVVM Calculating Total

    - by LnDCobra
    I need to calculate a trade value based on the selected price and quantity. How can The following is my ViewModel: class ViewModel : ViewModelBase { public Trade Trade { get { return _trade; } set { SetField(ref _trade, value, () => Trade); } } private Trade _trade; public decimal TradeValue { get { return Trade.Amount * Trade.Price; } } } ViewModelBase inherits INotifyPropertyChanged and contains SetField() The Following is the Trade class: public class Trade : INotifyPropertyChaged { public virtual Decimal Amount { get { return _amount; } set { SetField(ref _amount, value, () => Amount); } } private Decimal _amount; public virtual Decimal Price { get { return _price; } set { SetField(ref _price, value, () => Price); } } private Decimal _price; ...... } I know due to the design my TradeValue only gets calculated once (when its first requested) and UI doesn't get updated when amount/price changes. What is the best way of achieving this? Any help greatly appreciated.

    Read the article

  • CodePlex Daily Summary for Friday, January 28, 2011

    CodePlex Daily Summary for Friday, January 28, 2011Popular ReleasesVFPX: VFP2C32 2.0.0.8 Release Candidate: This release includes several bugfixes, new functions and finally a CHM help file for the complete library.EnhSim: EnhSim 2.3.3 ALPHA: 2.3.3 ALPHAThis release supports WoW patch 4.06 at level 85 To use this release, you must have the Microsoft Visual C++ 2010 Redistributable Package installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=A7B7A05E-6DE6-4D3A-A423-37BF0912DB84 To use the GUI you must have the .NET 4.0 Framework installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992 - Added back in a p...DB>doc for Microsoft SQL Server: 1.0.0.0: Initial release Supported output HTML WikiPlex markup Raw XML Supported objects Tables Primary Keys Foreign Keys ViewsmojoPortal: 2.3.6.1: see release notes on mojoportal.com http://www.mojoportal.com/mojoportal-2361-released.aspx Note that we have separate deployment packages for .NET 3.5 and .NET 4.0 The deployment package downloads on this page are pre-compiled and ready for production deployment, they contain no C# source code. To download the source code see the Source Code Tab I recommend getting the latest source code using TortoiseHG, you can get the source code corresponding to this release here.Office Web.UI: Alpha preview: This is the first alpha release. Very exciting moment... This download is just the demo application : "Contoso backoffice Web App". No source included for the moment, just the app, for testing purposes and for feedbacks !! This package includes a set of official MS Office icons (143 png 16x16 and 132 png 32x32) to really make a great app ! Please rate and give feedback ThanksParallel Programming with Microsoft Visual C++: Drop 6 - Chapters 4 and 5: This is Drop 6. It includes: Drafts of the Preface, Introduction, Chapters 2-7, Appendix B & C and the glossary Sample code for chapters 2-7 and Appendix A & B. The new material we'd like feedback on is: Chapter 4 - Parallel Aggregation Chapter 5 - Futures The source code requires Visual Studio 2010 in order to run. There is a known bug in the A-Dash sample when the user attempts to cancel a parallel calculation. We are working to fix this.Catel - WPF and Silverlight MVVM library: 1.1: (+) Styles can now be changed dynamically, see Examples application for a how-to (+) ViewModelBase class now have a constructor that allows services injection (+) ViewModelBase services can now be configured by IoC (via Microsoft.Unity) (+) All ViewModelBase services now have a unit test implementation (+) Added IProcessService to run processes from a viewmodel with directly using the process class (which makes it easier to unit test view models) (*) If the HasErrors property of DataObjec...NodeXL: Network Overview, Discovery and Exploration for Excel: NodeXL Excel Template, version 1.0.1.160: The NodeXL Excel template displays a network graph using edge and vertex lists stored in an Excel 2007 or Excel 2010 workbook. What's NewThis release improves NodeXL's Twitter and Pajek features. See the Complete NodeXL Release History for details. Installation StepsFollow these steps to install and use the template: Download the Zip file. Unzip it into any folder. Use WinZip or a similar program, or just right-click the Zip file in Windows Explorer and select "Extract All." Close Ex...Kooboo CMS: Kooboo CMS 3.0 CTP: Files in this downloadkooboo_CMS.zip: The kooboo application files Content_DBProvider.zip: Additional content database implementation of MSSQL, RavenDB and SQLCE. Default is XML based database. To use them, copy the related dlls into web root bin folder and remove old content provider dlls. Content provider has the name like "Kooboo.CMS.Content.Persistence.SQLServer.dll" View_Engines.zip: Supports of Razor, webform and NVelocity view engine. Copy the dlls into web root bin folder to enable...UOB & ME: UOB ME 2.6: UOB ME 2.6????: ???? V1.0: ???? V1.0 ??Password Generator: 2.2: Parallel password generation Password strength calculation ( Same method used by Microsoft here : https://www.microsoft.com/protect/fraud/passwords/checker.aspx ) Minor code refactoringVisual Studio 2010 Architecture Tooling Guidance: Spanish - Architecture Guidance: Francisco Fagas http://geeks.ms/blogs/ffagas, Microsoft Most Valuable Professional (MVP), localized the Visual Studio 2010 Quick Reference Guidance for the Spanish communities, based on http://vsarchitectureguide.codeplex.com/releases/view/47828. Release Notes The guidance is available in a xps-only (default) or complete package. The complete package contains the files in xps, pdf and Office 2007 formats. 2011-01-24 Publish version 1.0 of the Spanish localized bits.ASP.NET MVC Project Awesome, jQuery Ajax helpers (controls): 1.6.2: A rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form, Popup and Pager the html generation has been optimized, the html page size is much smaller nowFacebook Graph Toolkit: Facebook Graph Toolkit 0.6: new Facebook Graph objects: Application, Page, Post, Comment Improved Intellisense documentation new Graph Api connections: albums, photos, posts, feed, home, friends JSON Toolkit upgraded to version 0.9 (beta release) with bug fixes and new features bug fixed: error when handling empty JSON arrays bug fixed: error when handling JSON array with square or large brackets in the message bug fixed: error when handling JSON obejcts with double quotation in the message bug fixed: erro...Microsoft All-In-One Code Framework: Visual Studio 2008 Code Samples 2011-01-23: Code samples for Visual Studio 2008MVVM Light Toolkit: MVVM Light Toolkit V3 SP1 (3): Instructions for installation: http://www.galasoft.ch/mvvm/installing/manually/ Includes the hotfix templates for Windows Phone 7 development. This is only relevant if you didn't already install the hotfix described at http://blog.galasoft.ch/archive/2010/07/22/mvvm-light-hotfix-for-windows-phone-7-developer-tools-beta.aspx.Community Forums NNTP bridge: Community Forums NNTP Bridge V42: Release of the Community Forums NNTP Bridge to access the social and anwsers MS forums with a single, open source NNTP bridge. This release has added some features / bugfixes: Bugfix: Decoding of Subject now also supports multi-line subjects (occurs only if you have very long subjects with non-ASCII characters)Minecraft Tools: Minecraft Topographical Survey 1.3: MTS requires version 4 of the .NET Framework - you must download it from Microsoft if you have not previously installed it. This version of MTS adds automatic block list updates, so MTS will recognize blocks added in game updates properly rather than drawing them in bright pink. New in this version of MTS: Support for all new blocks added since the Halloween update Auto-update of blockcolors.xml to support future game updates A splash screen that shows while the program searches for upd...StyleCop for ReSharper: StyleCop for ReSharper 5.1.14996.000: New Features: ============= This release is just compiled against the latest release of JetBrains ReSharper 5.1.1766.4 Previous release: A considerable amount of work has gone into this release: Huge focus on performance around the violation scanning subsystem: - caching added to reduce IO operations around reading and merging of settings files - caching added to reduce creation of expensive objects Users should notice condsiderable perf boost and a decrease in memory usage. Bug Fixes...New ProjectsAgilErp: AgilErp is a .NET OpenSource ERP - System developed in C# using WPF, WCF ,Entity Framework, MS-SQL-Server and MVVM. Angel Eye: 3d Game for the new generation AWWWE Browser: AWWWE Browser. (Pronounced "awe".) Aural World Wide Web Everywhere. 1) An aural browser. It talks and listens to you and you talk and listen to it. 2) A VUI for normal HTML web sites. It lets regular web sites talk and listen to you while you talk and listen to them.BitLocker Wrapper Library: The BDE Wrapper library allows .NET Developers to quickly use the WMI BitLocker provider without having to learn the complex methods and operation of the WMI classes.CRM8000: CRM8000????????????????DSM Hub for WP7: Implements a light version of the DSM tools for WP7. Currently, most of the effort is on the audio station.File Downloader: This application checks a Gmail account regularly for mail containing URLs. Once a URL is found, its content is downloaded and sent as a reply message with the file as an attachment. Intended usage: - Download IEEE articles as PDF when you're not in a authenticated network.Folder Space Quota: This component return Quotas Disk Space used for each folders and subfolders in a given directory. Results are returned with a graphic percent bar. Another Tab give access to this directory tree, indicating the size of each file and allows previewing them in a "LightBox" window. IDK: Every other month, IDK asks people to come up with awesome ideas for new programs and webpages. After the end of the month, IDKs developers have another month to create one of the top rated websites or applications. Got a great idea for a new app? Let IDK build it for you.Interop 2: Microformats for Azure Cloud with OData-InterfacejSPoint - JavaScript Library for SharePoint: JavaScript for SharePoint (jSPoint) is a library that help SharePoint developers to create rich,dynamic, & powerfull pages for SharePoint sites.MVVM T4: T4 Templates for generating view models, and views for WPF, Silverlight, Windows Phone using T4 Toolbox and MVVM LightNumericUpDown Control for WPF: A basic NumericUpDown Control for WPF that mirrors all the most used functions of the WinForms NumericUpDown Control and looks similar to itOData for IQToolkit: OData for IQToolkit, converts OData expressions into a usable expressions for IQToolkit providers.PLATO: PALTO is micro plate processing pipeline and supports enzymes and metabolites. PLATO was developed at INRA-Bordeaux and is an evolution of the EnzymeLaborTool developed at the Max-Planck Institute of Molecular Plant Physiology.Purdue CS 490: Model-based testing of ADO.NET: Five students from Purdue University will develop model-based tests for an aspect of ADO.NET during the Spring 2011 semester. We'll be using C# and Spec Explorer, among other tools.Replace in multiple Office 2010 documents: This program replaces a text string in multiple office 2010 documents (Word, Excel, PowerPoint). It is developed in VB.NET and new code for additional products is welcome. SearchEngine: A Website Search Engine and Crawler.Set Custom Currency Symbol: This utility enables you to set/register custom currency symbols for the .NET FrameworkSimple C# Email Templates: A really simple, really easy to use class for sending email templates. Reads any file from disk (think ".txt" or ".html") and matches custom tokens with the values you supply, in both the message body and the subject line. Supports multiple CC and BCC addresses.SimpleBasicAuthentication: SimpleBasicAuthentication makes it easier for developers to build a website with basic authentication using the credentials from just a text file. You'll no longer have to create new users on the system just to let them log in to the website or service. It's developed in C# 4.0.SpecsFor - Yet Another BDD Framework For .NET: SpecsFor is another Behavior-Driven Development framework that focuses on ease of use for *developers* by minimizing testing friction. Square: Custom SharePoint MyProfile PageSynchrolist workflow: Sharepoint workflow whitch perform automatic synchronisation between two lists in the same collection. Usefull for automatic translation.TFS Aggregator: This server side plugin for TFS 2010 enables dynamic calculation of field values in TFS. (For example: Dev work + Test Work = Total Work) Supports same work item and parent-child links. Also has support for aggregating string values (ie Children are Done so the parent is Done)Tinchant: My nice projectZebra_Image, a lightweight image manipulation library written in PHP: This is a compact (one-file only), lightweight, object-oriented image manipulation library written in and for PHP, that provides methods for performing several types of image manipulation operations. It doesn’t require any external libraries other than the GD2 extension.Zebra_Pagination, a generic pagination class written in PHP: A generic pagination class that automatically generates navigation links given the total number of items and the number of items per page.Zebra_Session, a wrapper for PHP’s default session handler, using MySQL: Zebra_Session is a PHP class that acts as a wrapper for PHP’s default session handling functions but instead of storing session data in flat files it stores them in a MySQL database, thus providing both better security and better performance.

    Read the article

  • CodePlex Daily Summary for Thursday, January 27, 2011

    CodePlex Daily Summary for Thursday, January 27, 2011Popular ReleasesVFPX: VFP2C32 2.0.0.8 Release Candidate: This release includes several bugfixes, new functions and finally a CHM help file for the complete library.EnhSim: EnhSim 2.3.3 ALPHA: 2.3.3 ALPHAThis release supports WoW patch 4.06 at level 85 To use this release, you must have the Microsoft Visual C++ 2010 Redistributable Package installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=A7B7A05E-6DE6-4D3A-A423-37BF0912DB84 To use the GUI you must have the .NET 4.0 Framework installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992 - Added back in a p...DB>doc for Microsoft SQL Server: 1.0.0.0: Initial release Supported output HTML WikiPlex markup Raw XML Supported objects Tables Primary Keys Foreign Keys ViewsOffice Web.UI: Alpha preview: This is the first alpha release. Very exciting moment... This download is just the demo application : "Contoso backoffice Web App". No source included for the moment, just the app, for testing purposes and for feedbacks !! This package includes a set of official MS Office icons (143 png 16x16 and 132 png 32x32) to really make a great app ! Please rate and give feedback ThanksParallel Programming with Microsoft Visual C++: Drop 6 - Chapters 4 and 5: This is Drop 6. It includes: Drafts of the Preface, Introduction, Chapters 2-7, Appendix B & C and the glossary Sample code for chapters 2-7 and Appendix A & B. The new material we'd like feedback on is: Chapter 4 - Parallel Aggregation Chapter 5 - Futures The source code requires Visual Studio 2010 in order to run. There is a known bug in the A-Dash sample when the user attempts to cancel a parallel calculation. We are working to fix this.Catel - WPF and Silverlight MVVM library: 1.1: (+) Styles can now be changed dynamically, see Examples application for a how-to (+) ViewModelBase class now have a constructor that allows services injection (+) ViewModelBase services can now be configured by IoC (via Microsoft.Unity) (+) All ViewModelBase services now have a unit test implementation (+) Added IProcessService to run processes from a viewmodel with directly using the process class (which makes it easier to unit test view models) (*) If the HasErrors property of DataObjec...NodeXL: Network Overview, Discovery and Exploration for Excel: NodeXL Excel Template, version 1.0.1.160: The NodeXL Excel template displays a network graph using edge and vertex lists stored in an Excel 2007 or Excel 2010 workbook. What's NewThis release improves NodeXL's Twitter and Pajek features. See the Complete NodeXL Release History for details. Installation StepsFollow these steps to install and use the template: Download the Zip file. Unzip it into any folder. Use WinZip or a similar program, or just right-click the Zip file in Windows Explorer and select "Extract All." Close Ex...Kooboo CMS: Kooboo CMS 3.0 CTP: Files in this downloadkooboo_CMS.zip: The kooboo application files Content_DBProvider.zip: Additional content database implementation of MSSQL, RavenDB and SQLCE. Default is XML based database. To use them, copy the related dlls into web root bin folder and remove old content provider dlls. Content provider has the name like "Kooboo.CMS.Content.Persistence.SQLServer.dll" View_Engines.zip: Supports of Razor, webform and NVelocity view engine. Copy the dlls into web root bin folder to enable...UOB & ME: UOB ME 2.6: UOB ME 2.6????: ???? V1.0: ???? V1.0 ??Password Generator: 2.2: Parallel password generation Password strength calculation ( Same method used by Microsoft here : https://www.microsoft.com/protect/fraud/passwords/checker.aspx ) Minor code refactoringVisual Studio 2010 Architecture Tooling Guidance: Spanish - Architecture Guidance: Francisco Fagas http://geeks.ms/blogs/ffagas, Microsoft Most Valuable Professional (MVP), localized the Visual Studio 2010 Quick Reference Guidance for the Spanish communities, based on http://vsarchitectureguide.codeplex.com/releases/view/47828. Release Notes The guidance is available in a xps-only (default) or complete package. The complete package contains the files in xps, pdf and Office 2007 formats. 2011-01-24 Publish version 1.0 of the Spanish localized bits.ASP.NET MVC Project Awesome, jQuery Ajax helpers (controls): 1.6.2: A rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form, Popup and Pager the html generation has been optimized, the html page size is much smaller nowFacebook Graph Toolkit: Facebook Graph Toolkit 0.6: new Facebook Graph objects: Application, Page, Post, Comment Improved Intellisense documentation new Graph Api connections: albums, photos, posts, feed, home, friends JSON Toolkit upgraded to version 0.9 (beta release) with bug fixes and new features bug fixed: error when handling empty JSON arrays bug fixed: error when handling JSON array with square or large brackets in the message bug fixed: error when handling JSON obejcts with double quotation in the message bug fixed: erro...Microsoft All-In-One Code Framework: Visual Studio 2008 Code Samples 2011-01-23: Code samples for Visual Studio 2008BloodSim: BloodSim - 1.4.0.0: This version requires an update for WControls.dll. - Removed option to use Old Rune Strike - Fixed an issue that was causing Ratings to not properly update when running Progressive simulations - Ability data is now loaded from an XML file in the BloodSim directory that is user editable. This data will be reloaded each time a fresh simulation is run. - Added toggle for showing Graph window. When unchecked, output data will instead be saved to a text file in the BloodSim directory based on the...MVVM Light Toolkit: MVVM Light Toolkit V3 SP1 (3): Instructions for installation: http://www.galasoft.ch/mvvm/installing/manually/ Includes the hotfix templates for Windows Phone 7 development. This is only relevant if you didn't already install the hotfix described at http://blog.galasoft.ch/archive/2010/07/22/mvvm-light-hotfix-for-windows-phone-7-developer-tools-beta.aspx.Minecraft Tools: Minecraft Topographical Survey 1.3: MTS requires version 4 of the .NET Framework - you must download it from Microsoft if you have not previously installed it. This version of MTS adds automatic block list updates, so MTS will recognize blocks added in game updates properly rather than drawing them in bright pink. New in this version of MTS: Support for all new blocks added since the Halloween update Auto-update of blockcolors.xml to support future game updates A splash screen that shows while the program searches for upd...StyleCop for ReSharper: StyleCop for ReSharper 5.1.14996.000: New Features: ============= This release is just compiled against the latest release of JetBrains ReSharper 5.1.1766.4 Previous release: A considerable amount of work has gone into this release: Huge focus on performance around the violation scanning subsystem: - caching added to reduce IO operations around reading and merging of settings files - caching added to reduce creation of expensive objects Users should notice condsiderable perf boost and a decrease in memory usage. Bug Fixes...MediaScout: MediaScout 3.0 Preview 4: Update ReleaseNew ProjectsCaltrain: Caltrain WP7 free app. Fast and easy way to get caltrain schedules on your windows phone.DB>doc for Microsoft SQL Server: Tool to generate documentation for Microsoft SQL Server database structure. Generates documentation in HTML, XML or WikiPlex format.Delete any type of files: This is a small utility which can be used to delete any type of file from any directory (and it's sub-directories) based on their modified date. You can control all settings via app.config and DeleteFile.config files. DEV Achievements - VS2010 Extension: An extension to get, view and manage your Visual Studio 2010 Achievements :)DirectCanvas: A hardware accelerated, 2D drawing API.Gonte.Web: - Helpers to interface javascript frameworks (such as extjs) - Web utilities for ASP.NET MVCgqq mvc: I create this project to enhance my understand to mvc3. Razor is an excite tool for mvc.jQuery mvctemplate: mvctemplate is a simple jquery plugin that makes it simple to enable great client side functionality for ASP.NET MVC views that bind to models with IEnumerable properties. You get full templating while still being able to use your favorite Html extension methods.List-View navigation WebPart: The ListViewNavigation WebPart shows a list of all your lists/document libraries and their views.Management Cluster Memory SQL Server: Management of automatic configuration of memory instance SQL Server on Cluster Service.MessengerBot: A bot for the Windows Live Messenger system, built on top of msnp-sharp (http://code.google.com/p/msnp-sharp/), using pluggable extensions to respond to various commands. Example usage: monitor a server, monitor your build process, application status or interface, etc.Microsoft Streetslide API (hack): Microsoft Research has developed a street slide, revolutionary new street map. However, it currently works only in iPhone Bing App, so I tried to sneak its API for developers who are interested in. It won't have actual source code until I decided it needed.Moodle 2.0 for Azure: Moodle 2.0 port to Windows Azure platform, using SQL Azure and Azure Drives.MvcCodeRouting: MvcCodeRouting for ASP.NET MVC analyzes your controllers and actions and automatically creates the best possible routes for them.Office Web.UI: Office Web UI provides visual components to create consitant web apps that look like Office.Orchard Choice List Custom Field: Adds a new field type, ChoiceList, to your Orchard Project installation. Creates a simple drop-down list. Add the field to a content type, then add a semi-colon-delimited list of items. Written in C#.Procedural 2D terrain generator: Small application used for procedurally generating a terrain for a one-level 2D tilemap. Makes use of "ant" style algorithms for randomly generating the terrain. It's made in VB.NET: Idea is for others to reproduce the algorithms in their language / game engine of choice.QuanLyKho: Qu?n lý kho hàngSharepoint Custom fields (lookup,ID and Choice): Sharepoint Custom fields project is an amelioration of basic sharepoint fields. Are included: - A lookup field and multi choice field with muti column view and other functionnalities. - An ID field to use ID in calculated fields - Modification of SoapService for Excel use.Silverlight.Me: this is an open source website.we want to create a website about silverlight.then there's all our ideas.Tigerkin's Code Zone: My code will be put on this site.WPTinyApps: A collection of small Windows Phone 7 apps I've released as open sourceZebra_Database, a MySQL database wrapper written in PHP: Zebra_Database it is an advanced, compact (one-file only), lightweight, object-oriented MySQL database wrapper built upon PHP’s MySQL extension. It provides methods for interacting with MySQL databases that are more intuitive and fun to use than PHP’s default ones.

    Read the article

  • CodePlex Daily Summary for Wednesday, January 26, 2011

    CodePlex Daily Summary for Wednesday, January 26, 2011Popular ReleasesCatel - WPF and Silverlight MVVM library: 1.1: (+) Styles can now be changed dynamically, see Examples application for a how-to (+) ViewModelBase class now have a constructor that allows services injection (+) ViewModelBase services can now be configured by IoC (via Microsoft.Unity) (+) All ViewModelBase services now have a unit test implementation (+) Added IProcessService to run processes from a viewmodel with directly using the process class (which makes it easier to unit test view models) (*) If the HasErrors property of DataObjec...NodeXL: Network Overview, Discovery and Exploration for Excel: NodeXL Excel Template, version 1.0.1.160: The NodeXL Excel template displays a network graph using edge and vertex lists stored in an Excel 2007 or Excel 2010 workbook. What's NewThis release improves NodeXL's Twitter and Pajek features. See the Complete NodeXL Release History for details. Installation StepsFollow these steps to install and use the template: Download the Zip file. Unzip it into any folder. Use WinZip or a similar program, or just right-click the Zip file in Windows Explorer and select "Extract All." Close Ex...MVC Foolproof Validation: Beta 0.9.4042: Fixed a few bugs and added ASP.NET MVC 3 support (Including Unobtrusive JavaScript support).Kooboo CMS: Kooboo CMS 3.0 CTP: Files in this downloadkooboo_CMS.zip: The kooboo application files Content_DBProvider.zip: Additional content database implementation of MSSQL, RavenDB and SQLCE. Default is XML based database. To use them, copy the related dlls into web root bin folder and remove old content provider dlls. Content provider has the name like "Kooboo.CMS.Content.Persistence.SQLServer.dll" View_Engines.zip: Supports of Razor, webform and NVelocity view engine. Copy the dlls into web root bin folder to enable...UOB & ME: UOB ME 2.6: UOB ME 2.6????: ???? V1.0: ???? V1.0 ??Developer Guidance - Onboarding Windows Phone 7: Fuel Tracker Source: Release NotesThis project is almost complete. We'll be making small updates to the code and documentation over the next week or so. We look forward to your feedback. This documentation and accompanying sample application will get you started creating a complete application for Windows Phone 7. You will learn about common developer issues in the context of a simple fuel-tracking application named Fuel Tracker. Some of the tasks that you will learn include the following: Creating a UI that...Password Generator: 2.2: Parallel password generation Password strength calculation ( Same method used by Microsoft here : https://www.microsoft.com/protect/fraud/passwords/checker.aspx ) Minor code refactoringVisual Studio 2010 Architecture Tooling Guidance: Spanish - Architecture Guidance: Francisco Fagas http://geeks.ms/blogs/ffagas, Microsoft Most Valuable Professional (MVP), localized the Visual Studio 2010 Quick Reference Guidance for the Spanish communities, based on http://vsarchitectureguide.codeplex.com/releases/view/47828. Release Notes The guidance is available in a xps-only (default) or complete package. The complete package contains the files in xps, pdf and Office 2007 formats. 2011-01-24 Publish version 1.0 of the Spanish localized bits.ASP.NET MVC Project Awesome, jQuery Ajax helpers (controls): 1.6.2: A rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form, Popup and Pager the html generation has been optimized, the html page size is much smaller nowFacebook Graph Toolkit: Facebook Graph Toolkit 0.6: new Facebook Graph objects: Application, Page, Post, Comment Improved Intellisense documentation new Graph Api connections: albums, photos, posts, feed, home, friends JSON Toolkit upgraded to version 0.9 (beta release) with bug fixes and new features bug fixed: error when handling empty JSON arrays bug fixed: error when handling JSON array with square or large brackets in the message bug fixed: error when handling JSON obejcts with double quotation in the message bug fixed: erro...Microsoft All-In-One Code Framework: Visual Studio 2008 Code Samples 2011-01-23: Code samples for Visual Studio 2008BloodSim: BloodSim - 1.4.0.0: This version requires an update for WControls.dll. - Removed option to use Old Rune Strike - Fixed an issue that was causing Ratings to not properly update when running Progressive simulations - Ability data is now loaded from an XML file in the BloodSim directory that is user editable. This data will be reloaded each time a fresh simulation is run. - Added toggle for showing Graph window. When unchecked, output data will instead be saved to a text file in the BloodSim directory based on the...MVVM Light Toolkit: MVVM Light Toolkit V3 SP1 (3): Instructions for installation: http://www.galasoft.ch/mvvm/installing/manually/ Includes the hotfix templates for Windows Phone 7 development. This is only relevant if you didn't already install the hotfix described at http://blog.galasoft.ch/archive/2010/07/22/mvvm-light-hotfix-for-windows-phone-7-developer-tools-beta.aspx.Community Forums NNTP bridge: Community Forums NNTP Bridge V42: Release of the Community Forums NNTP Bridge to access the social and anwsers MS forums with a single, open source NNTP bridge. This release has added some features / bugfixes: Bugfix: Decoding of Subject now also supports multi-line subjects (occurs only if you have very long subjects with non-ASCII characters)Minecraft Tools: Minecraft Topographical Survey 1.3: MTS requires version 4 of the .NET Framework - you must download it from Microsoft if you have not previously installed it. This version of MTS adds automatic block list updates, so MTS will recognize blocks added in game updates properly rather than drawing them in bright pink. New in this version of MTS: Support for all new blocks added since the Halloween update Auto-update of blockcolors.xml to support future game updates A splash screen that shows while the program searches for upd...StyleCop for ReSharper: StyleCop for ReSharper 5.1.14996.000: New Features: ============= This release is just compiled against the latest release of JetBrains ReSharper 5.1.1766.4 Previous release: A considerable amount of work has gone into this release: Huge focus on performance around the violation scanning subsystem: - caching added to reduce IO operations around reading and merging of settings files - caching added to reduce creation of expensive objects Users should notice condsiderable perf boost and a decrease in memory usage. Bug Fixes...MediaScout: MediaScout 3.0 Preview 4: Update ReleaseMFCMAPI: January 2011 Release: Build: 6.0.0.1024 Full release notes at SGriffin's blog. If you just want to run the tool, get the executable. If you want to debug it, get the symbol file and the source. The 64 bit build will only work on a machine with Outlook 2010 64 bit installed. All other machines should use the 32 bit build, regardless of the operating system. Facebook BadgeAutoLoL: AutoLoL v1.5.4: Added champion: Renekton Removed automatic file association Fix: The recent files combobox didn't always open a file when an item was selected Fix: Removing a recently opened file caused an errorNew Projects? ! :): AskAnswerDone (? ! :)) is a free and open source Q&A platform. Your user choses a problem they're having (like "ERROR: 123" or "THE PICTURES DONT SHOW"), choses something about the program that they can help with, and gets their answer while helping someone else. Chat by Mibbit.BusinessControl2: BusinessControl project. v. 2Citizen Journalism Network Server: An educational project that will hopefully one day prove useful. Initially a simple ASP.NET MVC 3 implementation of the Atom Publishing Protocol, and later have features for federated servers, geolocation, advanced searching, and ratings.ciws-distr: CIWS distrContentFinder: Help user to find the content in every file in your folder.ContentFinder Support Regex Search and the UI will not freeze any more.CSC446: database driven website done with silverlightElos: Projeto ElosEnhanced Host File Manager: Enhanced Host File Editor / Manager Intended for web development (developers or designers) to switch between development and live easily, hassle free. Full access to the host file is required. It is assumed that host file is at default location: C:\Windows\System32\drivers\etcHelloWorld: As a sample center, HelloWorld sketches the skeletons of most Microsoft development techniques. Each sample is elaborately selected, composed, and documented to demonstrate one frequently-asked/tested/used scenario based on my experience as a support engineer. InkSpot: Adds SVG runtime support to WPF applications.ITaCS Change Password web part: This web part allows users to change their local or Active Directory password from within a MOSS or WSS Site.JoscalSoftware: At JoscalSoftware you can find programs designed (mostly) in Visual Basic 2010 Express. Most programs are to do with text editors, and webbrowsers.K.Frame: A open .net structual for enterprice application with MVC,iBatis.Net,WCF,etc.LogExpert: Windows tail program and log file analyzer.MasterGuitarReader: This project is a free guitar tab readerOpalis Scheduled Tasks Integration Pack: A Opalis integration pack for manipulating scheduled tasks on windows systems.OpenInsure: OpenInsure is an OpenSource Insurance Agent automation system. It is being developed using the .Net 4.0 frame work and is using a SQL 2008 backend. Orchard Hyperlink Custom Field: The Hyperlink module introduces a new field to store hyperlinks as custom types. Includes URL, label, title, and target. It's developed in C# as a plugin to the Orchard CMS project.Orchard Stars: A simple five-star rating Orchard module.PerformancePoint 2010 Content Deployment Tool: The PerformancePoint 2010 Content Deployment Tool is a command-line tool that allows you to deploy PerformancePoint content using an existing ddwx file and can be used to migrate content from development to production or between site collections on the same SharePoint server.Plat Manager / Real Estate management application: The administration module is meant to manage 3 web clients with their real estate databases. The main feature is ability to automatically generate the interface of the module based on the information pulled from the database. PHP, MySQL, MVC Kohana, Doctrene ORM, Ajax, ExtJSSalesManager: SalesManagerSercury: ????????,????WCF??????????????。SGPF: The team does not have nothing to declare here!Sitefinity Social Widgets Contrib: Sitefinity Social Widget Contrib makes it easier for GiveCamp Charities and other Sitefinity users to pull their social feeds into your site. You'll no longer have to build one off controls. It's developed in a combination of C# and JQuery.StackHash Plugin SDK & Sample Plugins (for WinQual / Windows Error Reporting): Plugin SDK and sample command line, email and FogBugz plugins for StackHash. StackHash is a tool that helps developers access crash reports from Microsoft's WinQual service (Windows Error Reporting). The SDK is designed to support synchronizing StackHash data with bug trackers.TIC: ticTwedge: Twedge is a customizable Silverlight-based Twitter badge, showing the latst tweets, based on your specific search term.Web Scripting and Content Creation Code Samples: Sample code used in the Web Scripting and Content Creation course at the University of HertfordshirewebSurfer - a test tool: Windows Workflow Foundation, WWF, test web pagesWLCompus: WLCompusYellow Rice: Yellow RiceZDStar Enterprise Framework: ZDStar Enterprise Framework for Small & Medium Size Enterprises.

    Read the article

  • CodePlex Daily Summary for Saturday, January 29, 2011

    CodePlex Daily Summary for Saturday, January 29, 2011Popular ReleasesRawr: Rawr 4.0.17 Beta: Rawr is now web-based. The link to use Rawr4 is: http://elitistjerks.com/rawr.phpThis is the Cataclysm Beta Release. More details can be found at the following link http://rawr.codeplex.com/Thread/View.aspx?ThreadId=237262 and on the Version Notes page: http://rawr.codeplex.com/wikipage?title=VersionNotes As of the 4.0.16 release, you can now also begin using the new Downloadable WPF version of Rawr!This is a pre-alpha release of the WPF version, there are likely to be a lot of issues. If you...VivoSocial: VivoSocial 7.4.2: Version 7.4.2 of VivoSocial has been released. If you experienced any issues with the previous version, please update your modules to the 7.4.2 release and see if they persist. If you have any questions about this release, please post them in our Support forums. If you are experiencing a bug or would like to request a new feature, please submit it to our issue tracker. Web Controls * Updated Business Objects and added a new SQL Data Provider File. Groups * Fixed a security issue whe...PHP Manager for IIS: PHP Manager 1.1.1 for IIS 7: This is a minor release of PHP Manager for IIS 7. It contains all the functionality available in 56962 plus several bug fixes (see change list for more details). Also, this release includes Russian language support. SHA1 codes for the downloads are: PHPManagerForIIS-1.1.0-x86.msi - 6570B4A8AC8B5B776171C2BA0572C190F0900DE2 PHPManagerForIIS-1.1.0-x64.msi - 12EDE004EFEE57282EF11A8BAD1DC1ADFD66A654BloodSim: WControls.dll update: Priority Update It's just come to my attention that the latest version of WControls.dll was not included in the 1.4 release and as a result, BloodSim has been unuseable. Please download WControls.dll from here, and this will rectify the issue.VFPX: VFP2C32 2.0.0.8 Release Candidate: This release includes several bugfixes, new functions and finally a CHM help file for the complete library.DB>doc for Microsoft SQL Server: 1.0.0.0: Initial release Supported output HTML WikiPlex markup Raw XML Supported objects Tables Primary Keys Foreign Keys ViewsmojoPortal: 2.3.6.1: see release notes on mojoportal.com http://www.mojoportal.com/mojoportal-2361-released.aspx Note that we have separate deployment packages for .NET 3.5 and .NET 4.0 The deployment package downloads on this page are pre-compiled and ready for production deployment, they contain no C# source code. To download the source code see the Source Code Tab I recommend getting the latest source code using TortoiseHG, you can get the source code corresponding to this release here.Office Web.UI: Alpha preview: This is the first alpha release. Very exciting moment... This download is just the demo application : "Contoso backoffice Web App". No source included for the moment, just the app, for testing purposes and for feedbacks !! This package includes a set of official MS Office icons (143 png 16x16 and 132 png 32x32) to really make a great app ! Please rate and give feedback ThanksParallel Programming with Microsoft Visual C++: Drop 6 - Chapters 4 and 5: This is Drop 6. It includes: Drafts of the Preface, Introduction, Chapters 2-7, Appendix B & C and the glossary Sample code for chapters 2-7 and Appendix A & B. The new material we'd like feedback on is: Chapter 4 - Parallel Aggregation Chapter 5 - Futures The source code requires Visual Studio 2010 in order to run. There is a known bug in the A-Dash sample when the user attempts to cancel a parallel calculation. We are working to fix this.Catel - WPF and Silverlight MVVM library: 1.1: (+) Styles can now be changed dynamically, see Examples application for a how-to (+) ViewModelBase class now have a constructor that allows services injection (+) ViewModelBase services can now be configured by IoC (via Microsoft.Unity) (+) All ViewModelBase services now have a unit test implementation (+) Added IProcessService to run processes from a viewmodel with directly using the process class (which makes it easier to unit test view models) (*) If the HasErrors property of DataObjec...NodeXL: Network Overview, Discovery and Exploration for Excel: NodeXL Excel Template, version 1.0.1.160: The NodeXL Excel template displays a network graph using edge and vertex lists stored in an Excel 2007 or Excel 2010 workbook. What's NewThis release improves NodeXL's Twitter and Pajek features. See the Complete NodeXL Release History for details. Installation StepsFollow these steps to install and use the template: Download the Zip file. Unzip it into any folder. Use WinZip or a similar program, or just right-click the Zip file in Windows Explorer and select "Extract All." Close Ex...Kooboo CMS: Kooboo CMS 3.0 CTP: Files in this downloadkooboo_CMS.zip: The kooboo application files Content_DBProvider.zip: Additional content database implementation of MSSQL, RavenDB and SQLCE. Default is XML based database. To use them, copy the related dlls into web root bin folder and remove old content provider dlls. Content provider has the name like "Kooboo.CMS.Content.Persistence.SQLServer.dll" View_Engines.zip: Supports of Razor, webform and NVelocity view engine. Copy the dlls into web root bin folder to enable...UOB & ME: UOB ME 2.6: UOB ME 2.6????: ???? V1.0: ???? V1.0 ??Password Generator: 2.2: Parallel password generation Password strength calculation ( Same method used by Microsoft here : https://www.microsoft.com/protect/fraud/passwords/checker.aspx ) Minor code refactoringVisual Studio 2010 Architecture Tooling Guidance: Spanish - Architecture Guidance: Francisco Fagas http://geeks.ms/blogs/ffagas, Microsoft Most Valuable Professional (MVP), localized the Visual Studio 2010 Quick Reference Guidance for the Spanish communities, based on http://vsarchitectureguide.codeplex.com/releases/view/47828. Release Notes The guidance is available in a xps-only (default) or complete package. The complete package contains the files in xps, pdf and Office 2007 formats. 2011-01-24 Publish version 1.0 of the Spanish localized bits.ASP.NET MVC Project Awesome, jQuery Ajax helpers (controls): 1.6.2: A rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form, Popup and Pager the html generation has been optimized, the html page size is much smaller nowFacebook Graph Toolkit: Facebook Graph Toolkit 0.6: new Facebook Graph objects: Application, Page, Post, Comment Improved Intellisense documentation new Graph Api connections: albums, photos, posts, feed, home, friends JSON Toolkit upgraded to version 0.9 (beta release) with bug fixes and new features bug fixed: error when handling empty JSON arrays bug fixed: error when handling JSON array with square or large brackets in the message bug fixed: error when handling JSON obejcts with double quotation in the message bug fixed: erro...Microsoft All-In-One Code Framework: Visual Studio 2008 Code Samples 2011-01-23: Code samples for Visual Studio 2008MVVM Light Toolkit: MVVM Light Toolkit V3 SP1 (3): Instructions for installation: http://www.galasoft.ch/mvvm/installing/manually/ Includes the hotfix templates for Windows Phone 7 development. This is only relevant if you didn't already install the hotfix described at http://blog.galasoft.ch/archive/2010/07/22/mvvm-light-hotfix-for-windows-phone-7-developer-tools-beta.aspx.New ProjectsAsp.Net MvcRoute Debugger Visualizer: Asp.Net MvcRoute Debugger Visualizer is an extension for Visual Studio 2010.It displays the matched route data and datatokens of all defined routes in your mvc applicationAutoLaunch for Windows Embedded Compact (CE): AutoLaunch component for Windows Embedded CE 6.0 and Windows Embedded Compact 7BicubicResizeSilverlight: A client-side Silverlight library for performing a bicubic resize. Cloud Monitoring Studio: Cloud Monitoring Studio provides real-time performance monitoring mechanism for Azure deployed applications/Azure roles with the help of easy-to-understand graphs. Users can configure required performance counters for individual Azure roles through easy-to-use & intuitive GUI.CoreCon for Windows Embedded Compact (CE): CoreCon component for Windows Embedded CE 6.0 and Windows Embedded Compact 7, to simplify the tasks needed to include CoreCon files to the OS image.DokanDiscUtils Bridge: This a a bridge for the Dokan library and the DiscUtils library that allows Any partition/image that discutils can open to be mounted using dokanEverything About My Share: Everything About My ShareExtraordinary Ideas: This project contains some Extra oradinary solutions for difficult software problems.. Article's are in Turkish Language tahircakmak.blogspot.comIE9 Helper: The IE9 Helper is an ASP.NET Helper to makes adding IE9 features simple.ITSolutions: .NET Sandbox SolutionsKitty - Async Server: Kitty is an Async Server with C# and Java versions. It builds on Parallelism to deliver a Internet Scale Server StarterKit.mediainfocollector: Retrieves info from mediafilesMini - Async WebSocket Server: Mini is an Async WebSocket Server with versions in C# and Java. It builds on Parallelism and Kitty to deliver an Internet Scale WebSocket Server StarterKit. MVC N-tier EMR Sample Application: This sample uses EMR to showcase a MVC N-Tier application. It uses WCF to separate the presentation from the DB/Backend.MyPhotoGallery: MyPhotoGallery is a photo gallery developed in ASP.Net MVC.NuGet: NuGet is a free, open source developer focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development.OneCode CodeBox: OneCode CodeBoxonecode toolkit: toolsOrchard SSL: Orchard Secured Sockets Layer (SSL) adds new features to force the usage of SSL in sections like authentication pages or the dashboard.OrchardCMS - Lokalizacija: OrchardCMS - Lokalizacija je projekat lokalizacije Orchard CMS-a na srpski, hrvatski, srpskohrvatski, hrvatskosrpski i sve ostale jezike sa podrucija ex-YU. Pokušacemo da iskorisitmo slicnosti u jezicima kako bi jedni drugima pomogli i olakšali lokalizaciju Orchard-a. Pyxis Install Maker: This utility creates single file installs for Pyxis 2 applications.SaleCard: TestSharePoint Social Networking: A Collection of solutions aimed at adding social network to your SharePoint 2010 site. The collection will include web parts, ribbon extensions and other type of solutions that will add or enhance the social networking capabilities of SharePoint. The solution is written in c#.SmartScreenTerminator: Pissed off by the stupid "smart screen" asking you to "remember to protect your password" every time you click someone else's blog link in your Windows Live homepage? Use this three line appication to allow your IE to automatically navigate to the destination page.StreetScene: StreetScene is a sample project showing how to use Microsoft technologies such as ASP.NET, Azure and Silverlight to build rich applications.svmnetx: testtest_project: test projectTweet-Links: Tweet-Links is designed for ultra-fast sending a twitter selected text and files and images.WCMF - Windows Content Management Framework: WCMF is a framework that allows one to build CMS appllications that target the Windows platform (whereas a typical CMS system is usually web based). Used technologies are MEF, WCF, WPF (including Silverlight) and Caliburn.Micro.WebNoteAOP: A sample project for aspect oriented programming with PostSharp. The main purpose is a short introduction. All aspects are made in a very simple way. They should be useful for simple applications. Please keep in mind, that complex problems often require a complex solution, too.

    Read the article

  • CodePlex Daily Summary for Sunday, January 30, 2011

    CodePlex Daily Summary for Sunday, January 30, 2011Popular ReleasesWPF Application Framework (WAF): WPF Application Framework (WAF) 2.0.0.3: Version: 2.0.0.3 (Milestone 3): This release contains the source code of the WPF Application Framework (WAF) and the sample applications. Requirements .NET Framework 4.0 (The package contains a solution file for Visual Studio 2010) The unit test projects require Visual Studio 2010 Professional Remark The sample applications are using Microsoft’s IoC container MEF. However, the WPF Application Framework (WAF) doesn’t force you to use the same IoC container in your application. You can use ...Rawr: Rawr 4.0.17 Beta: Rawr is now web-based. The link to use Rawr4 is: http://elitistjerks.com/rawr.phpThis is the Cataclysm Beta Release. More details can be found at the following link http://rawr.codeplex.com/Thread/View.aspx?ThreadId=237262 and on the Version Notes page: http://rawr.codeplex.com/wikipage?title=VersionNotes As of the 4.0.16 release, you can now also begin using the new Downloadable WPF version of Rawr!This is a pre-alpha release of the WPF version, there are likely to be a lot of issues. If you...VivoSocial: VivoSocial 7.4.2: Version 7.4.2 of VivoSocial has been released. If you experienced any issues with the previous version, please update your modules to the 7.4.2 release and see if they persist. If you have any questions about this release, please post them in our Support forums. If you are experiencing a bug or would like to request a new feature, please submit it to our issue tracker. Web Controls * Updated Business Objects and added a new SQL Data Provider File. Groups * Fixed a security issue whe...PHP Manager for IIS: PHP Manager 1.1.1 for IIS 7: This is a minor release of PHP Manager for IIS 7. It contains all the functionality available in 56962 plus several bug fixes (see change list for more details). Also, this release includes Russian language support. SHA1 codes for the downloads are: PHPManagerForIIS-1.1.0-x86.msi - 6570B4A8AC8B5B776171C2BA0572C190F0900DE2 PHPManagerForIIS-1.1.0-x64.msi - 12EDE004EFEE57282EF11A8BAD1DC1ADFD66A654VFPX: VFP2C32 2.0.0.8 Release Candidate: This release includes several bugfixes, new functions and finally a CHM help file for the complete library.EnhSim: EnhSim 2.3.3 ALPHA: 2.3.3 ALPHAThis release supports WoW patch 4.06 at level 85 To use this release, you must have the Microsoft Visual C++ 2010 Redistributable Package installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=A7B7A05E-6DE6-4D3A-A423-37BF0912DB84 To use the GUI you must have the .NET 4.0 Framework installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992 - Added back in a p...DB>doc for Microsoft SQL Server: 1.0.0.0: Initial release Supported output HTML WikiPlex markup Raw XML Supported objects Tables Primary Keys Foreign Keys ViewsmojoPortal: 2.3.6.1: see release notes on mojoportal.com http://www.mojoportal.com/mojoportal-2361-released.aspx Note that we have separate deployment packages for .NET 3.5 and .NET 4.0 The deployment package downloads on this page are pre-compiled and ready for production deployment, they contain no C# source code. To download the source code see the Source Code Tab I recommend getting the latest source code using TortoiseHG, you can get the source code corresponding to this release here.Office Web.UI: Alpha preview: This is the first alpha release. Very exciting moment... This download is just the demo application : "Contoso backoffice Web App". No source included for the moment, just the app, for testing purposes and for feedbacks !! This package includes a set of official MS Office icons (143 png 16x16 and 132 png 32x32) to really make a great app ! Please rate and give feedback ThanksParallel Programming with Microsoft Visual C++: Drop 6 - Chapters 4 and 5: This is Drop 6. It includes: Drafts of the Preface, Introduction, Chapters 2-7, Appendix B & C and the glossary Sample code for chapters 2-7 and Appendix A & B. The new material we'd like feedback on is: Chapter 4 - Parallel Aggregation Chapter 5 - Futures The source code requires Visual Studio 2010 in order to run. There is a known bug in the A-Dash sample when the user attempts to cancel a parallel calculation. We are working to fix this.Catel - WPF and Silverlight MVVM library: 1.1: (+) Styles can now be changed dynamically, see Examples application for a how-to (+) ViewModelBase class now have a constructor that allows services injection (+) ViewModelBase services can now be configured by IoC (via Microsoft.Unity) (+) All ViewModelBase services now have a unit test implementation (+) Added IProcessService to run processes from a viewmodel with directly using the process class (which makes it easier to unit test view models) (*) If the HasErrors property of DataObjec...NodeXL: Network Overview, Discovery and Exploration for Excel: NodeXL Excel Template, version 1.0.1.160: The NodeXL Excel template displays a network graph using edge and vertex lists stored in an Excel 2007 or Excel 2010 workbook. What's NewThis release improves NodeXL's Twitter and Pajek features. See the Complete NodeXL Release History for details. Installation StepsFollow these steps to install and use the template: Download the Zip file. Unzip it into any folder. Use WinZip or a similar program, or just right-click the Zip file in Windows Explorer and select "Extract All." Close Ex...Kooboo CMS: Kooboo CMS 3.0 CTP: Files in this downloadkooboo_CMS.zip: The kooboo application files Content_DBProvider.zip: Additional content database implementation of MSSQL, RavenDB and SQLCE. Default is XML based database. To use them, copy the related dlls into web root bin folder and remove old content provider dlls. Content provider has the name like "Kooboo.CMS.Content.Persistence.SQLServer.dll" View_Engines.zip: Supports of Razor, webform and NVelocity view engine. Copy the dlls into web root bin folder to enable...UOB & ME: UOB ME 2.6: UOB ME 2.6????: ???? V1.0: ???? V1.0 ??Password Generator: 2.2: Parallel password generation Password strength calculation ( Same method used by Microsoft here : https://www.microsoft.com/protect/fraud/passwords/checker.aspx ) Minor code refactoringVisual Studio 2010 Architecture Tooling Guidance: Spanish - Architecture Guidance: Francisco Fagas http://geeks.ms/blogs/ffagas, Microsoft Most Valuable Professional (MVP), localized the Visual Studio 2010 Quick Reference Guidance for the Spanish communities, based on http://vsarchitectureguide.codeplex.com/releases/view/47828. Release Notes The guidance is available in a xps-only (default) or complete package. The complete package contains the files in xps, pdf and Office 2007 formats. 2011-01-24 Publish version 1.0 of the Spanish localized bits.ASP.NET MVC Project Awesome, jQuery Ajax helpers (controls): 1.6.2: A rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form, Popup and Pager the html generation has been optimized, the html page size is much smaller nowFacebook Graph Toolkit: Facebook Graph Toolkit 0.6: new Facebook Graph objects: Application, Page, Post, Comment Improved Intellisense documentation new Graph Api connections: albums, photos, posts, feed, home, friends JSON Toolkit upgraded to version 0.9 (beta release) with bug fixes and new features bug fixed: error when handling empty JSON arrays bug fixed: error when handling JSON array with square or large brackets in the message bug fixed: error when handling JSON obejcts with double quotation in the message bug fixed: erro...Microsoft All-In-One Code Framework: Visual Studio 2008 Code Samples 2011-01-23: Code samples for Visual Studio 2008New ProjectsAnaida - WebSocket Client/Adapter: Anaida is a WebSocket Client Library/Adapter. With 3 versions for Java, Silverlight and C#CutPasteAssign: Visual Studio extension to assist in the common refactoring of assigning parameters to local variables.Drori Photos: Photos of Drori the photographerD-Solution: App de D-SolutionEnigma Home Inventory: Most consumers do not have an itemized list of proof of ownership. Enigma Home Inventory may take the hassle out of arguing with the insurance companies. This project is aimed to be for a simple inventory program for end users who are not computer savvy.FastKnow: is a CMS & wikiFileSignatures: FileSignatures aims to create a class library that can identify the file format based on file contents. The project is written in C# 3.0, and can be used in .NET 3.5 and 4.0 projects.Genrsis: The aim of the Genrsis project is to be a suite of products that you can use to build things, starting with a workflow-based project management tool. Built in C#, it should be a one-stop place to get well-integrated products to get you up and running.MVC Demos: MVC 2 and MVC 3 examples with ajax and json.MVC Templates for DevExpress: Scaffolding templates for use in ASP.NET MVC 2 with DevExpress MVC Extensions for ASP.NET MVCPixel Replacer: The Pixel Replacer is a simple library for replacing pixel colors with a new color, by setting a filter rule.ReviewPal - The Code Review Companion for .Net.: ReviewPal, the Code Review Companion for .Net. This is an Add-In / Extension for Visual Studio 2008 & Visual Studio 2010. The aim of the Add-In / Extension is to do a source code review within the Visual Studio IDE where code makes more sense and most readable.SMVector3: Vector3 class implemented as float array or with SIMD instructions with the same interface so it is transparant whether you decide to use one version or another. You can also chance version during the life cycle of the projects.uRibbon - Office 2007 Ribbon control for VB.NET: Office 2007 ribbon control, with Orb and graphic transitions. After searching for many day looking for an Office 2007-like ribbon bar, I finally gave up and decided to write my own. It's in decent shape as-is. But anyone interested in helping me to continue the devlopment??vtcheck: This will read a target binary and check to see if it is detected by VirusTotal.Web Scheduled Task Framework: A simple set of classes intended to allow the standalone scheduling of tasks (arbitrary code to execute) on a .net website without requiring access to the operating system.WP7 codeproject app: A Windows Phone 7 app for browsing codeproject.com.zhongjh: ?????????,???????。???????????: ???????????

    Read the article

  • Combining MVVM Light Toolkit and Unity 2.0

    - by Alan Cordner
    This is more of a commentary than a question, though feedback would be nice. I have been tasked to create the user interface for a new project we are doing. We want to use WPF and I wanted to learn all of the modern UI design techniques available. Since I am fairly new to WPF I have been researching what is available. I think I have pretty much settled on using MVVM Light Toolkit (mainly because of its "Blendability" and the EventToCommand behavior!), but I wanted to incorporate IoC also. So, here is what I have come up with. I have modified the default ViewModelLocator class in a MVVM Light project to use a UnityContainer to handle dependency injections. Considering I didn't know what 90% of these terms meant 3 months ago, I think I'm on the right track. // Example of MVVM Light Toolkit ViewModelLocator class that implements Microsoft // Unity 2.0 Inversion of Control container to resolve ViewModel dependencies. using Microsoft.Practices.Unity; namespace MVVMLightUnityExample { public class ViewModelLocator { public static UnityContainer Container { get; set; } #region Constructors static ViewModelLocator() { if (Container == null) { Container = new UnityContainer(); // register all dependencies required by view models Container .RegisterType<IDialogService, ModalDialogService>(new ContainerControlledLifetimeManager()) .RegisterType<ILoggerService, LogFileService>(new ContainerControlledLifetimeManager()) ; } } /// <summary> /// Initializes a new instance of the ViewModelLocator class. /// </summary> public ViewModelLocator() { ////if (ViewModelBase.IsInDesignModeStatic) ////{ //// // Create design time view models ////} ////else ////{ //// // Create run time view models ////} CreateMain(); } #endregion #region MainViewModel private static MainViewModel _main; /// <summary> /// Gets the Main property. /// </summary> public static MainViewModel MainStatic { get { if (_main == null) { CreateMain(); } return _main; } } /// <summary> /// Gets the Main property. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public MainViewModel Main { get { return MainStatic; } } /// <summary> /// Provides a deterministic way to delete the Main property. /// </summary> public static void ClearMain() { _main.Cleanup(); _main = null; } /// <summary> /// Provides a deterministic way to create the Main property. /// </summary> public static void CreateMain() { if (_main == null) { // allow Unity to resolve the view model and hold onto reference _main = Container.Resolve<MainViewModel>(); } } #endregion #region OrderViewModel // property to hold the order number (injected into OrderViewModel() constructor when resolved) public static string OrderToView { get; set; } /// <summary> /// Gets the OrderViewModel property. /// </summary> public static OrderViewModel OrderViewModelStatic { get { // allow Unity to resolve the view model // do not keep local reference to the instance resolved because we need a new instance // each time - the corresponding View is a UserControl that can be used multiple times // within a single window/view // pass current value of OrderToView parameter to constructor! return Container.Resolve<OrderViewModel>(new ParameterOverride("orderNumber", OrderToView)); } } /// <summary> /// Gets the OrderViewModel property. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public OrderViewModel Order { get { return OrderViewModelStatic; } } #endregion /// <summary> /// Cleans up all the resources. /// </summary> public static void Cleanup() { ClearMain(); Container = null; } } } And the MainViewModel class showing dependency injection usage: using GalaSoft.MvvmLight; using Microsoft.Practices.Unity; namespace MVVMLightUnityExample { public class MainViewModel : ViewModelBase { private IDialogService _dialogs; private ILoggerService _logger; /// <summary> /// Initializes a new instance of the MainViewModel class. This default constructor calls the /// non-default constructor resolving the interfaces used by this view model. /// </summary> public MainViewModel() : this(ViewModelLocator.Container.Resolve<IDialogService>(), ViewModelLocator.Container.Resolve<ILoggerService>()) { if (IsInDesignMode) { // Code runs in Blend --> create design time data. } else { // Code runs "for real" } } /// <summary> /// Initializes a new instance of the MainViewModel class. /// Interfaces are automatically resolved by the IoC container. /// </summary> /// <param name="dialogs">Interface to dialog service</param> /// <param name="logger">Interface to logger service</param> public MainViewModel(IDialogService dialogs, ILoggerService logger) { _dialogs = dialogs; _logger = logger; if (IsInDesignMode) { // Code runs in Blend --> create design time data. _dialogs.ShowMessage("Running in design-time mode!", "Injection Constructor", DialogButton.OK, DialogImage.Information); _logger.WriteLine("Running in design-time mode!"); } else { // Code runs "for real" _dialogs.ShowMessage("Running in run-time mode!", "Injection Constructor", DialogButton.OK, DialogImage.Information); _logger.WriteLine("Running in run-time mode!"); } } public override void Cleanup() { // Clean up if needed _dialogs = null; _logger = null; base.Cleanup(); } } } And the OrderViewModel class: using GalaSoft.MvvmLight; using Microsoft.Practices.Unity; namespace MVVMLightUnityExample { /// <summary> /// This class contains properties that a View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm/getstarted /// </para> /// </summary> public class OrderViewModel : ViewModelBase { private const string testOrderNumber = "123456"; private Order _order; /// <summary> /// Initializes a new instance of the OrderViewModel class. /// </summary> public OrderViewModel() : this(testOrderNumber) { } /// <summary> /// Initializes a new instance of the OrderViewModel class. /// </summary> public OrderViewModel(string orderNumber) { if (IsInDesignMode) { // Code runs in Blend --> create design time data. _order = new Order(orderNumber, "My Company", "Our Address"); } else { _order = GetOrder(orderNumber); } } public override void Cleanup() { // Clean own resources if needed _order = null; base.Cleanup(); } } } And the code that could be used to display an order view for a specific order: public void ShowOrder(string orderNumber) { // pass the order number to show to ViewModelLocator to be injected //into the constructor of the OrderViewModel instance ViewModelLocator.OrderToShow = orderNumber; View.OrderView orderView = new View.OrderView(); } These examples have been stripped down to show only the IoC ideas. It took a lot of trial and error, searching the internet for examples, and finding out that the Unity 2.0 documentation is lacking (at best) to come up with this solution. Let me know if you think it could be improved.

    Read the article

  • Silverlight Recruiting Application Part 4 - Navigation and Modules

    After our brief intermission (and the craziness of Q1 2010 release week), we're back on track here and today we get to dive into how we are going to navigate through our applications as well as how to set up our modules. That way, as I start adding the functionality- adding Jobs and Applicants, Interview Scheduling, and finally a handy Dashboard- you'll see how everything is communicating back and forth. This is all leading up to an eventual webinar, in which I'll dive into this process and give a honest look at the current story for MVVM vs. Code-Behind applications. (For a look at the future with SL4 and a little thing called MEF, check out what Ross is doing over at his blog!) Preamble... Before getting into really talking about this app, I've done a little bit of work ahead of time to create a ton of files that I'll need. Since the webinar is going to cover the Dashboard, it's not here, but otherwise this is a look at what the project layout looks like (and remember, this is both projects since they share the .Web): So as you can see, from an architecture perspective, the code-behind app is much smaller and more streamlined- aka a better fit for the one man shop that is me. Each module in the MVVM app has the same setup, which is the Module class and corresponding Views and ViewModels. Since the code-behind app doesn't need a go-between project like Infrastructure, each MVVM module is instead replaced by a single Silverlight UserControl which will contain all the logic for each respective bit of functionality. My Very First Module Navigation is going to be key to my application, so I figured the first thing I would setup is my MenuModule. First step here is creating a Silverlight Class Library named MenuModule, creatingthe View and ViewModel folders, and adding the MenuModule.cs class to handle module loading. The most important thing here is that my MenuModule inherits from IModule, which runs an Initialize on each module as it is created that, in my case, adds the views to the correct regions. Here's the MenuModule.cs code: public class MenuModule : IModule { private readonly IRegionManager regionManager; private readonly IUnityContainer container; public MenuModule(IUnityContainer container, IRegionManager regionmanager) { this.container = container; this.regionManager = regionmanager; } public void Initialize() { var addMenuView = container.Resolve<MenuView>(); regionManager.Regions["MenuRegion"].Add(addMenuView); } } Pretty straightforward here... We inject a container and region manager from Prism/Unity, then upon initialization we grab the view (out of our Views folder) and add it to the region it needs to live in. Simple, right? When the MenuView is created, the only thing in the code-behind is a reference to the set the MenuViewModel as the DataContext. I'd like to achieve MVVM nirvana and have zero code-behind by placing the viewmodel in the XAML, but for the reasons listed further below I can't. Navigation - MVVM Since navigation isn't the biggest concern in putting this whole thing together, I'm using the Button control to handle different options for loading up views/modules. There is another reason for this- out of the box, Prism has command support for buttons, which is one less custom command I had to work up for the functionality I would need. This comes from the Microsoft.Practices.Composite.Presentation assembly and looks as follows when put in code: <Button x:Name="xGoToJobs" Style="{StaticResource menuStyle}" Content="Jobs" cal:Click.Command="{Binding GoModule}" cal:Click.CommandParameter="JobPostingsView" /> For quick reference, 'menuStyle' is just taking care of margins and spacing, otherwise it looks, feels, and functions like everyone's favorite Button. What MVVM's this up is that the Click.Command is tying to a DelegateCommand (also coming fromPrism) on the backend. This setup allows you to tie user interaction to a command you setup in your viewmodel, which replaces the standard event-based setup you'd see in the code-behind app. Due to databinding magic, it all just works. When we get looking at the DelegateCommand in code, it ends up like this: public class MenuViewModel : ViewModelBase { private readonly IRegionManager regionManager; public DelegateCommand<object> GoModule { get; set; } public MenuViewModel(IRegionManager regionmanager) { this.regionManager = regionmanager; this.GoModule = new DelegateCommand<object>(this.goToView); } public void goToView(object obj) { MakeMeActive(this.regionManager, "MainRegion", obj.ToString()); } } Another for reference, ViewModelBase takes care of iNotifyPropertyChanged and MakeMeActive, which switches views in the MainRegion based on the parameters. So our public DelegateCommand GoModule ties to our command on the view, that in turn calls goToView, and the parameter on the button is the name of the view (which we pass with obj.ToString()) to activate. And how do the views get the names I can pass as a string? When I called regionManager.Regions[regionname].Add(view), there is an overload that allows for .Add(view, "viewname"), with viewname being what I use to activate views. You'll see that in action next installment, just wanted to clarify how that works. With this setup, I create two more buttons in my MenuView and the MenuModule is good to go. Last step is to make sure my MenuModule loads in my Bootstrapper: protected override IModuleCatalog GetModuleCatalog() { ModuleCatalog catalog = new ModuleCatalog(); // add modules here catalog.AddModule(typeof(MenuModule.MenuModule)); return catalog; } Clean, simple, MVVM-delicious. Navigation - Code-Behind Keeping with the history of significantly shorter code-behind sections of this series, Navigation will be no different. I promise. As I explained in a prior post, due to the one-project setup I don't have to worry about the same concerns so my menu is part of MainPage.xaml. So I can cheese-it a bit, though, since I've already got three buttons all set I'm just copying that code and adding three click-events instead of the command/commandparameter setup: <!-- Menu Region --> <StackPanel Grid.Row="1" Orientation="Vertical"> <Button x:Name="xJobsButton" Content="Jobs" Style="{StaticResource menuStyleCB}" Click="xJobsButton_Click" /> <Button x:Name="xApplicantsButton" Content="Applicants" Style="{StaticResource menuStyleCB}" Click="xApplicantsButton_Click" /> <Button x:Name="xSchedulingModule" Content="Scheduling" Style="{StaticResource menuStyleCB}" Click="xSchedulingModule_Click" /> </StackPanel> Simple, easy to use events, and no extra assemblies required! Since the code for loading each view will be similar, we'll focus on JobsView for now.The code-behind with this setup looks something like... private JobsView _jobsView; public MainPage() { InitializeComponent(); } private void xJobsButton_Click(object sender, RoutedEventArgs e) { if (MainRegion.Content.GetType() != typeof(JobsView)) { if (_jobsView == null) _jobsView = new JobsView(); MainRegion.Content = _jobsView; } } What am I doing here? First, for each 'view' I create a private reference which MainPage will hold on to. This allows for a little bit of state-maintenance when switching views. When a button is clicked, first we make sure the 'view' typeisn't active (why load it again if it is already at center stage?), then we check if the view has been created and create if necessary, then load it up. Three steps to switching views and is easy as pie. Part 4 Results The end result of all this is that I now have a menu module (MVVM) and a menu section (code-behind) that load their respective views. Since I'm using the same exact XAML (except with commands/events depending on the project), the end result for both is again exactly the same and I'll show a slightly larger image to show it off: Next time, we add the Jobs Module and wire up RadGridView and a separate edit page to handle adding and editing new jobs. That's when things get fun. And somewhere down the line, I'll make the menu look slicker. :) Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How do you mock ViewModel Commands using moq?

    - by devnet247
    Hi I might be approaching this all wrong.But please help me to understand. I really want to TDD building wpf application using Moq. I would like to mock the viewmodel. Application Show a list of contacts and when you double click on a contact it shows the contact. Test Moq GetContactsCommand.Test it has been called. Test that you get a list of contacts. Not sure how to mock the viewModel and it's commands can you correct me? So I have started to do the following [Test] public void Should_be_able_to_mock_getContactsCommand_and_get_a_list_of_contacts() { //Arrange var expectedContacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; var mock = new Mock<IContactListViewModel>(); mock.SetupGet(x => x.GetContactsCommand).Verifiable(); mock.SetupGet(x => x.Contacts).Returns(expectedContacts); //Act //? //assert mock.VerifySet(x => x.Contacts, Times.AtLeastOnce()); mock.Object.Contacts.Count.ShouldEqual(expectedContacts.Count); } public interface IContactListViewModel { ObservableCollection<ContactViewModel> Contacts { get; set; } ICommand GetContactsCommand{ get; } } public interface IContactModel { string FirstName { get; set; } string LastName { get; set; } string Email { get; set; } } public class ContactModel : IContactModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } public class ContactViewModel : ViewModelBase { private readonly ContactModel _contactModel; public ContactViewModel(ContactModel contactModel) { _contactModel = contactModel; } public string FirstName { get { return _contactModel.FirstName; } set { _contactModel.FirstName = value; OnPropertyChanged("FirstName"); } } public string LastName { get { return _contactModel.LastName; } set { _contactModel.LastName = value; OnPropertyChanged("LastName"); } } public string Email { get { return _contactModel.Emai; } set { _contactModel.Email = value; OnPropertyChanged("Email"); } } } public class ContactListViewModel : ViewModelBase, IContactListViewModel { private ObservableCollection<ContactViewModel> _contacts; public ObservableCollection<ContactViewModel> Contacts { get { return _contacts; } set { _contacts = value; OnPropertyChanged("Contacts"); } } private RelayCommand _getContactsCommand; public ICommand GetContactsCommand { get { return _getContactsCommand ?? (_getContactsCommand = new RelayCommand(x => GetContacts(), x => CanGetContacts)); } } private static bool CanGetContacts { get { return true; } } private void GetContacts() { //pretend we are going to the service or db whatever Contacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; } }

    Read the article

1 2 3  | Next Page >