Not able to Load MimeConent of certain Emails using EWS API - email

When i Try to get the Mime Content of an email attachment using below code
msgAttachment.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mc = msgAttachment.Item.MimeContent;
I am getting the following exception on second line
Microsoft.Exchange.WebServices.Data.ServiceRequestException occurred
HResult=-2146233088
Message=The request failed. Unable to read data from the transport connection: The connection was closed.
Source=Microsoft.Exchange.WebServices
StackTrace:
at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.ReadResponse(HttpWebResponse response)
at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.InternalExecute()
at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest1.Execute()
at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalGetAttachments(IEnumerable1 attachments, Nullable1 bodyType, IEnumerable1 additionalProperties, ServiceErrorHandling errorHandling)
at Microsoft.Exchange.WebServices.Data.ExchangeService.GetAttachment(Attachment attachment, Nullable1 bodyType, IEnumerable1 additionalProperties)
at Microsoft.Exchange.WebServices.Data.Attachment.InternalLoad(Nullable1 bodyType, IEnumerable1 additionalProperties)
at Microsoft.Exchange.WebServices.Data.ItemAttachment.Load(IEnumerable1 additionalProperties)
at Presensoft.JournalEmailVerification.EmailVerification.DownloadFailedAttachments(EmailMessage msg, JournalEmail journalEmail) in D:\Source\ProductionReleases\Release_8.0.7.0\Email Archiving\Presensoft.JournalEmailVerification\EmailVerification.cs:line 621
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: The connection was closed.
Source=System
StackTrace:
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.IO.Compression.GZipStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.Xml.XmlTextReaderImpl.ReadData()
at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars)
at System.Xml.XmlTextReaderImpl.ParseText()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlCharCheckingReader.Read()
at Microsoft.Exchange.WebServices.Data.EwsXmlReader.Read()
at Microsoft.Exchange.WebServices.Data.ComplexProperty.InternalLoadFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName, Func2 readAction)
at Microsoft.Exchange.WebServices.Data.ComplexProperty.LoadFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName)
at Microsoft.Exchange.WebServices.Data.ComplexProperty.LoadFromXml(EwsServiceXmlReader reader, String xmlElementName)
at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.InternalLoadFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.LoadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
at Microsoft.Exchange.WebServices.Data.PropertyBag.LoadFromXml(EwsServiceXmlReader reader, Boolean clear, PropertySet requestedPropertySet, Boolean onlySummaryPropertiesRequested)
at Microsoft.Exchange.WebServices.Data.ServiceObject.LoadFromXml(EwsServiceXmlReader reader, Boolean clearPropertyBag)
at Microsoft.Exchange.WebServices.Data.ItemAttachment.TryReadElementFromXml(EwsServiceXmlReader reader)
at Microsoft.Exchange.WebServices.Data.ComplexProperty.InternalLoadFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName, Func2 readAction)
at Microsoft.Exchange.WebServices.Data.ComplexProperty.LoadFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName)
at Microsoft.Exchange.WebServices.Data.ComplexProperty.LoadFromXml(EwsServiceXmlReader reader, String xmlElementName)
at Microsoft.Exchange.WebServices.Data.GetAttachmentResponse.ReadElementsFromXml(EwsServiceXmlReader reader)
at Microsoft.Exchange.WebServices.Data.ServiceResponse.LoadFromXml(EwsServiceXmlReader reader, String xmlElementName)
at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest1.ParseResponse(EwsServiceXmlReader reader)
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadResponse(EwsServiceXmlReader ewsXmlReader)
at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.ReadResponse(HttpWebResponse response)
InnerException:
What I have observed is this occurs when the particular email attachment is Undeliberable email with below content:
The e-mail system had a problem processing this message. Exchange will not try to redeliver this message for you.
Diagnostic information for administrators:
Generating server: MAIL.saaital.com
Hsfsafda#saaital.com
550 5.6.0 M2MCVT.StorageError; storage error in content conversion
Any hints..pointers?? . Really need help on this as I have been struggling for quite some time to process this particular email attachment.

Are you using Exchange Server 2010 SP3 RU2? If not, that might fix the issue. Another poster ran into a similar error and they were also sending an email with an attachment: http://social.technet.microsoft.com/Forums/en-US/fd7ef80e-f80b-47ed-883b-a34511c6233c/a-storage-transient-failure-has-occurred-during-content-conversion?forum=exchangesvrsecuremessaginglegacy.
The support page related to the fix is here: http://support.microsoft.com/kb/2863310.

Related

sending a larg string on socket by Apache Netty,but gets incomplete string in client side

I am sending a string with 2000 character on TCP socket by netty, both side of client and server,I set this pipeline :
socketChannel.pipeline().addLast(
new StringEncoder(),
new StringDecoder(),
new LineBasedFrameDecoder(Integer.MAX_VALUE),
myHandler);
on server side, I have a ChannelInboundHandlerAdapter.
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// some code
ctx.writeAndFlush(line);
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
on client side I have a SimpleChannelInboundHandler. but I get my string incomplete. why !? How can I solve that?
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {//msg is incomplete}
I found solution.
new LineBasedFrameDecoder(Integer.MAX_VALUE) is nonsense. because maximum of characters in each String in java is 65536, so try new LineBasedFrameDecoder(65536) or any size you need.
In server side each msg should end with \n or \r\n. so for example if you read a line from a text file you need add \n in the end of that.

Send email from service fabric actor with SmtpClient fails

I am trying to send an email from a Service fabric actor method. The code is very simple and works without problem in a console application but the very same code inside the actor method generate the exception:
"The remote certificate is invalid according to the validation procedure"
I have no idea why this is happening and what I should add to my code to make it work (I don't want to bypass certificate validation or disable encryption), so I am looking for help on this forum.
Thank you
Here is my code (just replaced credentials and domain with dummy names)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace testsmtp {
class Program {
static void Main(string[] args) {
SendEmailAlert("myuserid", "mypassword", "recipient#mydomain.com", "test subject", "test body");
}
private static bool SendEmailAlert(string uid, string pwd, string recipient_list, string subject, string body) {
MailMessage msg = new MailMessage();
msg.To.Add(recipient_list);
msg.From = new MailAddress("sender#mydomain.com");
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = false;
SmtpClient client = new SmtpClient();
client.Host = "smtp.mydomain.com";
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(uid, pwd);
try {
client.Send(msg);
return true;
}
catch (Exception e) {
string emsg = e.Source + "\n" + e.Message;
return false;
}
}
}
}
and here is the exception data
Message "The remote certificate is invalid according to the validation procedure." string
StackTrace " at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)\r\n at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)\r\n at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)\r\n at System.Net.Mail.SmtpConnection.Flush()\r\n at System.Net.Mail.ReadLinesCommand.Send(SmtpConnection conn)\r\n at System.Net.Mail.EHelloCommand.Send(SmtpConnection conn, String domain)\r\n at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)\r\n at System.Net.Mail.SmtpClient.GetConnection()\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)\r\n at UserActor.UserActor.DeliverFeedbackMessage(String cur_msg, String remote_ip, String usr_agent) in C:\\testsrc\\DigitalRadar\\UserActor\\UserActor.cs:line 621" string
You're using SSL to connect to the mail server (smtp.mydomain.com). Check if the certificate on the mail server has a valid (CA signed) certificate. Maybe it's self-signed, or expired, or has a weak cypher.
Allright, I found a good workaround (without compromising security) to avoid this problem, I am answering my own question to help anyone that might have the same problem and end up here.
I should mention my SF version is 5.0.217, actors ver is 2.0.217, maybe newer ver. might not have the problem since the SF team is continuosly improving the framework. When I have some time I will check new ver and update this thread in case.
Coming back to the problem it seems the default cert validation fails when SmtpClient.Send is called from within a SF actor method. The same call made from a C# console app works great. The reason is beyond my understanding, maybe some SF glitch, anyway .NET allows to write and register a custom validation procedure to replace the default one, using this approach I solved the problem, but it's important to not blindly say "valid" to any certificate as I have seen suggested in many upvoted posts here on S.O, I recommend to actually check the certificate to see if it's good, otherwise you screw the security, then there is no point to use SSL or certificate at all. Having said that here is my validation code (adapt it to your own situation)
private bool MyValidateSmtpServerCertificate(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors) {
if (sslPolicyErrors != SslPolicyErrors.None)
return false;
string[] subj_params = certificate.Subject.Split(',');
string common_name = string.Empty;
foreach (string param in subj_params) {
string[] sub_params = param.Split('=');
if (sub_params[0].Trim() == "CN")
common_name = sub_params[1].Trim();
}
string[] valid_names = {
common_const.smtpServer,
"*." + common_const.smtpServer,
};
if (!valid_names.Contains(common_name))
return false;
return true;
}
Register this function before calling the SmtpClient.Send with the following line:
ServicePointManager.ServerCertificateValidationCallback = MyValidateSmtpServerCertificate;
That's all, now my code inside the actor method works flawlessly, the email is securely and reliably delivered.

Custom workflow step inconsistent behavior

I've made a custom workflow step which sends email to the group of users. I take precreated email and send it programmatically:
if (recepients.Entities.Any())
{
Entity email = service.Retrieve("email", mailId, new ColumnSet(true));
email.Attributes["to"] = recepients.Entities.ToArray();
service.Update(email);
SendEmailRequest sendEmail = new SendEmailRequest()
{
EmailId = mailId,
IssueSend = true
};
service.Execute(sendEmail);
}
The problem is - it works just fine in sync mode, and throw an "Invalid Cast" exception if i convert workflow into async and try to run it.
Here what trace log on the server provides:
>System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #EBCA9EC1: System.InvalidCastException: Specified cast is not valid.
> at Microsoft.Crm.Common.ObjectModel.TrackingManager.GetNextTrackingToken(String subject, String& trackingToken)
> at Microsoft.Crm.Common.ObjectModel.EmailService.Send(Guid emailId, Boolean issueSend, String trackingToken, ExecutionContext context)
Somehow error occurs during converting results of the workflow. Where should I look to find the root of this problem?
at WorkflowToAsyncResultConverter.Convert(WorkflowSystemPausedResult wfResult) ilOffset = 0x23
at WorkflowToAsyncResultConverter.Convert() ilOffset = 0x9D
at WorkflowContext.EndProcessing(IGenericHandlerResult result) ilOffset = 0xC
at ActivityHost.CompleteWorkflow(IGenericHandlerResult result, WorkflowApplication activityInstance, ICommonWorkflowContext context) ilOffset = 0x70
at ActivityHostBase.OnWorkflowTerminated(WorkflowApplicationUnhandledExceptionEventArgs args, WorkflowApplication activityInstance, ICommonWorkflowContext context) ilOffset = 0x8F
at UnhandledExceptionEventHandler.OnStage1Complete(IAsyncResult lastResult, WorkflowApplication instance, Exception exception, Activity source, String sourceInstanceId) ilOffset = 0x46
at UnhandledExceptionEventHandler.Run(WorkflowApplication instance, Exception exception, Activity exceptionSource, String exceptionSourceInstanceId) ilOffset = 0x78
at WorkflowApplication.OnNotifyUnhandledException(Exception exception, Activity exceptionSource, String exceptionSourceInstanceId) ilOffset = 0x23
at ActivityExecutor.NotifyUnhandledException(Exception exception, ActivityInstance source) ilOffset = 0x18
at Scheduler.OnScheduledWork(Object state) ilOffset = 0x123
at SendOrPostThunk.UnhandledExceptionFrame(Object state) ilOffset = 0x0
at ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) ilOffset = 0x22
at IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) ilOffset = 0x5
at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) ilOffset = 0x3C
Try creating an OrganizationService running as the executing user, instead of SYSTEM. A similar issue with the core email operation has been experienced by Andrii Butenko, who concluded that it works when running the service in the context of the executing user.
I have changed instantiation of service to running user and everything worked without any issues:
IOrganizationServiceFactory factory =
(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(executioncontext.UserId);

Access to the path 'xxxxxxxxx' is denied

I'm facing this error every time I want to write file to folder.
Here is my code:
protected void ListAttachments(List<MessagePart> msgParts)
{
bool attachmentsFound = false;
StringBuilder b = new StringBuilder();
b.Append("<ol>");
foreach (MessagePart p in msgParts)
{
string contentType = p.Headers["Content-Type"];
string contentDisposition = p.Headers["Content-Disposition"];
Match m;
if (contentDisposition != null)
{
m = FilenameRegex.Match(contentDisposition);
if (m.Success)
{
attachmentsFound = true;
b.Append("<li><a href='Handler.ashx?fileName=" + m.Groups["filename"].Value + "'>").Append(m.Groups["filename"].Value).Append("</a></li>");
Response.AppendHeader("content-disposition", "attachment; filename=" + m.Groups["filename"].Value);
Response.ContentType = "application/octet-stream";
//Error Occurs
Response.TransmitFile(Server.MapPath(#"~/Files"));
Response.End();
}
}
else if (contentType != null)
{
m = NameRegex.Match(contentType);
if (m.Success)
{
attachmentsFound = true;
b.Append("<li><a href='Handler.ashx?fileName="+m.Groups["filename"].Value+"'>").Append(m.Groups["filename"].Value).Append("</a></li>");
}
}
}
b.Append("</ol>");
if (attachmentsFound)
AttachmentsLiteral.Text = b.ToString();
else
AttachementsRow.Visible = false;
}
Here error occurs like Access to the path 'F:\Gmail\Files' is denied.
This is error details:
Server Error in '/Gmail' Application.
Access to the path 'F:\Gmail\Files' is denied.
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.UnauthorizedAccessException: Access to the path 'F:\Gmail\Files' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Source Error:
Line 160: Response.AppendHeader("content-disposition", "attachment; filename=" + m.Groups["filename"].Value);
Line 161: Response.ContentType = "application/octet-stream";
Line 162: Response.TransmitFile(Server.MapPath(#"~/Files"));
Line 163: Response.End();
Line 164: }
Source File: f:\Gmail\DisplayPop3Email.aspx.cs Line: 162
Stack Trace:
[UnauthorizedAccessException: Access to the path 'F:\Gmail\Files' is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +7712175
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) +1162
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +66
System.Web.HttpResponse.TransmitFile(String filename, Int64 offset, Int64 length) +134
System.Web.HttpResponse.TransmitFile(String filename) +12
DisplayPop3Email.ListAttachments(List`1 msgParts) in f:\Gmail\DisplayPop3Email.aspx.cs:162
DisplayPop3Email.Page_Load(Object sender, EventArgs e) in f:\Gmail\DisplayPop3Email.aspx.cs:90
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Please tell me how I can fix it up....
It has been some time since I have worked on ASP.NET, but I will take a shot at this answer. Firstly, the error is pretty obvious - the user account possibly the NETWORK service account under whose context the ASP.NET processes are executing do not have access to the directory F:\Gmail\Files.
Please refer to this link that should give you a pointer on how to go forward - rather it details the steps to taken in order to ensure that ASP.NET processes can write/read disk files without posing a security concern.
Also refer to the below links to learn more about What is new in ASP.NET Data access (article applies to ASP.NET 3.0) and ASP.NET required Access Control Lists.
Hope this gives a step to solve the current problem you are facing

"The remote host closed the connection. The error code is 0x80072746." On cancelling a big report export

I get the following exception when i try to cancel the download of SSRS report export.
It is generated by Reserved.ReportViewerWebControl.axd file.
Is there anything i can do to prevent this exception? I did google before posting here but really didn't find anything useful.
System.Web.HttpException: The remote host closed the connection. The error code is 0x80072746.
at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status, Byte[] header, Int32 keepConnected, Int32 totalBodySize, Int32 numBodyFragments, IntPtr[] bodyFragments, Int32[] bodyFragmentLengths, Int32 doneWithSession, Int32 finalStatus, Boolean& async)
at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal)
at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush)
at System.Web.HttpResponse.Flush(Boolean finalFlush)
at System.Web.HttpResponse.Flush()
at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size)
at System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at Microsoft.Reporting.WebForms.ReportDataOperation.StreamToResponse(Stream data, HttpResponse response)
at Microsoft.Reporting.WebForms.ExportOperation.PerformOperation(NameValueCollection urlQuery, HttpResponse response)
at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)