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.
Related
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);
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 have a function that can create a new email in outlook and it works fine when running on my local machine. However, when deployed to the server i get the error shown below.
This is what it looks like when I run the code on my local machine:
Link. Is it possible to make this code run on the server and generate emails for users?
Error:
System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)). 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 MyProjectName.btnEmailEstimate_Click(Object sender, EventArgs e) in D:\My\Project\location\MyProjectName.ascx.cs:line 9833
Here is my code:
protected void btnEmailEstimate_Click(object sender, EventArgs e)
{
try
{
List<string> lstAllRecipients = new List<string>();
//Below is hardcoded - can be replaced with db data
lstAllRecipients.Add("test1#testmail.com");
lstAllRecipients.Add("test2#testmail.com");
Outlook.Application outlookApp = new Outlook.Application();
Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMailItem.GetInspector;
// Recipient
Outlook.Recipients oRecips = (Outlook.Recipients)oMailItem.Recipients;
foreach (String recipient in lstAllRecipients)
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
oRecip.Resolve();
}
//Add CC
Outlook.Recipient oCCRecip = oRecips.Add("testCC#testmail.com");
oCCRecip.Type = (int)Outlook.OlMailRecipientType.olCC;
oCCRecip.Resolve();
//Add Subject
oMailItem.Subject = "Test Mail";
// body, bcc etc...
oMailItem.Body = "Email body content here \nThis is a new line.";
//Display the mailbox
oMailItem.Display(true);
var time = DateTime.Now;
tbLast_email_update.Text = time.ToString();
}
catch (Exception objEx)
{
Response.Write(objEx.ToString());
}
}
I am working on enqueue jobs using hangfire in my application.
my enqueue job statement is given below,
string jobId = BackgroundJob.Enqueue(() =>
strategy.get(typeof(_service.Engine.Summary), cpdata));
when this will enqueue my job successfully but got the error message in State table like this,
"FailedAt": "2018-03-21T13:14:46.0172303Z", "ExceptionType":
"System.MissingMethodException", "ExceptionMessage": "No
parameterless constructor defined for this object.",
"ExceptionDetails": "System.MissingMethodException: No parameterless
constructor defined for this object.\r\n 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.Activator.CreateInstance(Type type, Boolean nonPublic)\r\n at
System.Activator.CreateInstance(Type type)\r\n at
Hangfire.JobActivator.SimpleJobActivatorScope.Resolve(Type type)\r\n
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext
context)\r\n at
Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass8_0.b__0()\r\n
at
Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter
filter, PerformingContext preContext, Func 1 continuation)\r\n at
Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext
context, IEnumerable`1 filters)\r\n at
Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext
context)\r\n at
Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context,
IStorageConnection connection, String jobId)"
Is this DI issue that creating this type of error?
i used calling method in Enqueue using the reference of this link
Factory method with DI and IOC
For Example,
var strategy = new CarStrategy(new ICarFactory[] {
new Car1Factory(dep1, dep2, dep3),
new Car2Factory(dep4, dep5, dep6),
new Car3Factory(dep7, dep8, dep9)
});
My Code is Like this,
var strategy = new Strategy(new ICP[] {
new _Services.Engine.Detail.Detail(),
new _1Services.Engine.Summary.Summary(),
});
var CP = PrepareCPModelForEngine(c);
string jobId = BackgroundJob.Enqueue(() =>
strategy.get(typeof(_Services.Engine.Summary.Summary), cp));
I'm getting the following error and I'm not sure why as I am running code straight off of a template. Does anyone see something in the stack trace that I don't? It is posted below.
Server Error in '/Cfia.Web.MvcTemplate.Example' Application.
The remote server returned an error: (404) Not Found.
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.Net.WebException: The remote server returned
an error: (404) Not Found.
Source of Error:
Line 27: /// Initializes a new instance of the <see cref="ApplicationBaseController" /> class.
Line 28: /// </summary>
Line 29: public ApplicationBaseController()
Line 30: {
Line 31: ApplicationTitle = Labels.GetLabel("Application.MvcTemplate.Examples");
Stack Trace:
[WebException: The remote server returned an error: (404) Not Found.]
System.Net.HttpWebRequest.GetResponse() +8521152
System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials
credentials, IWebProxy proxy, RequestCachePolicy cachePolicy) +160
System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type
ofObjectToReturn) +328
System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver) +75
System.Threading.CompressedStack.runTryCode(Object userData) +260
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode
code, CleanupCode backoutCode, Object userData) +0
System.Threading.CompressedStack.Run(CompressedStack compressedStack,
ContextCallback callback, Object state) +118
System.Xml.XmlTextReaderImpl.OpenUrl() +7534355
System.Xml.XmlTextReaderImpl.Read() +187
System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean
preserveWhitespace) +176 System.Xml.XmlDocument.Load(XmlReader
reader) +144 System.Xml.XmlDocument.Load(String filename) +205
Cfia.Globalization.Provider.XmlFileLabelProvider.RetrieveAllLabels(CultureInfo
culture) +424
Cfia.Globalization.Provider.LabelService.RetrieveAllRawLabels(CultureInfo
culture) +490
Cfia.Globalization.Provider.LabelService.RetrieveAllLabels(CultureInfo
culture) +50
Cfia.Globalization.Provider.LabelService.Labels(CultureInfo culture)
+344 Cfia.Globalization.Labels.GetLabels(CultureInfo culture) +157 Cfia.Web.Mvc.Menu.FooterLink..ctor() +221
Cfia.Web.Mvc.ControllerBase.BaseController..ctor() +165
Cfia.Web.MvcTemplate.Example2.Controllers.ApplicationBaseController..ctor()
in c:\Users\cir-anglinovd\Documents\Visual Studio
2012\Projects\ContosoUniversity\Cfia.Web.MvcTemplate.Example2\Controllers\ApplicationBaseController.cs:29
Cfia.Web.MvcTemplate.Example2.Controllers.HomeController..ctor() in
c:\Users\cir-anglinovd\Documents\Visual Studio
2012\Projects\ContosoUniversity\Cfia.Web.MvcTemplate.Example2\Controllers\HomeController.cs:30
[TargetInvocationException: Exception has been thrown by the target of
an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType
type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +159
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
+256 System.Activator.CreateInstance(Type type, Boolean nonPublic) +127 System.Activator.CreateInstance(Type type) +11 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +92
[InvalidOperationException: An error occurred when trying to create a
controller of type
'Cfia.Web.MvcTemplate.Example2.Controllers.HomeController'. Make sure
that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +562491
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) +89
Castle.Proxies.Invocations.IControllerFactory_CreateController.InvokeMethodOnTarget()
+155 Castle.DynamicProxy.AbstractInvocation.Proceed() +116 Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext
context) +71 Castle.DynamicProxy.AbstractInvocation.Proceed() +604
Castle.Proxies.IControllerFactoryProxy.CreateController(RequestContext
requestContext, String controllerName) +193
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
+305 System.Web.Mvc.<>c__DisplayClass6.b__2() +78 System.Web.Mvc.<>c__DisplayClassb1.<ProcessInApplicationTrust>b__a()
+19 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func1 func) +128
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+12551795 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
I fixed it, just had to make some changes in the web.config file.