WinFoms Designer in VS2019 won't open newly created form - c#

I have a simple C# project (SDK style, targetting .NET Framework 4.8). When I right click my project and add a new WinForm, the designer refuses to open the form. It just shows this error message:
Object reference not set to an instance of an object.
The callstack that is shown below the error message does not help (me) at all:
at System.Resources.Tools.StronglyTypedResourceBuilder.Create(IDictionary resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, Boolean internalClass, String[]& unmatchable)
at System.Resources.Tools.StronglyTypedResourceBuilder.Create(IDictionary resourceList, String baseName, String generatedCodeNamespace, CodeDomProvider codeProvider, Boolean internalClass, String[]& unmatchable)
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObject.BuildType()
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObject.GetObjectType()
at Microsoft.VisualStudio.Shell.Design.GlobalType.get_ObjectType()
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObject.get_Children()
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.CreateGlobalObjectsForItem(ProjectItem item, GlobalObjectCollection oldObjects, GlobalObjectCollection newObjects, ITypeResolutionService typeResolver)
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.CreateGlobalObjectsForItem(ProjectItem item, GlobalObjectCollection oldObjects, GlobalObjectCollection newObjects, ITypeResolutionService typeResolver)
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.CreateGlobalObjectsForItem(ProjectItem item, GlobalObjectCollection oldObjects, GlobalObjectCollection newObjects, ITypeResolutionService typeResolver)
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.CreateGlobalObjects(Project project)
at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.GetGlobalObjectsCore(Project project, Type baseType)
at Microsoft.VisualStudio.Shell.Design.GlobalObjectProvider.GetGlobalObjects(Project project, Type baseType)
at Microsoft.VisualStudio.Shell.Design.GlobalObjectService.GetGlobalObjects(Type baseType)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetTypeFromGlobalObjects(String name, Boolean throwOnError, Boolean ignoreCase)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name)
at System.ComponentModel.Design.Serialization.DesignerSerializationManager.GetRuntimeType(String typeName)
at System.ComponentModel.Design.Serialization.DesignerSerializationManager.GetType(String typeName)
at System.ComponentModel.Design.Serialization.DesignerSerializationManager.System.ComponentModel.Design.Serialization.IDesignerSerializationManager.GetType(String typeName)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.GetType(IDesignerSerializationManager manager, String name, Dictionary`2 names)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.FillStatementTable(IDesignerSerializationManager manager, IDictionary table, Dictionary`2 names, CodeStatementCollection statements, String className)
at System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32 fReload)
Has anyone seen this kind of behavior?
Is there any way to make the designer load the WinForm?

Related

SOAP exception in WPF Application while accessing Web Service

I am learning C#, and in one of the assignment i have to display the data from an Access file into a DataGrid upon button click using a WPF Application, and a web reference.
There is a SOAP Exception which i am not able to resolve, any help is appreciated, thanks in advance -
Web reference asmx file contains the below method, that is called upon button click -
[WebMethod]
public ArrayList queryDB()
{
string selectStmt = "select * from Students";
OleDbConnection conn_obj = new DBConnect().checkDBStatus(databaseLocation);
conn_obj.Open();
OleDbCommand query = new OleDbCommand(selectStmt, conn_obj);
OleDbDataReader dbReader = query.ExecuteReader();
ArrayList dbRecordList = new ArrayList();
foreach (DbDataRecord dbRecord in dbReader)
{
dbRecordList.Add(dbRecord);
}
conn_obj.Close();
return dbRecordList;
}
WPF file code is as below - "Button click method"
private void GetData_Click(object sender, RoutedEventArgs e)
{
ArrayList datagridList = (ArrayList) websrvc.queryDB();
dataGrid.ItemsSource = datagridList;
}
The above code is creating an error - Cannot implicitly convert type 'object[]' to 'System.Collections.ArrayList'
Hence based on a suggestion over web, changed the code as below -
private void GetData_Click(object sender, RoutedEventArgs e)
{
object obj = websrvc.queryDB();
ArrayList datagridList = (ArrayList) obj;
dataGrid.ItemsSource = datagridList;
}
Now, there seems to be no errors, but an exception at the below line of code, which i am not able to solve -
object obj = websrvc.queryDB();
{"System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: System.Data.Common.DataRecordInternal cannot be serialized because it does not have a parameterless constructor.\n at System.Xml.Serialization.TypeDesc.CheckSupported()\n at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)\n at System.Xml.Serialization.XmlSerializationWriter.CreateUnknownTypeException(Type type)\n at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)\n at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)\n at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_queryDBResponse(Object[] p)\n at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer1.Serialize(Object objectToSerialize, XmlSerializationWriter writer)\n at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)\n --- End of inner exception stack trace ---\n at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)\n at System.Web.Services.Protocols.SoapServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)\n at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)\n at System.Web.Services.Protocols.WebServiceHandler.Invoke()\n --- End of inner exception stack trace ---"}
Create a class on web service side named Student with all the properties that you want to send to client.
Mark this class as serializable.
Map the DB object properties one by one to this Student class.
From the service, instead of returning ArrayList, return ArrayList();
Let me know if this works.

How to pass parameters for a managed code dll in installshield?

I have a dotnet script which is for encryption and decryption. I have to pass the parameters for the setvalues function in installshield. How can I achieve this? Dotnet code is as follows. I have the assembly (.dll) file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Security;
using System.Xml;
using System.Collections.Specialized;
namespace EncryptionDecryption
{
public class EncrptionHelper
{
#region Member variables
static byte[] entropy = { 0, 8, 2, 3, 5 };
#endregion
#region Public Methods
public static void SetValue(string configFilePathName, string appSettingKey, string appSettingValue)
{
appSettingValue = EncryptString(ToSecureString(appSettingValue));
SetSetting(appSettingKey, appSettingValue, configFilePathName);
}
public static string GetValue(string configFilePathName, string appSettingKey)
{
string value = GetSetting(appSettingKey, configFilePathName);
value = ToInsecureString( DecryptString(value));
return value;
}
#endregion
#region Private Methods
private static bool SetSetting(string Key, string Value, string configFilePath)
{
bool result = false;
try
{
// System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(configFilePath);
// config.AppSettings.File = configFilePath;
// config.AppSettings.Settings[Key].Value = Value;
// config.Save(ConfigurationSaveMode.Modified);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(configFilePath);
xmlDoc.SelectSingleNode("//appSettings/add[#key='" + Key +"']").Attributes["value"].Value = Value;
xmlDoc.Save(configFilePath);
ConfigurationManager.RefreshSection("appSettings");
result = true;
}
finally
{ }
return result;
}
private static string GetSetting(string Key, string configFilePath)
{
string result = null;
try
{
XmlDocument appSettingsDoc = new XmlDocument();
appSettingsDoc.Load(configFilePath);
XmlNode node = appSettingsDoc.SelectSingleNode("//appSettings");
XmlElement value = (XmlElement)node.SelectSingleNode(string.Format("//add[#key='" + Key + "']"));
result = (value.GetAttribute("value").ToString());
}
finally
{ }
return result;
}
private static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
private static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
private static string EncryptString(System.Security.SecureString input)
{
byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)), entropy, System.Security.Cryptography.DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
private static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
Convert.FromBase64String(encryptedData),
entropy,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
#endregion
}
}
Update: Action start 14:31:36: Encryption.
MSI (c) (84:40) [14:31:36:525]: Invoking remote custom action. DLL: C:\Users\<username>\AppData\Local\Temp\MSIE259.tmp, Entrypoint: m1
InstallShield: Attempting to load through CLR 4 APIs...
InstallShield: Getting meta host...
InstallShield: Enumerating available runtimes...
InstallShield: Highest available runtime: v4.0.30319
InstallShield: Trying to use highest runtime...
InstallShield: Using highest version runtime...
InstallShield: Loading assembly Security.Encryption from resource 4097
InstallShield: Calling method with parameters [(System.String)C:\Program Files (x86)\<Installdir>\<configfilename>.config, (System.String)VWFPassword, (System.String)]
InstallShield: Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\<Installdir>\<configfilename>.config'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.Load(String filename)
at Security.Encryption.EncrptionHelper.SetSetting(String appSettingKey, String appsettingValue, String configFilePathName)
at Security.Encryption.EncrptionHelper.SetValue(String configFilePathName, String appSettingKey, String appSettingValue)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at InstallShield.ClrHelper.CustomActionHelper.CallMethod(EntryPointInfo info)
at InstallShield.ClrHelper.CustomActionHelper.RunAction(UInt32 installHandle, Int32 entryNumber, Int64 instanceHandle)
InstallShield: Managed code threw an unhandled exception.
This is the error I receive after doing all that is mentioned in the screenshots below and doing some R&D. The directory mentioned "C:\Program Files (x86)\\.config" exists when the encryption custiom action is being called but it throws an exception.
Yes, it can be done with following steps:
1- write your required functionality in c# installer class (make sure your are using installer class)
2- Compile and add your dll into installshield (recomended create a separate component for this dll)
3- Select component view -> select above component and go to .Net settings section, set the ".Net Installer class" to true. Set the ".net installer class parameters"
Parameters are passed as key/value pair e.g
/targetDirectory="[INSTALLDIR]\"
All steps are same, just added screenshots.
Create a dll with an installer class and your encrypt/decrypt class.
Add dll and config file to component(above mentioned), if config file is already added to some other component then its fine. no need to add again.
I have added and retrieved INSTALLDIR variable as argument which is predefined. if you want to receive some input from user (from some custom textboxes) then you will need to define your own variables to store and pass values as arguments.
Creating dll with installer class and your requred logic for other task
Creating component and adding files
Mark the dll as installer class and pass arguments
Here goes installer class:
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Configuration.Install;
using System.Collections.Generic;
namespace EncryptionDecryption
{
[RunInstaller(true)]
public class InstallerClassDemo : Installer
{
private string installationDirectory=string.Empty;
private string testString=string.Empty ;
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
try
{
//For testing purpose only.. work only in debug mode when pdb files are deployed as well.
//Debugger.Break();
installationDirectory = Context.Parameters["INSTALLDIR"];
//I believe, the config file must be located in the installation directory if so, then use the following way to compute path
string configFilePath = Path.Combine(installationDirectory, "myConfigFile.config");
EncrptionHelper.SetValue(configFilePath, "testKey", "testValue");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
protected override void OnCommitted(System.Collections.IDictionary savedState)
{
base.OnCommitted(savedState);
}
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
}
}
}
I think installshield cannot (or need extra work) for read your assemblies, but you can run simple console application which consume your assemblies from installscript and passing parameter from installshield.
Create simple console application
Include console application on Support Files
Copy to installation folder or assemblies location, so console application can access your assemblies
Launch from installscript using launchappandwait
If consoleapp.exe not use anymore, just delete it.

I'm getting an odd MissingManifestResourceException

I have a solution with several projects, a main project, a globalization project and a test project.
When code in the main project retreives a message from the Messages.de.resx file of the globalization project everything works fine.
But when I copy the same code to the test project, I get a MissingManifestResourceException telling me no resources were found for the specified or neutral culture:
System.Resources.MissingManifestResourceException ist aufgetreten.
Message=Für die angegebene Kultur oder die neutrale Kultur konnten
keine Ressourcen gefunden werden. Stellen Sie sicher, dass
EGR_IQone_Globalization.Messages.resources beim Kompilieren richtig in
die Assembly EGR_IQone_Globalization eingebettet wurde, oder dass die
erforderlichen Satellitenassemblys geladen werden können und
vollständig signiert sind. Source=mscorlib StackTrace:
bei System.Resources.ManifestBasedResourceGroveler.HandleResourceStreamMissing(String
fileName)
bei System.Resources.ManifestBasedResourceGroveler.GrovelForResourceSet(CultureInfo
culture, Dictionary`2 localResourceSets, Boolean tryParents, Boolean
createIfNotExists, StackCrawlMark& stackMark)
bei System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo
requestedCulture, Boolean createIfNotExists, Boolean tryParents,
StackCrawlMark& stackMark)
bei System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo
culture, Boolean createIfNotExists, Boolean tryParents)
bei System.Resources.ResourceManager.GetString(String name, CultureInfo culture)
bei System.Resources.ResourceManager.GetString(String name)
bei EGR_IQone_Globalization.UserMessage.GetMessage(String msgID, String[] arguments) in
C:\projects\EGR_IQoneH\EGR_IQone\EGR_IQone_Globalization\UserMessage.cs:Zeile
28. InnerException:
Normally, the code works just using the .resx file and even using resgen to compile it into a .resources file changes nothing.
I thought it might have to do with the ResourceManager or the specified Assembly, but I could not see any difference between the call from the main project and the call from the test project.
This is the code:
public static class UserMessage
{
private static ResourceManager _resourceManager;
static UserMessage()
{
string baseName = Assembly.GetAssembly(typeof(UserMessage)).GetName().Name + ".Messages.de";
Console.WriteLine(baseName);
_resourceManager = new ResourceManager(baseName, Properties.GlobalizationAssembly);
}
public static string GetMessage(string msgID, params string[] arguments)
{
string msg = "";
string error = "[Message Error] cannot read Message " + msgID;
try
{
//DefaultLanguage = 'de'
//using the GetString overload with or without CultureInfo paramter makes no difference
msg = _resourceManager.GetString(msgID, new CultureInfo(Properties.DefaultLanguage));
for (int i = 0; i < arguments.Length; i++)
{
msg = msg.Replace("{" + i.ToString() + "}", arguments[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(error + "\r\n" + ex.ToString());
return error;
}
return msg;
}
}
http://pastebin.com/L0YNxyfK
Thanks!
I've had the same error - it suddenly occurred even though the application had been running for a while.
It helped to set the Thread.CurrentThread.CurrentUICulture before getting the resource.
Try the following or something similar:
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
msg = _resourceManager.GetString(msgID);

Connect to database (ADO.NET, SQL Server)

I created an ADO.NET Entity Data Model, using this instruction. I have two new classes:
namespace Parser
{
public partial class advert : EntityObject
{
///////////
}
public partial class test_workEntities1 : ObjectContext
{
///////
}
}
Then I created the following class:
namespace Parser
{
public class BdProvider
{
public void InsertAdv()
{
advert adv = new advert();
test_workEntities1 f = new test_workEntities1();
adv.adress = "adress 1";
adv.const_link = "domain.com";
adv.count_room = 10;
f.advert.AddObject(adv);
}
}
}
And I have created the following console application:
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
BdProvider bd = new BdProvider();
bd.InsertAdv();
Console.ReadKey();
}
}
}
When I run the application, I see:
The specified named connection is either not found in the
configuration, not intended to be used with the EntityClient provider,
or not valid
StackTrace:
System.ArgumentException не обработано Message=Указанное именованное
соединение не найдено в конфигурации, не предназначалось для
использования с поставщиком EntityClient или недопустимо.
Source=System.Data.Entity StackTrace: в
System.Data.EntityClient.EntityConnection.ChangeConnectionSt
ring(String newConnectionString) в
System.Data.EntityClient.EntityConnection..ctor(String
connectionString) в
System.Data.Objects.ObjectContext.CreateEntityConnection(Str ing
connectionString) в System.Data.Objects.ObjectContext..ctor(String
connectionString, String defaultContainerName) в
Parser.test_workEntities1..ctor() в
C:\proj\Parser\Model1.Designer.cs:строка 34 в
Parser.BdProvider.InsertAdv() в C:\proj\Parser\BdProvider.cs:строка 28
в TestApp.Program.Main(String[] args) в
C:\proj\TestApp\Program.cs:строка 21 в
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args) в
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssem bly() в
System.Threading.ThreadHelper.ThreadStart_Context(Object state) в
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) в
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) в
System.Threading.ThreadHelper.ThreadStart() InnerException:
I tried to create test_workEntities1, using different connectionString, but I was not successful.
My connectionString is
<connectionStrings>
<add name="test_workEntities1"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=PKVZALE\SQLEXPRESS;Initial Catalog=test_work;Integrated Security=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
</connectionStrings>
You need to add the connection string the TestApp configuration file.
Currently, you have it in the app.config file of the Parser project, however, as you are running the application via the TestApp project, .NET is looking for settings in this project.
// Expanded Answer
The app.config can be created in the root folder of your project. You can do this by copy/paste from Parser project or by using the following instructions from msdn
To add an application configuration file to your C# project
On the Project menu, click Add New Item.
The Add New Item dialog box appears.
Select the Application Configuration File template and then click Add.
A file named app.config is added to your project.
You need to do 3 things when you have an entity framework - EF in a different project:
Connection String in EF project
Reference in another project
EF Connection string in another project

AppDomain probing problems

I am trying to load a strongly named assembly that is located at a user-defined location into an AppDomain using this code:
AppDomainSetup ads1 = new AppDomainSetup();
if (ads1.PrivateBinPath != null)
{
ads1.PrivateBinPath += ads1.PrivateBinPath.Length == 0 ? "" : Path.PathSeparator.ToString();
}
ads1.PrivateBinPath += #"c:\work\abc1";
sandbox1 = AppDomain.CreateDomain("sandbox1", null, ads1);
Object o1 = sandbox1.CreateInstanceFromAndUnwrap(#"abc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f10808f3df0adc34", "Abc.Def");
When I run I get this error:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'file:///C:\Users\gel\Documents\Visual Studio 2012\Projects\ConsoleApplicat
ion1\ConsoleApplication1\bin\Debug\abc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f10808f3df0adc34' or one of its dependencies. The system cannot find the fil
e specified.
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stack
Mark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& st
ackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& st
ackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boole
an forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadFrom(String assemblyFile, Evidence securityEvidence)
at System.Activator.CreateInstanceFromInternal(String assemblyFile, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, C
ultureInfo culture, Object[] activationAttributes, Evidence securityInfo)
at System.AppDomain.CreateInstanceFrom(String assemblyFile, String typeName)
at System.AppDomain.CreateInstanceFromAndUnwrap(String assemblyName, String typeName)
at System.AppDomain.CreateInstanceFromAndUnwrap(String assemblyName, String typeName)
at ConsoleApplication1.Program.Main(String[] args) in c:\Users\gel\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:li
ne 69
It is as though the AppDomain is not looking in the PrivateBinPath at all. What am I not doing right? I've double checked in an Explorer window and I can see the assembly at the location that I specified in the PrivateBinPath. It works fine if I just do Assembly.LoadFile and specify the right path, but that'd defeating the purpose of trying to load it in another AppDomain.
I've modified your code and this works just great. See the changes you needs to be done.
AppDomainSetup ads1 = new AppDomainSetup();
if (ads1.PrivateBinPath != null)
{
ads1.PrivateBinPath += ads1.PrivateBinPath.Length == 0 ? "" : Path.PathSeparator.ToString();
}
ads1.PrivateBinPath += #"D:\ConsoleApplication1\ClassLibrary1\bin\debug";
AppDomain sandbox1 = AppDomain.CreateDomain("sandbox1", null, ads1);
Object o1 = sandbox1.CreateInstanceFromAndUnwrap(#"ClassLibrary1.dll", "ClassLibrary1.Class1");
I belive it fails to load that assembly into your current AppDomain, not to the new one (where it likley loaded ok).
The behavior sometimes called "leaking types to aother domain" and casued by attempt to use the created object directly. To work around it one need to create class completely in the other AppDomain (i.e. by running some custom code that deal with creation) and than exposing only interface/classes known to both domain. Check out Unloadable plugins for details.
Short portion of code adopted from the article - create RemoteLoader class in other AppDomain with CreateInstanceFromAndUnwrap and use that object to load/manage other types in the new AppDomain.
public class RemoteLoader : MarshalByRefObject
{
public void Load(string assemblyName, string typeName)
{
object instance = Activator.CreateInstance(assemblyName, typeName);
//Do something with instance, or return shared interface of it.
}
}
Side note: unless you doing it for education purposes consider using existing plugin frameworks like MEF.

Categories