I have an issue where I got error
id 1000 (KERNELBASE.dll)
and
error id 1026 System.IO.FileNotFoundException
When I try to run my program on Win 7 (witch had run fine before), but it runs perfectly on win 8/8.1/10. I am running .Net Framework 4.5.
I had been trying to deleting the code, but then the error just appears on other lines off my code and thats keeps going on, so does anyone know how to fix it or know how to find out what actually are causing that issue
Binding Failure occurred
Message : Managed Debugging Assistant ' Binding Failure ' has detected a problem in ' F: \ Omini \ Omini Dækberegner.exe ' .
Additional information : the assembly with the display name ' PresentationFramework.Aero2 ' could not be loaded into the binding context '
C#
InitializeComponent();
bredebox_nu.Focus();
textBoxes = new List<TextBox> { bredebox_nu, profilbox_nu, Fælgestr_nu, bredebox_ny, profilbox_ny, Fælgestr_ny, oprofilbox, obredebox, oFælgestr };
win.SourceInitialized += new EventHandler(win_SourceInitialized);
List<biler> items = new List<biler>();
the other error
System.Windows.Markup.XamlParseException occurred
HResult=-2146233087
Line Number = 616
Line Position = 48
Message = ' There were triggered an exception at setting the property ' System.Windows.FrameworkElement.Style ' . ' Line number ' 616 ' and line position ' 48' .
Source = Presentation Framework
Stack Trace :
by System.Windows.Markup.WpfXamlLoader.Load ( XamlReader xamlReader , IXamlObjectWriterFactory writer factory , Boolean skipJournaledProperties , Object rootObject , XamlObjectWriterSettings settings , Uri baseUri )
by System.Windows.Markup.WpfXamlLoader.LoadBaml ( XamlReader xamlReader , Boolean skipJournaledProperties , Object rootObject , XamlAccessLevel access level , Uri baseUri )
by System.Windows.Markup.XamlReader.LoadBaml ( Stream stream , ParserContext parserContext , Object parent , Boolean close stream)
by System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
by Omini_Tires_And_rims.MainWindow.InitializeComponent() i C:\Users\Sindakewin\documents\visual studio 2015\Projects\omini_dækberegner\omini_dækberegner\MainWindow.xaml:linje 1
by Omini_Tires_And_rims.MainWindow..ctor() i C:\Users\Sindakewin\documents\visual studio 2015\Projects\omini_dækberegner\omini_dækberegner\MainWindow.xaml.cs:linje 210
InnerException:
FileName=PresentationFramework.Aero2, PublicKeyToken=31bf3856ad364e35
FusionLog ==== state information prior binding ===
LOG: Display Name = PresentationFramework.Aero2, PublicKeyToken = 31bf3856ad364e35
(Partial)
WRN: There was delivered about a partial binding for assembly:
WRN: Assemblyname: PresentationFramework.Aero2, PublicKeyToken = 31bf3856ad364e35 | Domain ID: 1
WRN: A partial binding Occurs tabloid is only given part of assemblyens display name.
WRN This may cause the binder inputting a wrong assembly.
WRN: It is recommended to give up fully specified text ID for the Assembly,
WRN: consisting of the simple name, version, culture and token for the public key.
WRN: For more information and common solutions to this problem in the white paper http://go.microsoft.com/fwlink/?LinkId=109270.
LOG: Appbase = file: /// F: / Omini /
LOG: First PrivatePath = NULL
Calling assembly: Presentation Framework, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35.
LOG: This binding initiates in loadingcontex default.
LOG: User application configuration file: F: \ Omini \ Omini Dækberegner.exe.Config
LOG: User host configuration file:
LOG: User machineconfigurationsfile from C: \ Windows \ Microsoft.NET \ Framework \ v4.0.30319 \ config \ machine.config.
LOG: Policy not applied to reference at this time (private, custom, partial, or location-based assemblybinding).
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2.DLL.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2/PresentationFramework.Aero2.DLL.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2.EXE.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2/PresentationFramework.Aero2.EXE.
)
HRESULT = -2147024894
Message = The file or the assembly ' PresentationFramework.Aero2 , PublicKeyToken = 31bf3856ad364e35 ' or one of its dependencies could not be loaded . The specified file was not found.
Source = mscorlib
StackTrace:
by System.Reflection.RuntimeAssembly._nLoad (AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly location hint, Stack Crawl Mark & stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.RuntimeAssembly.nLoad (AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly location hint, Stack Crawl Mark & stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.RuntimeAssembly.InternalLoadAssemblyName (AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, Stack Crawl Mark & stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.Assembly.Load (AssemblyName assemblyRef)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveAssembly (BamlAssembly bamlAssembly)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlTypeToType (BamlType bamlType)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlType (BamlType bamlType, int16 typeid)
by System.Windows.Baml2006.Baml2006SchemaContext.GetXamlType (int16 typeid)
by System.Windows.Baml2006.Baml2006Reader.Process_ElementStart ()
by System.Windows.Baml2006.Baml2006Reader.Process_OneBamlRecord ()
by System.Windows.Baml2006.Baml2006Reader.ReadObject (KeyRecord record)
by System.Windows.ResourceDictionary.CreateObject (KeyRecord key)
by System.Windows.ResourceDictionary.OnGettingValue (Object key, Object & value, Boolean & canCache)
by System.Windows.ResourceDictionary.OnGettingValuePrivate (Object key, Object & value, Boolean & canCache)
by System.Windows.ResourceDictionary.GetValueWithoutLock (Object key, Boolean & canCache)
by System.Windows.ResourceDictionary.GetValue (Object key, Boolean & canCache)
by System.Windows.DeferredResourceReference.GetValue (Base Value Source Internal value source)
by System.Windows.DependencyPropertyChangedEventArgs.get_NewValue ()
by System.Windows.Controls.Control.OnTemplateChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.OnPropertyChanged (DependencyPropertyChangedEventArgs e)
by System.Windows.FrameworkElement.OnPropertyChanged (DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
by System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
by System.Windows.StyleHelper.ApplyStyleOrTemplateValue(FrameworkObject fo, DependencyProperty dp)
by System.Windows.StyleHelper.InvalidateContainerDependents(DependencyObject container, FrugalStructList`1& exclusionContainerDependents, FrugalStructList`1& oldContainerDependents, FrugalStructList`1& newContainerDependents)
by System.Windows.StyleHelper.DoStyleInvalidations(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle)
by System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache)
by System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
by System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
by System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
by System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
by System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
by MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
by MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
InnerException:
Xaml <GridViewColumn Header="Model" Width="140" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Model}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
i removed PresentationFramework.Aero2 from the references in visual studio and replaced it with PresentationFramework.Aero and deleted some of the themes and replaced the namespaces and now it runs fine on win 7 and win vista without any issues
Related
I have a question. I created a region with view and model for a "pdf reader". Then I add this "pdf reader region" to two content controls in two usercontrols. I want to recycle this region with the view and model
The pdf reader is only a view to display a pdf file.
Bootstrapper register:
regionManager.RegisterViewWithRegion(BaseNames.PDF_VIEW_REGION, typeof(
Infrastructure.Base.Views.PdfView));
BaseNames class
public static class BaseNames
{
public const string PDF_VIEW_REGION = "PdfViewBaseRegion";
}
View 1
<ContentControl Grid.Column="1" prism:RegionManager.RegionName="{x:Static contract:BaseNames.PDF_VIEW_REGION }"/>
View 2
<ContentControl Grid.Column="1" prism:RegionManager.RegionName="{x:Static contract:BaseNames.PDF_VIEW_REGION }"/>
Exception:
Prism.Regions.Behaviors.RegionCreationException: "An exception occurred while creating a region with name 'PdfViewBaseRegion'. The exception was: System.ArgumentException: Region with the given name is already registered: PdfViewBaseRegion
bei Prism.Regions.RegionManager.RegionCollection.Add(IRegion region)
bei Prism.Regions.Behaviors.RegionManagerRegistrationBehavior.TryRegisterRegion()
bei Prism.Regions.Behaviors.RegionManagerRegistrationBehavior.StartMonitoringRegionManager()
bei Prism.Regions.Behaviors.RegionManagerRegistrationBehavior.OnAttach()
bei Prism.Regions.RegionBehavior.Attach()
bei Prism.Regions.RegionBehaviorCollection.Add(String key, IRegionBehavior regionBehavior)
bei Prism.Regions.RegionAdapterBase1.AttachDefaultBehaviors(IRegion region, T regionTarget)
bei Prism.Regions.RegionAdapterBase1.Initialize(T regionTarget, String regionName)
bei Prism.Regions.RegionAdapterBase`1.Prism.Regions.IRegionAdapter.Initialize(Object regionTarget, String regionName)
bei Prism.Regions.Behaviors.DelayedRegionCreationBehavior.CreateRegion(DependencyObject targetElement, String regionName). "
If you navigate to View that uses RegionManager, you should remove your Region from RegionCollection in RegionManager.
public void OnNavigatedFrom(NavigationContext navigationContext)
{
navigationContext.NavigationService.Region.RegionManager.Regions.Remove(BaseNames.PDF_VIEW_REGION);
}
i hope you can help me.
i'm de-serializing a custom object and i'm getting this error.
the type is in a dll which is loaded using a windows hook - thus, running under explorer.exe
i understand why this error occurs, this because the DLL doesnt reside "explorer.exe" process.
there are 2 solutions for this:
1. install the assembly in GAC
2. use the "Binder" of the binary formatter.
i don't want to use any of those, as the DLL is actually loaded in explorer.exe (when i'm attaching, i see that the DLL is indeed loaded).
i'm serializing a custom object - created in the same DLL that does the de-serializing
this is my code:
BinaryFormatter binaryFormatter = new BinaryFormatter();
byte[] serializedObject;
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, new MyCustomObject());
serializedObject = memoryStream.ToArray();
}
BinaryFormatter binaryFormatter2 = new BinaryFormatter();
object deserializedObject;
using (MemoryStream memoryStream2 = new MemoryStream(serializedObject))
{
deserializedObject = binaryFormatte2r.Deserialize(memoryStream2); // Unable to find this assembly
}
by the way. i've looked a bit in the binary formatter code, somehow it does tries to load the DLL.. but it's already loaded to the process..
error:
Unable to find assembly 'AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=Key'.
stack trace:
at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
at System.Runtime.Serialization.Formatters.Binary.BinaryConverter.TypeFromInfo(BinaryTypeEnum binaryTypeEnum, Object typeInformation, ObjectReader objectReader, BinaryAssemblyInfo assemblyInfo, InternalPrimitiveTypeE& primitiveTypeEnum, String& typeString, Type& type, Boolean& isVariant)
at
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadArray(BinaryHeaderEnum binaryHeaderEnum)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
-- edit--
i'm using namespace extensions (so the OS hooks to my dlls)
It's too late, but my solution is shown below. The implementation of BindToType is overridden to solve your issue.
[Serializable]
public class YourClass : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type tyType = null;
string sShortAssemblyName = assemblyName.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ayAssembly in ayAssemblies)
{
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])
{
tyType = ayAssembly.GetType(typeName);
break;
}
}
return tyType;
}
...
This link helped me
I'm trying to load my plugin dll into separate AppDomain, but Load() method fails with FileNotFoundException. Moreover, it seems like setting PrivateBinPath property of AppDomainSetup has no effect, because in log I see "Initial PrivatePath = NULL". All plugin have strong name. Normally each plugin is stored in [Application startp path]\postplugins\[plugindir]. If I put plugins subdirectories under [Application startp path] directory, everything works. I also have tried to change AppBase property manually but it does not change.
Here is the code:
public void LoadPostPlugins(IPluginsHost host, string pluginsDir)
{
_Host = host;
var privatePath = "";
var paths = new List<string>();
//build PrivateBinPath
var dirs = new DirectoryInfo(pluginsDir).GetDirectories();
foreach (var d in dirs)
{
privatePath += d.FullName;
privatePath += ";";
}
if (privatePath.Length > 1) privatePath = privatePath.Substring(0, privatePath.Length - 1);
//create new domain
var appDomainSetup = new AppDomainSetup { PrivateBinPath = privatePath };
Evidence evidence = AppDomain.CurrentDomain.Evidence;
var sandbox = AppDomain.CreateDomain("sandbox_" + Guid.NewGuid(), evidence, appDomainSetup);
try
{
foreach (var d in dirs)
{
var files = d.GetFiles("*.dll");
foreach (var f in files)
{
try
{
//try to load dll - here I get FileNotFoundException
var ass = sandbox.Load(AssemblyName.GetAssemblyName(f.FullName));
var f1 = f;
paths.AddRange(from type in ass.GetTypes()
select type.GetInterface("PluginsCore.IPostPlugin")
into iface
where iface != null
select f1.FullName);
}
catch (FileNotFoundException ex)
{
Debug.WriteLine(ex);
}
}
}
}
finally
{
AppDomain.Unload(sandbox);
}
foreach (var plugin in from p in paths
select Assembly.LoadFrom(p)
into ass
select
ass.GetTypes().FirstOrDefault(t => t.GetInterface("PluginsCore.IPostPlugin") != null)
into type
where type != null
select (IPostPlugin)Activator.CreateInstance(type))
{
plugin.Init(host);
plugin.GotPostsPartial += plugin_GotPostsPartial;
plugin.GotPostsFull += plugin_GotPostsFull;
plugin.PostPerformed += plugin_PostPerformed;
_PostPlugins.Add(plugin);
}
}
And here is the log:
'FBTest.vshost.exe' (Managed (v4.0.30319)): Loaded 'D:\VS2010Projects\PNotes - NET\pnfacebook\FBTest\bin\Debug\postplugins\pnfacebook\pnfacebook.dll', Symbols loaded.
A first chance exception of type 'System.IO.FileNotFoundException' occurred in FBTest.exe
System.IO.FileNotFoundException: Could not load file or assembly 'pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7' or one of its dependencies. The system cannot find the file specified.
File name: 'pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7'
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at System.UnitySerializationHolder.GetRealObject(StreamingContext context)
at System.AppDomain.Load(AssemblyName assemblyRef)
at PNotes.NET.PNPlugins.LoadPostPlugins(IPluginsHost host, String pluginsDir) in D:\VS2010Projects\PNotes - NET\pnfacebook\FBTest\PNPlugins.cs:line 71
=== Pre-bind state information ===
LOG: User = ANDREYHP\Andrey
LOG: DisplayName = pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7
(Fully-specified)
LOG: Appbase = file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: pnfacebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9e2a2192d22aadc7
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook.DLL.
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook/pnfacebook.DLL.
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook.EXE.
LOG: Attempting download of new URL file:///D:/VS2010Projects/PNotes - NET/pnfacebook/FBTest/bin/Debug/pnfacebook/pnfacebook.EXE.
when you load an assembly into the AppDomain in that way, it is the current AppDomain's PrivateBinPath that is used to find the assembly.
For your example, when I added the following to my App.config it ran fine:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="[PATH_TO_PLUGIN]"/>
</assemblyBinding>
</runtime>
This is not very useful to you though.
What I did instead was to create a new assembly that contained the IPostPlugin and IPluginsHost interfaces, and also a class called Loader that looked like this:
public class Loader : MarshalByRefObject
{
public IPostPlugin[] LoadPlugins(string assemblyName)
{
var assemb = Assembly.Load(assemblyName);
var types = from type in assemb.GetTypes()
where typeof(IPostPlugin).IsAssignableFrom(type)
select type;
var instances = types.Select(
v => (IPostPlugin)Activator.CreateInstance(v)).ToArray();
return instances;
}
}
I keep that new assembly in the application root, and it doesn't need to exist in the plugin directories (it can but won't be used as the application root will be searched first).
Then in the main AppDomain I did this instead:
sandbox.Load(typeof(Loader).Assembly.FullName);
Loader loader = (Loader)Activator.CreateInstance(
sandbox,
typeof(Loader).Assembly.FullName,
typeof(Loader).FullName,
false,
BindingFlags.Public | BindingFlags.Instance,
null,
null,
null,
null).Unwrap();
var plugins = loader.LoadPlugins(AssemblyName.GetAssemblyName(f.FullName).FullName);
foreach (var p in plugins)
{
p.Init(this);
}
_PostPlugins.AddRange(plugins);
So I create an instance of the known Loader type, and then get that to create the plugin instances from within the plug-in AppDomain. That way the PrivateBinPaths are used as you want them to be.
One other thing, the private bin paths can be relative so rather than adding d.FullName you could add pluginsDir + Path.DirectorySeparatorChar + d.Name to keep the final path list short. That's just my personal preference though! Hope this helps.
Thanks a lot to DedPicto and James Thurley ; I was able to implement a complete solution, I posted in this post.
I had the same problem as Emil Badh : if you try to return from "Loader" class an interface that represents a concrete class that is unknown in current AppDomain, you get a "Serialization Exception".
It is because the concrete type tries to be deserialized.
The solution: I was able to return from "Loader" class a concrete type of a "custom proxy" and it works. See referenced post for details :
// Our CUSTOM PROXY: the concrete type which will be known from main App
[Serializable]
public class ServerBaseProxy : MarshalByRefObject, IServerBase
{
private IServerBase _hostedServer;
/// <summary>
/// cstor with no parameters for deserialization
/// </summary>
public ServerBaseProxy ()
{
}
/// <summary>
/// Internal constructor to use when you write "new ServerBaseProxy"
/// </summary>
/// <param name="name"></param>
public ServerBaseProxy(IServerBase hostedServer)
{
_hostedServer = hostedServer;
}
public string Execute(Query q)
{
return(_hostedServer.Execute(q));
}
}
This proxy could be returned and use as if it was the real concrete type !
Ok, a bit stumped here, and instead of banging my head any more on this, I thought I'd toss this out to all the bright people here.
I'm using Entity Framework and c# for a WinApp solution, and the core of the problem is that the darned thing runs fine on my system, but after I deploy it, it fails. Even when I install the deployed app on my development system, it fails. I find that a bit disturbing.
To the nuts and bold of the issue. The user performs a search, I build a query, tap SQL via the ExecuteStoreQuery call and return a generic list of SearchResult objects.
The call:
retVal = ctx.ExecuteStoreQuery<SearchResults>(sql).ToList();
Alternate call also generates the same error:
ObjectQuery<DbDataRecord> c = ctx.CreateQuery<DbDataRecord>(sql);
The Error:
************** Exception Text **************
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at System.Data.Metadata.Edm.ObjectItemConventionAssemblyLoader.LoadTypesFromAssembly()
at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load()
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors)
at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly)
at System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters)
at AMMCred.Data.Search.GetSearchResults(SearchTerms terms)
at AMMCred.frmMain.openProviderInfoToolStripMenuItem_Click(Object sender, EventArgs e)
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
SearchResults is a custom object, like so:
public class SearchResults : IEquatable<SearchResults>
{
private Guid id = Guid.Empty;
public Guid PROV_MPI_NO
{
get { return id; }
set { id = value; }
}
private string iPA = "";
public string IPA
{
get { return iPA; }
set { iPA = value; }
}
private string firstName = "";
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
private string middleName = "";
public string MI
{
get { return middleName; }
set { middleName = value; }
}
private string lastName = "";
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
private string license = "";
public string License
{
get { return license; }
set { license = value; }
}
private string provId = "";
public string ProvId
{
get { return provId; }
set { provId = value; }
}
/// <summary>
/// Used to help identify duplicates in a collection
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(SearchResults other)
{
return (this.PROV_MPI_NO == other.PROV_MPI_NO && this.License == other.License);
}
}
And finally, here is the select part of the SQL being used to obtain the search results:
SELECT a.PROV_MPI_NO, b.COMPANY_ID AS IPA, a.FIRSTNAME,a.MI,a.LASTNAME, b.PROVID, c.LICENSE
The problem seems to be coming from within Entity Framework as it's binding the results of the SQL to the custom object. I've verified that the custom object field names are the same as the SQL fields in case that mattered, which it didn't seem to.
It's darn near time for me to leave, and I'll be pondering this all weekend, so I'll probably check back in from time to time to answer any questions anyone might have.
Like I said, I'm completely stumped at the moment and would totally appreciate anyone's insight.
Thanks in advance!
Wayne
UPDATE 11/14/2011----------
Ran the Assembly Binding Log Viewer tool and came up with the following lead. Looks like Microsoft.Practices.Unity isn't loading. Thing is, I never once referenced these Practices assemblies in ANY application, but it seems that System.Data.Entity does...go figure. It's a lead...any info on this new development is so very appreciated.
*** Assembly Binder Log Entry (11/14/2011 # 3:10:52 PM) ***
The operation failed.
Bind result: hr = 0x80070002. The system cannot find the file specified.
Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable C:\Users\***me***\AppData\Local\Apps\2.0\1ND1AZ7G.HEJ\CWDQKK8A.LVO\ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4\AMMCred2.exe
--- A detailed error log follows.
=== Pre-bind state information ===
LOG: User = ***me***
LOG: DisplayName = Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
(Fully-specified)
LOG: Appbase = file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = AMMCred2.exe
Calling assembly : Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\***me***\AppData\Local\Apps\2.0\1ND1AZ7G.HEJ\CWDQKK8A.LVO\ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4\AMMCred2.exe.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity.DLL.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity/Microsoft.Practices.Unity.DLL.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity.EXE.
LOG: Attempting download of new URL file:///C:/Users/***me***/AppData/Local/Apps/2.0/1ND1AZ7G.HEJ/CWDQKK8A.LVO/ammc..tion_0000000000000000_0002.0000_456d6de62e1c40e4/Microsoft.Practices.Unity/Microsoft.Practices.Unity.EXE.
LOG: All probing URLs attempted and failed.
The error is a load exception.
Since this works in development, but not in the deployed program, it is probably due to the dll not being included.
Go into your VS project, expand the references and check the properties of each dll, make sure that copy local = true for the dll's that are not being deployed.
Based on your bind result, it looks like you are not deploying Microsoft.Practices.Unity.DLL with your application. And it looks like this is referenced from Microsoft.Practices.EnterpriseLibrary.Common, which is why you don't have a direct reference.
Here is the MSDN article that describes the various dependencies that the Enterprise Library has.
Update
I just checked the direct dependencies of System.Data.Entity using ildasm.exe (C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin) and it definitely does not reference the enterprise library. I would have been extremely surprised if it had, because they generally don't create dependencies between System DLLs and optional product DLLs (just for this reason).
Are you pulling in other DLLs/references that may include this? If you aren't sure, you can use ildasm.exe, navigate to the DLL, then open it's manifest. It's a little hard to read, but you are looking for references like:
module extern 'System.Data.dll, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
and
.assembly extern System.Data
i have written code to create new site in ftp. but its giving com exception. the code is attached for reference.
Exception details are
System.Runtime.InteropServices.COMException was unhandled
Message="Filename: \r\nError: Unrecognized element 'ftpServer'\r\n\r\n"
Source=""
ErrorCode=-2147023483
StackTrace:
at Microsoft.Web.Administration.Interop.IAppHostElement.GetElementByName(String bstrSubName)
at Microsoft.Web.Administration.ConfigurationElement.GetChildElement(String elementName)
at WindowsFormsTest.Form2.CreateFTPSite(String serverName, String siteName, String siteID) in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Form2.cs:line 48
at WindowsFormsTest.Form2.button1_Click(Object sender, EventArgs e) in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Form2.cs:line 25
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsTest.Program.Main() in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
code to create ftp site:
using(ServerManager serverManager = new ServerManager()) {
Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
ConfigurationElement siteElement = sitesCollection.CreateElement("site");
siteElement["name"] = #"eMentorftp";
ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
bindingElement["protocol"] = #"ftp";
bindingElement["bindingInformation"] = #"*:21:";
bindingsCollection.Add(bindingElement);
ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");
ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");
ConfigurationElement sslElement = securityElement.GetChildElement("ssl");
sslElement["serverCertHash"] = #"53FC3C74A1978C734751AB7A14A3E48F70A58A84";
sslElement["controlChannelPolicy"] = #"SslRequire";
sslElement["dataChannelPolicy"] = #"SslRequire";
ConfigurationElement authenticationElement = securityElement.GetChildElement("authentication");
ConfigurationElement basicAuthenticationElement = authenticationElement.GetChildElement("basicAuthentication");
basicAuthenticationElement["enabled"] = true;
ConfigurationElementCollection siteCollection = siteElement.GetCollection();
ConfigurationElement applicationElement = siteCollection.CreateElement("application");
applicationElement["path"] = #"/";
ConfigurationElementCollection applicationCollection = applicationElement.GetCollection();
ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
virtualDirectoryElement["path"] = #"/";
virtualDirectoryElement["physicalPath"] = #"D:\Ftp";
applicationCollection.Add(virtualDirectoryElement);
siteCollection.Add(applicationElement);
sitesCollection.Add(siteElement);
serverManager.CommitChanges();
You can tell what your error is from the exception. Look at the first line in the exception stack trace:
System.Runtime.InteropServices.COMException
was unhandled Message="Filename:
\r\nError: Unrecognized element
'ftpServer'\r\n\r\n" Source=""
ErrorCode=-2147023483
First of all, we see "Unrecognized element 'ftpserver'" - which should tell us a lot about what happened when we look at your code. But in addition to that, we are provided an error code that tells us exactly why the COMException got thrown. If we decode the error code into an unsigned int (hex), we get:
0x80070585
This corresponds to an error code of:
8: Failure
7: Win32
585: (1413 decimal): Invalid Index (ERROR_INVALID_INDEX)
For more info on error codes, see HRESULT and Win32 error codes.
So, we threw a COMException becuase we used an invalid index. And we get an "unrecognized element 'ftpServer'" in the exception message. Looking at your code, you create a new ConfigurationElement siteElement by telling the sitesCollection to add a new element named "site":
Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
ConfigurationElement siteElement = sitesCollection.CreateElement("site");
You then create a name for the site, and create bindings in the site's bindings collection:
siteElement["name"] = #"eMentorftp";
ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
bindingElement["protocol"] = #"ftp";
bindingElement["bindingInformation"] = #"*:21:";
bindingsCollection.Add(bindingElement);
Unfortunately, you then try to get a child element of the site using the name "ftpServer":
ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");
But, the ConfigurationElement siteElement - which was just made - doesn't have a child named ftpServer! So we get an invalid index and throw an exception. Did you mean to create a child element in this line of code?
As an aside, I imagine that it's a COMException due to interop of the .NET interface to the underlying IIS7 COM objects. Not being an expert (at all) on the Microsoft.Web namespace, that's just a guess.