Issue with import in MEF MVVM Silverlight 4 - silverlight-4.0

I am using MEF, MVVM and Silverlight4 and below is my code
Main.cs:
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Diagnostics;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
public partial class Main : UserControl
{
public Main()
{
InitializeComponent();
// Satisfy the MEF imports for the class.
if (!DesignerProperties.IsInDesignTool)
{
CompositionInitializer.SatisfyImports(this);
}
}
/// <summary>
/// Sets the datacontext to the viewmodel for this view
/// </summary>
[Import(ViewModelTypes.MainViewModel)]
public object ViewModel
{
set
{
this.DataContext = value;
}
}
}
Viewmodel:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows.Input;
[Export(ViewModelTypes.MainViewModel)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MainViewModel : ViewModelBase
{
[ImportingConstructor]
public MainViewModel(IAuthenticationModel authModel, IprospectManagementModel managementModel)
{
this.authenticationModel = authModel;
this.managementModel = managementModel;
}
/// <summary>
/// The authentication model.
/// </summary>
private IAuthenticationModel authenticationModel;
/// <summary>
/// The Iprospect management model.
/// </summary>
private IprospectManagementModel managementModel;
}
Below is the error i am getting, Please do help me out trace the same.
The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) No valid exports were found that match the constraint '(exportDefinition.ContractName == "MainViewModel")', invalid exports may have been rejected.
Resulting in:
Cannot set import 'IProspectCommonApp.Client.Main.ViewModel (ContractName="MainViewModel")' on part 'IProspectCommonApp.Client.Main'.
Element: IProspectCommonApp.Client.Main.ViewModel (ContractName="MainViewModel") --> IProspectCommonApp.Client.Main

It is probably failing because there is no IAuthenticationModel and/or IprospectManagementModel exported. The MainViewModel imports these via the ImportingConstructor, so it can't be created if they haven't been exported.
For more information on MEF debugging, see How to Debug and Diagnose MEF Failures.

Related

Load VSPackage with dynamic items did not load on startup

I have a Visual Studio Package where items are dynamically added to the menu bar. However, only the fixed entries are shown because the extension is not loaded correctly.
The package is only loaded when you click on a fixed entry. But it should be loaded at the start of the studio.
I tried everything with ProvideAutoLoad, the dynamic items are not shown. I don't know why. What is the problem ?
I hope someone can help me here
thx
[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string, PackageAutoLoadFlags.BackgroundLoad)]
should be enough to automatically load a package on Visual Studio startup.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.Windows.Forms;
namespace VSIXOpenSCE
{
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // Info on this package for Help/About
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(MenuControlPackage.PackageGuidString)]
[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class MenuControlPackage : Package
{
public const string PackageGuidString = "f5c6cb4a-bb86-48e4-92e6-f0ee6de2de3a";
public MenuControlPackage()
{
// Inside this method you can place any initialization code that does not require
// any Visual Studio service because at this point the package object is created but
// not sited yet inside Visual Studio environment. The place to do all the other
// initialization is the Initialize method.
}
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
protected override void Initialize()
{
base.Initialize();
MenuControl.Initialize(this);
}
#endregion
}
}

Prism4: Creating catalog from xaml CreateFromXaml doesn't compile

I'm developing with Silverlight 4 and Prism 4.
I'm also using Unity as my injection container.
I'm trying to create the module catalog from xaml, but I get this error "IModuleCatalog does not contain a definition of CreateFromXaml...".
My code snippet is:
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Prism.UnityExtensions;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.MefExtensions;
namespace MyModularityProject {
public class MyBootStrapper : UnityBootstrapper {
protected override DependencyObject CreateShell() {
return ServiceLocator.Current.GetInstance<Shell>();
}
protected override void InitializeShell() {
base.InitializeShell();
Application.Current.RootVisual = (UIElement)Shell;
}
protected override IModuleCatalog CreateModuleCatalog() {
// This is the isntruction that doesn't compile
return ModuleCatalog.CreateFromXaml(new
Uri("/MyProject.Silverlight;component/ModulesCatalog.xaml",
UriKind.Relative));
}
}
}
What could I be missing here?
The reason that you need to add the full path to the ModuleCatalog type is that there is a ModuleCatalog property within the Bootstrapper base class that UnityBootstrapper inherits. If you don't qualify the name, you are essentially calling an accessor on a property which returns IModuleCatalog. The interface definition does not include this function.

Singleton Data Access Object (Dao) & SQL Helper Instance, Is here any Performance drawback?

I need comments from Experts. I write my own SQL Helper Class to Communicate with DB.
Why I use it as because I try to
Encapsulate the Ado.Net logic.
Try to set a common standard for my developer in terms of DAL coding.
Flexible & Easy to use.
Same kind of code block for SQL Server/ Oracle / Access / Excel / Generic Database code block approach (SQL Server & Oracle) e.t.c.
Plug & Play or Reusable approach.
In terms of code optimization
This helper class or Assembly is CLS Compliant.
It pass Successfully by FxCop / Static Code Analysis.
I give you the sample Code Block (DAO). Please check bellow
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
#region include SQL Helper Namespace
using DBManager;
#endregion
#region include SQL Helper Namespace
using DBManager;
#endregion
namespace ContentManagementSystem.DataAccessLayer
{
/// <summary>
///
/// </summary>
public sealed class DaoContentOwner : DataAccessBase
{
#region CONSTRUCTOR
/// <summary>
///
/// </summary>
private DaoContentOwner()
{
GetInstance = new DaoContentOwner();
}
#endregion
//############################################# M E T H O D S ##########################
#region Retrieve Content Owner
/// <summary>
/// Retrieve Content Owner
/// </summary>
/// <returns></returns>
public static DataTable RetrieveContentOwner()
{
DataTable dt = null;
try
{
using (DBQuery dq = new DBQuery("stpGetContentOwner"))
{
dt = dq.ResultSetAsDataTable();
return dt;
}
}
catch (Exception)
{
throw;
}
finally
{
if (dt != null)
{
dt.Dispose();
}
}
}
#endregion
//############################################# P R O P E R T Y ########################
#region READ ONLY PROPERTY
/// <summary>
/// GetInstance of DaoContentOwner Class
/// </summary>
public static DaoContentOwner GetInstance { get; private set; }
#endregion
}
}
Justification:
"DataAccessBase" It is a Abstract class. Implement IDisposable Interface.
"DBQuery" is SQL Helper for SQL Server Only. It is a Sealed class. It is takes T-SQL / SP according to needs. Open an close database connection. No need to handel any thing by developer.
Why I make DAO Singleton Class, Because my all the methods withing DAO is a static method. I order to memory optimization I make it Singleton. It is also a design Principal.
Note: Needs comments. Whether need to change in the design or some thing is wrong that need to correct.
Personally I would go with:
DALFileItem dalF = new DALFileItem(DSN);
List<FileItem> list = dalF.GetAll("");
Allows accessing multiple databases, without making DSN static member.
In multithreaded environment only one thread will have access to the static method.
More object oriented: you can add interfaces, base classes and generics easier that way.

Does this MSDN article violate MVVM?

This may be old news but back in March 2009, this article, “Model-View-ViewModel In Silverlight 2 Apps,” has a code sample that includes DataServiceEntityBase:
// COPIED FROM SILVERLIGHTCONTRIB Project for simplicity
/// <summary>
/// Base class for DataService Data Contract classes to implement
/// base functionality that is needed like INotifyPropertyChanged.
/// Add the base class in the partial class to add the implementation.
/// </summary>
public abstract class DataServiceEntityBase : INotifyPropertyChanged
{
/// <summary>
/// The handler for the registrants of the interface's event
/// </summary>
PropertyChangedEventHandler _propertyChangedHandler;
/// <summary>
/// Allow inheritors to fire the event more simply.
/// </summary>
/// <param name="propertyName"></param>
protected void FirePropertyChanged(string propertyName)
{
if (_propertyChangedHandler != null)
{
_propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
#region INotifyPropertyChanged Members
/// <summary>
/// The interface used to notify changes on the entity.
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
_propertyChangedHandler += value;
}
remove
{
_propertyChangedHandler -= value;
}
}
#endregion
What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons Why would we go this way: what we can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework):
// Partial Method to support the INotifyPropertyChanged interface
public partial class Game : DataServiceEntityBase
{
#region Partial Method INotifyPropertyChanged Implementation
// Override the Changed partial methods to implement the
// INotifyPropertyChanged interface
// This helps with the Model implementation to be a mostly
// DataBound implementation
partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); }
partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); }
partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); }
partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); }
partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); }
partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); }
partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); }
partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); }
partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); }
partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); }
partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); }
partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); }
partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); }
partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); }
partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); }
#endregion
}
Of course MSDN code can seen as “toy code” for educational purposes but is anyone doing anything like this in the real world of Silverlight development?
In order to make a View entirely independent of the Model you would need to reproduce types that in many cases are identical to the Model types in your ViewModel.
Example
A Model contains a Person type that have FirstName and LastName properties. The visual design calls for a "List of people" so there is a View containing a ListBox that has a data template binding to property paths of FirstName and LastName. The ItemsSource binds to a property of ViewModel that exposes a set instances of types that have a FirstName and LastName property.
So here is the question, should there be a "ViewModel version" of the Model Person type or should the ViewModel simply re-use the existing Person type from the Model?
In either case its quite possible that you would want the properties to be observable.
To consider
What are the objectives behind MVVM? Quite often we like to present nice long lists of why a pattern exists but in this case there are really only 2.
Separate visual design (note: not design) from code.
Maximise the testable surface of the overall application.
Exposing Model types on the ViewModel doesn't form an obstacle to either of the above objectives. In fact it aids testability since the number of types and members that need testing is reduced.
In my opinion I don't see that implementing INotifyPropertyChanged implies binding to visuals. There may be other reasons why some service may want to observe changes in properties of a model object.
The key principle in the separation of Model from View is hiding of any specifics about the how the View presents the Model from the Model itself. Adding a ForenameBackColor property to the Model would be probably be bad. This is where the ViewModel comes in.
Bottom Line
Requiring the Model to expose observable properties is not breach of MVVM, its a simple and general requirement that does not require the Model to have any specific knowledge of any View or indeed that there are any "visuals" involved at all.
No, looks fine to me - DataServiceEntityBase is just the name of his base class which all his DTO's/business objects inherit from, nothing wrong with that setup (did that name throw you a little?). If he is putting his data in a ViewModel and then binding his View to the VM then you at least have the VVM part of MVVM.
The main thing i would be upset about is his naming of the FirePropertyChanged method - personally i would have called it OnPropertyChanged.

How to get full intellisense tooltip comments working?

I've got some C++/CLI software which is all nice and documented in a C#'ish kind of way which means DOxygen is able to pull it out into some nice html. Is there any way I can get that same information to appear in the intellisense tool tips the way that the .net framework does?
For example, lets say this is my header file (MyApp.h):
/*************** MyApp.h ***************/
/// My namespace containing all my funky classes
namespace MyNamespace
{
using namespace System;
ref class WorldHunger;
/// A truly elegent class which solves all the worlds problems
public ref class MyClass
{
public:
/// Constructs a MyClass
MyClass()
{
}
/// <summary>Attempts to fix world hunger</summary>
/// <param name="problem">The problem to try and fix</param>
/// <returns>Whether or not the problem was solved</param>
bool FixWorldHunger( WorldHunger^ problem );
};
}
...and this it's corresponding implementation:
/*************** MyApp.cpp ***************/
#include "MyApp.h"
using namespace MyNamespace;
MyClass::MyClass()
{
}
bool MyClass::FixWorldHunger( WorldHunger^ problem )
{
bool result = false;
/// TODO: implement something clever
return result;
}
Here's what intellisense does for built in functions when I'm typing:
http://www.geekops.co.uk/photos/0000-00-02%20%28Forum%20images%29/BrokenIntellisense1.jpg
Here's what intellisense does for my own functions when I type:
http://www.geekops.co.uk/photos/0000-00-02%20%28Forum%20images%29/BrokenIntellisense2.jpg
Surely there's a way to do this?
Just to summarise, for this to work you need your comments in a compatible form:
/// <summary>
/// Retrieves the widget at the specified index
/// </summary>
/// <param name="widgetIndex">Index of the widget to retrieve.</param>
/// <returns>The widget at the specified index</returns>
Widget* GetWidget(int widgetIndex);
Then you simply right-click on the project in Visual Studio and go to properties > configuration properties > C/C++ > Output Files and change Generate XML Documentation Files to Yes.
When you rebuild your project ad import it somewhere else, you should see fully documented tooltips appear.