I am trying to instantiate a class from DemoClass.dll using Activator.CreateInstance(type.Assembly.FullName, type.FullName)
This class implements the one interface from other dll. Lets say DemoInterfaces.dll. Earlier it was supposed to implement two methods. But now we have only one method i.e. one is removed. However, while instantiating it is trying to reference old copy which I don't see anywhere. It is the new dll and also checked it in dotpeek. The DemoInterfaces.dll interface has only one method.
Below is the sample code.
Assembly assembly = Assembly.LoadFrom(path);
Type type = assembly.GetType("className", true, true);
var xxx = Activator.CreateInstance(type.Assembly.FullName, type.FullName);
However, it is looking the implementation of second method. So Method implementation in class from DemoClass.dll is not found.
{"Exception has been thrown by the target of an invocation."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146232828
HelpLink: null
InnerException: {"Method not found: ''xxxx"}
Message: "Exception has been thrown by the target of an invocation."
Source: "mscorlib"
StackTrace: " at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)\r\n at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(Type type, Boolean nonPublic)\r\n at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)\r\n at System.Activator.CreateInstance(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Bi
nder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(String assemblyName, String typeName)\r\n at xxxx in xx"
TargetSite: {System.Object CreateInstance(System.RuntimeType, Boolean, Boolean, Boolean ByRef, System.RuntimeMethodHandleInternal ByRef, Boolean ByRef)}
Any help is highly appreciated.
Try passing Type only.
Assembly assembly = Assembly.LoadFrom(path);
Type type = assembly.GetType("Namespace.className");
object instance = Activator.CreateInstance(type);
Related
I am trying to read from an EXCEL file and display what i get.
Here is my Excel Class.
class Excel
{
private string path = "";
_Application excel = new _Excel.Application();
Workbook workbook;
Worksheet worksheet;
public Excel(string path, int sheet)
{
this.path = path;
workbook = excel.Workbooks.Open(path);
worksheet = workbook.Worksheets[sheet];
}
public string ReadCell(int row, int column)
{
row++;
column++;
if (worksheet.Cells[row, column].Value2 != null)
{
return worksheet.Cells[row, column].Value2;
}
else
{
return "";
}
}
}
Here is how i call it
string pathToFile = #"K:\hours\tracking.xlsx";
Excel excel = new Excel(pathToFile, 1);
MessageBox.Show(excel.ReadCell(0, 0));
Here is my exception
System.Runtime.InteropServices.COMException
HResult=0x80040154
Message=Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
Source=mscorlib
StackTrace:
at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at working_hours.Excel..ctor(String path, Int32 sheet) in K:\programming\visual_studio_projects\working_hours\working_hours\working_hours\Excel.cs:line 14
at working_hours.Program.Main(String[] args) in K:\programming\visual_studio_projects\working_hours\working_hours\working_hours\Program.cs:line 31
I Chcked if the path is correct and it is.
I think it may have to do with the References that i just implemented, but im not quite Sure.
I added
System.Windows.Forms.dll
and
Microsoft.Office.Interop.Excel.dll
If anyone has any idea please let me know.
Thank you.
I am trying to develop an application that sends automated emails through outlook and interop services and getting the following exception. below is the code with exception.
try
{
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = (Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "Details of Subject";
mailItem.To = "example#gmail.com";
mailItem.Body = "Automated email testing"
// mailItem.Attachments.Add(logPath);//logPath is a string holding path to the log.txt file
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send();
}
catch (Exception ex)
{
WriteErrorLog("\n");
WriteErrorLog(ex.Message);
WriteErrorLog(ex.StackTrace);
}
And its throwing an exception :
System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType) at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType) at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at WServiceMixInOne.ConnectionLogs.MainClass() in C:\Users\admin\documents\visual studio 2017\Projects\WServiceMixInOne\WServiceMixInOne\ConnectionLogs.cs:line 120
Line 120 is the 1st line app = new Microsoft.Office.Interop.Outlook.Application();
Try closing outlook from background process. And then execute your code.
Exception occurs when i try to create instance of type through assembly.CreateInstance method. This is my code in which exception occurs
Assembly assembly = Assembly.LoadFrom(#"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll");
Type type = assembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfileManager");
object ins = assembly.CreateInstance(type.FullName);
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: serviceContext
at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext)
at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext, Boolean ignorePrivacy)
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext, Boolean IgnoreUserPrivacy, Boolean backwardCompatible)
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Reflection.Assembly.CreateInstance(String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Reflection.Assembly.CreateInstance(String typeName)
at HomeWork.Program.Main(String[] args) in c:\users\amasud\documents\visual studio 2010\Projects\HomeWork\HomeWork\Program.cs:line 23
I dont know the reason why you want to create Microsoft.Office.Server.UserProfiles.UserProfileManager object in reflective way. In your case, you have to pass SPServerContext to the constructor. Here is how you can do it.
Assembly assembly = Assembly.LoadFrom(#"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll");
SPServiceContext serviceContext = SPServiceContext.Current;
Type type = assembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfileManager");
object ins = Activator.CreateInstance(type, serviceContext);
From the look of it, whatever type you are creating is expecting a serviceContext parameter in the constructor. You haven't set it, so it crashes.
Hi i am developing MMC snap in C#,
in this i want to read XML file so where to put my xml file.
the code is not giving any build error but when i am adding the snapin in MMC its giveing error what to do.
[SnapInSettings("{2078B103-76FF-46E1-95BB-8B2CE3A72E60}",
DisplayName = "Configuration",
Description = "abc Pvt Ltd.")
]
public class Mymmc : SnapIn
{
XDocument xDoc;
public Sararmmc()
{
ScopeNode childscopenode;
xDoc = XDocument.Load("MMCSnapinXML.xml");
IEnumerable<XElement> xelements = xDoc.Root.Descendants();
this.RootNode = new ScopeNode();
this.RootNode.DisplayName = xDoc.Root.Attribute("name").Value;
foreach (XElement elm in xelements)
{
childscopenode = new ScopeNode();
childscopenode.DisplayName = elm.Attribute("name").Value;
this.RootNode.Children.Add(childscopenode);
}
}
}
i am getting
Exception has been thrown by the target of an invocation.
Server stack trace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
at Microsoft.ManagementConsole.Internal.SnapInClient.CreateSnapIn(String assemblyName, String typeName)
at Microsoft.ManagementConsole.Internal.ClassLibraryServices.Microsoft.ManagementConsole.Internal.IClassLibraryServices.CreateSnapIn(String assemblyName, String typeName)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
Exception rethrown at [0]:
at Microsoft.ManagementConsole.Executive.SnapInInitializationOperation.OnStart()
at Microsoft.ManagementConsole.Executive.Operation.Start()
at Microsoft.ManagementConsole.Executive.RunningOperationsTable.EnqueueOperation(Operation operation)
at Microsoft.ManagementConsole.Executive.StandAloneComponentData..ctor(SnapInRegistrationInfo info, Int32 bookkeepingId)
at Microsoft.ManagementConsole.Advanced.FrameworkSnapInFactory.Microsoft.ManagementConsole.Advanced.ISnapInFactory.CreateSnapIn(Int32 bookkeepingId, String snapInKey, Object& snapIn)
There are many exceptions which could be thrown in your constructor (the stack trace indicates that this is the source of the error). It could be a malformed XML exception is thrown on XDocument.Load, it could also be null reference exception if any of the named nodes/attributes you're accessing don't exist. It could be a file not found exception, or even a SecurityException - it could even be something more obscure such as MMC requiring that your assembly is signed.. without knowing what type of exception you're getting it's very difficult for anyone to help you!
As I said in my comment, when you receive errors at runtime that you can't easily explain - this is when having verbose logging in your application becomes really valuable! NLog and log4net are the two most popular logging frameworks for .NET applications
On some, but not all, machines when we try to deserialize some XML using (written in C#) System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
we get a kind of security related error described in the error message and stack trace below. The exception is thrown by the assembly that gets generated by .NET when serializing/deserializing.
In the stack trace below, AggregateElement derives from Element.
We haven't had any problems with .NET 3.5 and our code hasn't changed since we've upgraded to .NET 4
Does anyone have any ideas on what and why this is?
Error: Illegal call to the reserved method 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read53_AggregateElement()' from 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read72_Element()'.
Call Stack Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read53_AggregateElement(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read72_Element(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read74_Section(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read70_SubForm(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read72_Element(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read74_Section(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read70_SubForm(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read92_Sheet(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSheet.Read93_Sheet()
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 System.Xml.Serialization.TempAssembly.InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)