I am using VS 2017 and SQL server 2016 to do the job. I create a script task that tries to send email by using SendGrid. If I put a break point inside the script task, I won't have problem to execute my SSIS package and then get the email. However, if I simply execute the package, the entire package still can be executed successfully but I cannot get the email, which I suspect that script task does not get executed. The following is the code of my script task
public void Main()
{
string User_Email = Dts.Variables["User::UserEmail"].Value.ToString();
try
{
if (!File.Exists(Dts.Variables["User::OutputPath"].Value.ToString()))
throw new FileNotFoundException();
File.Copy(Dts.Variables["User::OutputPath"].Value.ToString(), Dts.Variables["User::DestinationPath"].Value.ToString() + Dts.Variables["User::co_num"].Value.ToString() + ".pdf", true);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
SendGridMailHelper.SendOrderVerification(User_Email, "user name");
}
catch (FileNotFoundException)
{
MessageBox.Show("The file is not found in the specified location");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name.Contains("SendGrid"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "SendGrid.dll"));
}
if (args.Name.Contains("System.Net.Http"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "System.Net.Http.dll"));
}
if (args.Name.Contains("Newtonsoft.Json"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "Newtonsoft.Json.dll"));
}
return null;
}
To be safe, I checked the windows log and it showed the run time error when I run the package without adding check points. However, I cannot figure it out what it means. Any thoughts will be very helpful. Thank you.
Application: DtsDebugHost.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.MissingMethodException
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+<_SendEmail>d__7.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+<_SendEmail>d__7, ST_b240be27e55248ea869be51aa06a2018, Version=1.0.6877.42064, Culture=neutral, PublicKeyToken=null]](<_SendEmail>d__7 ByRef)
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper._SendEmail(System.Collections.Generic.List`1, System.Object, System.String)
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
Related
Hello everyone i am stuck with this exception and it is stopping my service. please help following is the full stack trace.
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.WebException at System.Net.HttpWebRequest.GetResponse()
at
Microsoft.Exchange.WebServices.Data.EwsHttpWebRequest.Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest.GetResponse()
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest)
Exception Info: Microsoft.Exchange.WebServices.Data.ServiceRequestException
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest)
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest ByRef)
at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.InternalExecute()
at Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection.Open()
at ERSupportGetOutlookEmail.EmailExchange.OnDisconnect(System.Object, Microsoft.Exchange.WebServices.Data.SubscriptionErrorEventArgs)
at Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection.InternalOnDisconnect(System.Exception)
at Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection.OnRequestDisconnect(System.Object, Microsoft.Exchange.WebServices.Data.HangingRequestDisconnectEventArgs)
at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.InternalOnDisconnect(Microsoft.Exchange.WebServices.Data.HangingRequestDisconnectReason, System.Exception)
at Microsoft.Exchange.WebServices.Data.GetStreamingEventsResponse.ReadElementsFromXml(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader)
at Microsoft.Exchange.WebServices.Data.ServiceResponse.LoadFromXml(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader, System.String)
at Microsoft.Exchange.WebServices.Data.GetStreamingEventsRequest.ParseResponse(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader)
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadResponse(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader)
at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.ParseResponses(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Here is my code please look into this
public async System.Threading.Tasks.Task Watch()
{
//Configuration options for a public client application (desktop/mobile app)
var pcaOptions = new PublicClientApplicationOptions
{
ClientId = ConfigurationManager.AppSettings["appId"],
TenantId = ConfigurationManager.AppSettings["tenantId"]
};
//Creates a PublicClientApplicationBuilder from a clientID.
var pca = PublicClientApplicationBuilder
.CreateWithApplicationOptions(pcaOptions).Build();
//access permission.
var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };
try
{
// Make the interactive token request
var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, EmailID, ConvertToSecureString(Password)).ExecuteAsync();
//var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();
// Configure the ExchangeService with the access token
ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
Console.WriteLine("New Email details will display below:-");
// Make an EWS call
CreateStreamingSubscription(); //Creating subscription.
}
catch (MsalException ex)
{
Email.onErrorOccur(ex.Message, "EmailExchange Watch event MsalException", ex.StackTrace);
}
catch (Exception ex)
{
Email.onErrorOccur(ex.Message, "EmailExchange Watch event", ex.StackTrace);
}
}
On the code you posted its whats in CreateStreamingSubscription that is causing the exception, its just being caught by the code block you posted which isn't doing any Exchange requests just authentication. Can you give more detail on when it happens eg does the code work for a while and this happens or it just doesn't work? if it just doesn't work may TLS 1.2 so i would suggest including in
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
I made a simple http endpoint using Grapevine (which is just an interface for HttpListener). Sometimes the connection drops before I SendResponse which leads to a HttpListenerException, but I don't understand why the try/catch doesn't handle the exception and the whole server crashes.
Error:
Application: Movimiento de Placas.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.HttpListenerException
Stack:
at System.Net.HttpResponseStream.Write(Byte[], Int32, Int32)
at Grapevine.Interfaces.Server.HttpResponse.SendResponse(Byte[])
at Grapevine.Server.HttpResponseExtensions.SendResponse(Grapevine.Interfaces.Server.IHttpResponse, System.String)
at Grapevine.Server.Router.Route(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Code:
[RestRoute(HttpMethod = HttpMethod.POST, PathInfo = "/patente")]
public IHttpContext ModificarPantalla(IHttpContext context)
{
var dict = HttpUtility.ParseQueryString(context.Request.Payload);
var json = new JavaScriptSerializer().Serialize(
dict.Keys.Cast<string>()
.ToDictionary(k => k, k => dict[k]));
var contenido = JsonConvert.DeserializeObject<Patente>(json);
Server.FormRef.CargarPatente(contenido.Plate, contenido.idCamera);
UltimaFoto.Fecha = DateTime.Now;
Task.Run(() => Sqlite.InsertarPatente(contenido));
try
{
context.Response.SendResponse(HttpStatusCode.Ok); //exception occurs here
}
catch (Exception ex)
{
}
return context;
}
This is a known issue. There is a PR that's been hanging around for a while now that fixes this, I'm merging it in now, along with an update that will add support for .NET Standard. This should be available by the end of the week.
Update: Grapevine 4.1.2 is available on Nuget.org as of August 9, 2019
This could happen if SendResponse was async and you didnt await it.
I have a server which listens to HTTP POSTs that several client make sending information. I use Grapevine as http server because methods are really simple and didn't need the complexity of ASP.
Sometimes I get this random
error:
2017-12-12 15:39:25.5642|ERROR|Omnibox_Server.Modelo.HttpServer.Controllers.OpenALPRController|System.Net.HttpListenerException (0x80004005): The I/O operation has been aborted because of either a thread exit or an application request
at System.Net.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at Grapevine.Interfaces.Server.HttpRequest.get_Payload()
at Omnibox_Server.Modelo.HttpServer.Controllers.OpenALPRController.PostPatente(IHttpContext context)
This is the
class/method:
namespace Omnibox_Server.Modelo.HttpServer.Controllers
{
[RestResource(BasePath = "/openalpr")]
public class OpenALPRController
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
[RestRoute(HttpMethod = HttpMethod.POST, PathInfo = "/patente")]
public IHttpContext PostPatente(IHttpContext context)
{
try
{
context.Response.StatusCode = HttpStatusCode.Ok;
context.Response.ContentType = ContentType.JSON;
context.Response.ContentEncoding = Encoding.UTF8;
var fotoOpenAlpr = JsonConvert.DeserializeObject<FotoOpenALPR>(context.Request.Payload); //<--- exception occurs here? shouldn't try/catch work?
var ip = context.Request.RemoteEndPoint;
if (fotoOpenAlpr.agent_uid != null)
Task.Run(async () =>
{
if (fotoOpenAlpr.is_parked) return;
await fotoOpenAlpr.ObtenerFoto(ip.Address);
try
{
var foto = new Foto(fotoOpenAlpr);
if (foto.IdOmnibox == 0) Logger.Info("Omnibox sin ID con IP " + ip.Address);
await foto.Procesar();
}
catch (Exception e)
{
}
});
context.Response.SendResponse(HttpStatusCode.Ok); //or maybe exception triggers here?
}
catch (Exception e)
{
Logger.Error(e);
}
return context;
}
}
}
An event is generated in the
windows log:
Application: Omnibox Server.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.HttpListenerException
at System.Net.HttpResponseStream.Write(Byte[], Int32, Int32)
at Grapevine.Interfaces.Server.HttpResponse.SendResponse(Byte[])
at Grapevine.Server.HttpResponseExtensions.SendResponse(Grapevine.Interfaces.Server.IHttpResponse, System.String)
at Grapevine.Server.Router.Route(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Both exception log and windows log in the event viewer have the same timestamp.
From the OP:
I fixed the issue by moving the line context.Response.SendResponse(HttpStatusCode.Ok); below the try/catch. I think what happened was that sometimes TCP pipe breaks and payload is corrupt/incomplete, therefore an exception is thrown when trying to get it, and because I didn't SendResponse(OK) another exception is thrown outside the try/catch, breaking my server.
My application is running on Windows Embedded Standard 7 and launches when the OS boots up.
Sometimes on the first load, I will get an Unknown Hard Error, and after checking the Event Viewer, I see a message of
The application requested process termination through System.Environment.FailFast(string message).
Message: Unrecoverable system error.
Needless to say, I of course have no calls to this function. I only seem to see this happen on Windows Embedded, and haven't seen this reproduced on a standard install of Windows.
I'm unsure of how to diagnose this or what 'fix' would be appropriate as I don't really know why it happens.
Edit:
The entire log in Event Viewer:
Application: WinForm.exe
Framework Version: v4.0.30319
Description: The application requested process termination through System.Environment.FailFast(string message).
Message: Unrecoverable system error.
Stack:
at System.Environment.FailFast(System.String)
at MS.Internal.Invariant.FailFast(System.String, System.String)
at System.IO.Packaging.Package.AddIfNoPrefixCollisionDetected(ValidatedPartUri,
System.IO.Packaging.PackagePart) at System.IO.Packaging.Package.GetPartHelper(System.Uri)
at System.IO.Packaging.Package.GetPart(System.Uri)
at System.Windows.Application.GetResourceOrContentPart(System.Uri)
at System.Windows.Application.LoadComponent(System.Object, System.Uri)
at Pms.PmControl.InitializeComponent()
at Pms.PmControl..ctor(Boolean)
at Pms.PmAppControl.StartWpfThread()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
If you look at the code with a decompiler you will find
// System.IO.Packaging.Package
private void AddIfNoPrefixCollisionDetected(PackUriHelper.ValidatedPartUri partUri, PackagePart part)
{
this._partList.Add(partUri, part);
int num = this._partList.IndexOfKey(partUri);
Invariant.Assert(num >= 0, "Given uri must be present in the dictionary");**
string normalizedPartUriString = partUri.NormalizedPartUriString;
string text = null;
string text2 = null;
if (num > 0)
{
text = this._partList.Keys[num - 1].NormalizedPartUriString;
}
if (num < this._partList.Count - 1)
{
text2 = this._partList.Keys[num + 1].NormalizedPartUriString;
}
if ((text != null && normalizedPartUriString.StartsWith(text, StringComparison.Ordinal) && normalizedPartUriString.Length > text.Length && normalizedPartUriString[text.Length] == PackUriHelper.ForwardSlashChar) || (text2 != null && text2.StartsWith(normalizedPartUriString, StringComparison.Ordinal) && text2.Length > normalizedPartUriString.Length && text2[normalizedPartUriString.Length] == PackUriHelper.ForwardSlashChar))
{
this._partList.Remove(partUri);
throw new InvalidOperationException(SR.Get("PartNamePrefixExists"));
}
}
The code fails at the assert because that is the only method which calls FailFast
internal static void Assert(bool condition, string invariantMessage)
{
if (!condition)
{
Invariant.FailFast(invariantMessage, null);
}
}
Now the question remains why you package could not be found in the PartList array. WPF fills some things out for you. Could it be that you reference from your XAML some resource via an internet addresses or a network share which could fail if the network subsystem of your Windows embedded is not yet ready?
My service code resided in OnStart() throws Exception(I) and service is stopped. I don't know why is there any ex. thrown?.. This is my code:
public Service1()
{
InitializeComponent();
}
Thread thread;
protected override void OnStart(string[] args)
{
thread = new Thread(delegate()
{
string path = #"D:\levani\FolderListenerTest\ListenedFolder";
FileSystemWatcher listener;
listener = new FileSystemWatcher(path);
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;
});
thread.Start();
}
public void listener_Created(object sender, FileSystemEventArgs e)
{
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name);
}
protected override void OnStop()
{
thread.Abort();
}
Log
Log Name: Application
Source: .NET Runtime
Date: 6/11/2012 5:33:27 PM
Event ID: 1026
Task Category: None
Level: Error
Keywords: Classic
User: N/A
Computer: Levan-PC
Description:
Application: FolderListenerService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException
Stack:
at System.IO.__Error.WinIOError(Int32, System.String)
at System.IO.File.InternalCopy(System.String, System.String, Boolean)
at System.IO.File.Copy(System.String, System.String)
at FolderListenerService.Service1.listener_Created(System.Object, System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32, System.String)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name=".NET Runtime" />
<EventID Qualifiers="0">1026</EventID>
<Level>2</Level>
<Task>0</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2012-06-11T14:33:27.000000000Z" />
<EventRecordID>18314</EventRecordID>
<Channel>Application</Channel>
<Computer>Levan-PC</Computer>
<Security />
</System>
<EventData>
<Data>Application: FolderListenerService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException
Stack:
at System.IO.__Error.WinIOError(Int32, System.String)
at System.IO.File.InternalCopy(System.String, System.String, Boolean)
at System.IO.File.Copy(System.String, System.String)
at FolderListenerService.Service1.listener_Created(System.Object, System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32, System.String)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
</Data>
</EventData>
</Event>
It could be any number of reasons. See File.Copy() documentation, especially the Exceptions section that document all the exceptions that could be thrown.
You need to wrap your File.Copy() and catch any exceptions so you can react appropriately:
public void listener_Created(object sender, FileSystemEventArgs e)
{
try
{
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name);
}
catch {FileNotFoundException e)
{
//do something if file isn't there
}
catch {UnauthorizedAccessException e)
{
//do something if invalid permissions
}
//etc
}
Extra parameter true in File.Copy will overwrite the file if already exists. I think the error is of file already exist.
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name,true);
Put the code in try..catch block and catch the IOException exception. You can do logging in file for further debugging.
We get the WinIOError error (as we get in call stack) when The filename , directory name, or volume label syntax is incorrect. So just check for the correct path and filename.
I don't know why but after I surrounded my code by try {} catch {} it works excellent, Have any idea? This is code:
public Service1()
{
InitializeComponent();
}
Thread thread;
protected override void OnStart(string[] args)
{
try
{
thread = new Thread(delegate()
{
string path = #"D:\levani\FolderListenerTest\ListenedFolder";
FileSystemWatcher listener; listener = new FileSystemWatcher(path);
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;
});
thread.Start();
}
catch (Exception ex)
{
File.WriteAllText(#"D:\levani\bussite.txt", "thread: " + ex.ToString());
}
}
public void listener_Created(object sender, FileSystemEventArgs e)
{
try
{
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name);
}
catch (Exception ex)
{
File.WriteAllText(#"D:\levani\bussite.txt", "File copy ex: " + ex.ToString());
}
}
protected override void OnStop()
{
thread.Abort();
}
If you create a new thread, you need to be sure to handle all exceptions thrown on that thread. Any unhandled exceptions that occur on a thread created by Thread.Start() will cause your application to terminate.
Specifically, the constructor FileSystemWatcher(string path) and File.Copy(string sourceFileName, string destFileName) throw several exceptions that you are not handling in your current code. Both of these are being called on a separate thread. It is most likely that you are getting an IOException, due to the file already existing (multiple changes to the same file will cause your code to try to copy it more than once, causing a collision on any copies after the first).
You should probably update your File.Copy call to use File.Copy(string sourceFileName, string destFileName, bool overwrite) and wrap your listener_Created function in a try/catch block that does soemthing with the exception (other than rethrowing it).