Unable to load module from Modulecatalog.xaml file - silverlight

Thanks in advance.
I am trying to load modules from XAML file but not able to go through, my xaml file is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Modularity:ModuleCatalog
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:Modularity="clr-namespace:Microsoft.Practices.Composite.Modularity;assembly=Microsoft.Practices.Composite">
<Modularity:ModuleInfo
Ref="ModuleAproject.xap"
ModuleName="ModuleA"
ModuleType="ModuleAproject.ModuleA,ModuleAproject,Version=1.0.0.0">
</Modularity:ModuleInfo>
<Modularity:ModuleInfo
Ref="ModuleBProject.xap"
ModuleName="ModuleB"
ModuleType="ModuleBProject.ModuleB,ModuleBproject,Version=1.0.0.0">
<Modularity:ModuleInfo.DependsOn>
<sys:String>ModuleA</sys:String>
</Modularity:ModuleInfo.DependsOn>
</Modularity:ModuleInfo>
<Modularity:ModuleInfo
Ref="MyDemoApplication.xap"
ModuleName="MainModule"
ModuleType="MyDemoApplication.MainModule,MyDemoApplication,Version=1.0.0.0">
<Modularity:ModuleInfo.DependsOn>
<sys:String>ModuleB</sys:String>
</Modularity:ModuleInfo.DependsOn>
</Modularity:ModuleInfo>
</Modularity:ModuleCatalog>
The exception which it is throwing is :
System.Windows.Markup.XamlParseException was caught
Message=Cannot add content to an object of type 'Microsoft.Practices.Composite.Modularity.ModuleInfo'. [Line: 12 Position: 27]
LineNumber=12
LinePosition=27
StackTrace:
at MS.Internal.XcpImports.CreateFromXaml(String xamlString, Boolean createNamescope, Boolean requireDefaultNamespace, Boolean allowEventHandlers, Boolean expandTemplatesDuringParse)
at MS.Internal.XcpImports.CreateFromXaml(String xamlString, Boolean createNamescope, Boolean requireDefaultNamespace, Boolean allowEventHandlers)
at System.Windows.Markup.XamlReader.Load(String xaml)
at Microsoft.Practices.Composite.Modularity.ModuleCatalog.CreateFromXaml(Stream xamlStream)
at Microsoft.Practices.Composite.Modularity.ModuleCatalog.CreateFromXaml(Uri builderResourceUri)
at MyDemoApplication.MyBootStrapper.GetModuleCatalog()
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.ConfigureContainer()
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.Run(Boolean runWithDefaultConfiguration)
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.Run()
at MyDemoApplication.App.Application_Startup(Object sender, StartupEventArgs e)
Any help on this is very much appreciated.
I am using Prism 2.2 and Silverlight 4.0 for development

I have not used Silverlight in a long time, but just quickly looking at your code, I think you have the following wrong
assembly=Microsoft.Practices.Composite
I believe that in my Silverlight projects I used the following
assembly=Microsoft.Practices.Prism
that is for the modularity namespace.
If this is not correct, just let me know and I will gladly help further.

Related

Must add reference to WindowsBase.dll to use RenderTargetBitmap.Render method?

I'm currently working on a WPF application that uses a plotting library called Live Charts for WPF. I want to save a PNG of my graph, which is described on their github page Save Plot Example also discussed at this stackoverflow question here. The problem is adding a reference to the windows base assembly.
`
private void SaveToPng(FrameworkElement visual, string filename)
{
var encoder = new PngBitmapEncoder();
EncodeVisual(visual, filename, encoder);
}
private static void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
var bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
//bitmap.Render();
bitmap.Render(visual);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName)) encoder.Save(stream);
}
`
I have tried to add this dll as a reference which is located at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0, but when I do this it does not work. It is actually implicitly included in the project, so that may be why I can add it explicitly like I did with the PresentationCore.dll and PresentationFramework.dll which were also required and solved a few errors. The error states: the type 'System.Windows.Freezable' is defined in an assembly that is not referenced. You must add a reference to assembly 'WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. This is shown by hovering over the call to bitmap.Render(visual), and when hovering over encoder.Save(stream) as shown in the picture and in the above code. I believe resolving this dependency would fix the problem, but I cannot figure out how. Thank you.
Picture of Project
Discovered what I believe is the answer to the problem. I was creating the SaveToPNG and EncodeVisual methods inside of a class library which would be used in the WPF project. The class library is unable to accept WindowsBase as an explicit reference, but the WPF project itself can. It will take some restructuring of the code to implement this in the WPF project itself, but it seems to be the way to resolve this problem.
I am using .NET 6. Here is the contents of my csproj file in my class library:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
<ItemGroup>
<Compile Update="Core Library\Port.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
</Project>
I did not see the attributes that you spoke of, and autocomplete could not reference them in this file. Inside of the IDE (Rider) I was able to target net6.0-windows in the properties menu of the project. I then reinserted the code into the class library, but the same error still occurred. I agree with you that it shouldn't be necessary to reference WindowsBase, which isn't necessary when placing the code in the wpf project itself, but in the class library I also had to reference PresentationCore and PresentationFramework, which did take care of multiple errors.

Resource Dictionary error during Silverlight app initialisation

I've got a problem with a Silverlight application. It has been working and I haven't changed the code, but I have changed a few other things such as upgrading to VS2012. I thought all was well with the project post upgrade but have now run in to trouble.
When the application starts it throws an exception during the InitializeComponent call. It looks like the problem is with the ResourceDictionary, specifically I notice this in the inner exception:
InnerException: System.Collections.Generic.KeyNotFoundException
Which makes me think it's trying to set a property and can't find the key it's looking for in the ResourceDictionary. I've been tearing my hair out trying to discover how to determine what key it's looking for, can anyone suggest a debugging technique to do this?
The full details of the exception are:
System.Windows.Markup.XamlParseException occurred Message=Set
property 'System.Windows.FrameworkElement.Style' threw an exception.
[Line: 228 Position: 64] LineNumber=228 LinePosition=64
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at MyApp.Silverlight.MainPage.InitializeComponent()
at MyApp.Silverlight.MainPage..ctor() InnerException: System.Windows.Markup.XamlParseException
Message=Failed to assign to property 'System.Windows.ResourceDictionary.Source'. [Line: 5 Position: 36]
LineNumber=5
LinePosition=36
StackTrace:
at MS.Internal.XcpImports.CreateFromXaml(UnmanagedMemoryStream stream,
String sourceAssemblyName, Boolean createNamescope, Boolean
requireDefaultNamespace, Boolean allowEventHandlers, String
xamlResourceUriString, Boolean isBinaryContent)
at System.Windows.Controls.Control.GetBuiltInStyle(IntPtr nativeTarget, IntPtr& nativeStyle)
InnerException: System.Collections.Generic.KeyNotFoundException
Message=The given key was not present in the dictionary.
StackTrace:
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Windows.ResourceManagerWrapper.GetResourceForUri(Uri xamlUri,
Type componentType)
InnerException:
Thanks very much for reading and if you have any suggestions I'll be very grateful.

Random InvalidOperationException on application startup

I am experiencing a problem at application startup from time to time on production machines. It doesn't happen every time the application starts, and apparently it only happens on reboot. The application is started from login, added to HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run.
Apparently, the problem is more frequent when resetting the machine, than during a reboot. Starting the application manually after it crashes is successful.
The following exception is thrown during startup:
Initialization of 'System.Windows.Controls.TextBlock' threw an exception.
System.Windows.Markup.XamlParseException: Initialization of 'System.Windows.Controls.TextBlock' threw an exception. ---> System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it.
at System.Windows.Threading.Dispatcher.VerifyAccess()
at System.Windows.Style.Seal()
at System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe,FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache)
at System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.Controls.TextBlock.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp)
at System.Windows.FrameworkElement.UpdateStyleProperty()
at System.Windows.FrameworkElement.OnInitialized(EventArgs e)
at System.Windows.FrameworkElement.TryFireInitialized()
at System.Windows.FrameworkElement.EndInit()
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)
--- End of inner exception stack trace ---
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at Exception.Occurs.At.Different.Origins.Between.Startup()
As seen from the StackTrace, there is something going on while updating style cache. I haven't been able to reproduce this on my own computer. There are no threads involved here while starting the application, but there are a few AppDomains. The origin of the exception is not always the same, but it is exactly the same from Application.LoadComponent(Object component, Uri resourceLocator)
Because our application needs to find the configuration file from a different location than the executable (..\ProgramData....) depending on the OS, we use a separate AppDomain where we instruct it where to look for the configuration file, as we could not find any better solution of telling ConfigurationManager where to look for the file. It could of course, be related to this, though not necessarily. EDIT: ConfigurationManager.OpenMappedExeConfiguration Doesn't seem to work, as it won't refresh any user or application settings accessed through Properties.Settings.Default, etc.
Does anyone have any suggestions or recommendations on how to deal with this? Sorry I am not able to provide you with a sample to reproduce with.
That exception was because you are modifying a visual element from a thread that is not the visual one. I know this because in the first line of your exception it said:
Initialization of 'System.Windows.Controls.TextBlock' threw an exception. System.Windows.Markup.XamlParseException: Initialization of 'System.Windows.Controls.TextBlock' threw an exception. ---> System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it.
All the rest of the exception doesn't matter. I think it is when you are loading the initial configuration, then you use other thread. The random behavior could be that some time you find the configuration before the TextBlock control is loaded, so this times the exception will no be thrown.
To solve this please take a look to this question, and the last answer that I give (the one that use the SynchronizationContext, that really works with WPF application that use several threads). If is not clear comment and I will write the solution here.
Hope this answer helps to find that random error, its are the worsts...
I'm not sure what is causing this exception but I there is a workaround to your problem.
Instead of creating a separate AppDomain just for loading a different configuration file, you could use ConfigurationManager.OpenMappedExeConfiguration which allows you to load any .config file from anywhere in your local file system.
You use it like this:
//Map the new configuration file.
var configFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = #"c:\myOther.config"};
//Get the mapped configuration file
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
Use config.GetSection() to get specific sections for read-only use or directly the config object to change the configuration at run-time.
And you will not need the different AppDomain which will mean faster startup time :)
Getting rid of the extra AppDomain used to specify configuration file, and replacing it with the method specified in this link took care of the problem.

Silverlight 4: How to reference class from another assembly

In XAML-file of the SquadView page (VfmElitaSilverlightClientView.Pages.SquadView) I am using custom value converter. XAML-file is in "VfmElitaSilverlightClientView" namespace. Separate folder was created for converter and it is in "VfmElitaSilverlightClientView.Converter" namespace (in the same assembly). To use converter following code is used in XAML:
xmlns:Converter="clr-namespace:VfmElitaSilverlightClientView.Converter"
...
<NavigationControls:Page.Resources>
<Converter:BooleanToVisibilityConverter x:Key="resourceBooleanToVisibilityConverter" />
</NavigationControls:Page.Resources>
All works fine. Here I want to move converter class into a custom separate assembly "SilverlightCommonView" and class himself will be in "SilverlightCommonView.Converter" namespace. The XAML code is changed to the following:
xmlns:Converter="clr-namespace:SilverlightCommonView.Converter;assembly=SilverlightCommonView"
...
<NavigationControls:Page.Resources>
<Converter:BooleanToVisibilityConverter x:Key="resourceBooleanToVisibilityConverter" />
</NavigationControls:Page.Resources>
In this case when application throws following exception:
An unhandled exception ('Unhandled
Error in Silverlight Application...
Code: 4004 Category:
ManagedRuntimeError Message:
Microsoft.Practices.Unity.ResolutionFailedException:
Resolution of dependency failed, type="VfmElitaSilverlightClientView.Pages.SquadView",
name="(none)".
Exception occurred while: Calling constructor
VfmElitaSilverlightClientView.Pages.SquadView(). Exception is: XamlParseException -
The type 'BooleanToVisibilityConverter' was not found because
'cl...:SilverlightCommonView.Converter;assembly=SilverlightCommonView'
is an unknown namespace.
It's unclear why specified namespace is unknown (those assembly is referenced by the current one).
Please advise.
Any thoughts are welcome.
I'd bet you do not have an assembly reference to your shared/common project from your application project.

Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'

In which situation following error occurs?
Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'.
UPDATE:
I got this error message while binding MyType.FindAllByProperty("col1", "foo"); to a GridView (exactly a Telerik's one: RadGrid). This error is not occuring every time, just sometimes. Here is markup of my grid:
<telerik:RadGrid ID="grdList" runat="server" AutoGenerateColumns="false" OnNeedDataSource="grdList_NeedDataSource"
OnUpdateCommand="grdList_UpdateCommand" AllowAutomaticUpdates="True" OnItemUpdated="grdList_ItemUpdated"
AllowMultiRowEdit="true">
<MasterTableView EditMode="InPlace" DataKeyNames="PageInRole_id" AllowAutomaticUpdates="true">
<Columns>
<telerik:GridBoundColumn DataField="ContainerPage.PageTitle" HeaderText="Title" UniqueName="ContainerPage.PageTitle"
ReadOnly="true" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
UPDATE2
Here is all exception message and stack trace:
Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.]
Telerik.Web.UI.GetEnumerator>d__0.MoveNext() +175
Telerik.Web.UI.GridDataTableFromEnumerable.FillDataTableFromEnumerable(IQueryable enumerable) +1285
Telerik.Web.UI.GridDataTableFromEnumerable.FillData35() +3390
Telerik.Web.UI.GridDataTableFromEnumerable.FillData() +824
Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
Telerik.Web.UI.GridTableView.PerformSelect() +23
Telerik.Web.UI.GridTableView.DataBind() +363
Telerik.Web.UI.GridTableView.Rebind() +101
Telerik.Web.UI.GridCommandEventArgs.ExecuteCommand(Object source) +1174
Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +185
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
Telerik.Web.UI.GridItem.OnBubbleEvent(Object source, EventArgs e) +142
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927
This exception probably comes from the code trying to re-attach a proxied/lazy-loading entity to a session. The most likely API call to throw this exception with a newer NHibernate (I don't have problem with 2.1 but I do have problems with latest) is Session.Lock(obj, LockMode.None).
If the programmer of this component first evicts the entity from the ISession and then re-loads it (perhaps cached?) into another one by id, or performs ISession.Update this problem should go away until the NHibernate team has figured out the underlying problem.
I had a similar problem with EntityFramework 6.0.
I had migrated from an old version of EntityFramework that did not use proxies and had some code that created and attached new instances of the entity via new MyEntity();.
My solution was to use dbContext.MyEntity.Create(); instead so I only work with proxies. Something similar should be available for NHibernate if I recall correctly.
My error was:
Unable to cast object of type 'MyProject.MyEntity' to type
'System.Data.Entity.DynamicProxies.MyEntity_849E94C98E5E543D6DF5245252144E3EAC00131F811886276B6ABD991719D232'
We ran into the same issue with RadGrid having AutomaticInserts. After inserting an item it throw InvalidCastException: Unable to cast object of type 'MyDbModel.Role' to type 'System.Data.Entity.DynamicProxies.Role_...' in DataBind() at Rebind().
The issue was gone after I adapted the DataBinding to have an OrderBy().

Resources