Send email from service fabric actor with SmtpClient fails - azure-service-fabric

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.

Related

Netty server memory usage keep increasing and eventually crashes with io.netty.util.internal.OutOfDirectMemoryError

Below is the code of my netty server. It is configured to release reference count on channelRead i.e wont be processing anything just drop the incoming data.
Client is also netty based. Which starts 16 parallel connections with server and start sending data on each channel.
However as soon as program starts, memory usage keep increasing and eventually it crashes with following exception.
08:41:15.789 [nioEventLoopGroup-3-1] WARN i.n.channel.DefaultChannelPipeline - An exceptionCaught() event was fired, and it reached a
t the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 100663296 byte(s) of direct memory (used: 3602907136, max: 369885184
0)
at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:640) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:594) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:764) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.PoolArena$DirectArena.newUnpooledChunk(PoolArena.java:754) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.PoolArena.allocateHuge(PoolArena.java:260) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.PoolArena.allocate(PoolArena.java:231) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.PoolArena.reallocate(PoolArena.java:397) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.PooledByteBuf.capacity(PooledByteBuf.java:118) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.AbstractByteBuf.ensureWritable0(AbstractByteBuf.java:285) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.AbstractByteBuf.ensureWritable(AbstractByteBuf.java:265) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1079) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1072) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1062) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.handler.codec.ByteToMessageDecoder$1.cumulate(ByteToMessageDecoder.java:92) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:263) ~[sosagent.jar:1.0-SNAPSHOT]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [sosagent.jar:1.0-
SNAPSHOT]
NettyServerHandler
public class AgentServerHandler extends ChannelInboundHandlerAdapter implements RequestListener {
private Buffer buffer;
private AgentToHost endHostHandler;
private String remoteAgentIP;
private int remoteAgentPort;
private ChannelHandlerContext context;
private float totalBytes;
private long startTime;
boolean called;
#Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
log.debug("New agent-side connection from agent {} at Port {}",
socketAddress.getHostName(),
socketAddress.getPort());
this.context = ctx;
remoteAgentIP = socketAddress.getHostName();
remoteAgentPort = socketAddress.getPort();
requestListenerInitiator.addRequestListener(this);
if (this == null ) log.info("EHy nULLL ");
// Utils.router.getContext().getAttributes().put("agent-callback", requestListenerInitiator);
StatCollector.getStatCollector().connectionAdded();
startTime = System.currentTimeMillis();
}
private boolean isMineChannel(RequestTemplateWrapper request, AgentServerHandler handler) {
// if (handler == null) log.info("nULLLL"); else log.info("not null");
return request.getPorts().contains(((InetSocketAddress) handler.context.channel().remoteAddress()).getPort());
}
/* Whenever AgentServer receives new port request from AgentClient.
This method will be called and all the open channels
will be notified. */
#Override
public void newIncomingRequest(RequestTemplateWrapper request) {
endHostHandler = getHostHandler(request);
if (isMineChannel(request, this)) {
endHostHandler.addChannel(this.context.channel());
log.debug("Channel added for Client {}:{} Agent Port {}",
request.getRequest().getClientIP(),
request.getRequest().getClientPort(),
(((InetSocketAddress) this.context.channel().remoteAddress())).getPort());
this.buffer = bufferManager.addBuffer(request, endHostHandler);
}
endHostHandler.setBuffer(buffer);
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ReferenceCountUtil.release(msg);
totalBytes += ((ByteBuf) msg).capacity();
}
}
Bootstrap
private boolean startSocket(int port) {
group = new NioEventLoopGroup();
AgentTrafficShaping ats = new AgentTrafficShaping(group, 5000);
ats.setStatListener(this);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer() {
#Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline()
.addLast("agent-traffic-shapping", ats)
.addLast("lengthdecorder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4))
// .addLast("bytesDecoder", new ByteArrayDecoder())
.addLast(new AgentServerHandler())
.addLast("4blength", new LengthFieldPrepender(4))
// .addLast("bytesEncoder", new ByteArrayEncoder())
;
}
}
);
ChannelFuture f = b.bind().sync();
log.info("Started agent-side server at Port {}", port);
return true;
// Need to do socket closing handling. close all the remaining open sockets
//System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
//f.channel().closeFuture().sync();
} catch (InterruptedException e) {
log.error("Error starting agent-side server");
e.printStackTrace();
return false;
} finally {
//group.shutdownGracefully().sync();
}
}
What could be possible cause here. I know netty uses reference count to keep track of Buffers. I am just releasing the reference as soon as I get a message so that shouldn't be problem !
There might be different reasons for OOM exception. One reason readily comes to my mind is is setting AUTO_READ option on the channel. The default value is true.
you can get more information about this in stack overflow posts here and here
If setting AUTO_READ option doesn't help, netty provides an option to check if any message to ChannelHandler is not released. Please set -Dio.netty.leakDetectionLevel=ADVANCED JVM option in the system properties.
This happens because the client is writing faster than what the server can process. This ends up filling up the client buffer (memory) and eventual crash. The solution is to adjust the client send rate based on the server. One way to achieve this is that the server periodically reports the reading rate to the client and the client adjusts the write speed based on that.

Not able to Load MimeConent of certain Emails using EWS API

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.

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)

OracleCommand execution blocks if has OracleDependency

I have the following code:
OracleConnection conn = new OracleConnection(connString);
OracleCommand command = new OracleCommand("select * from testtable", conn);
conn.Open();
OracleDependency.Port = 2010;
OracleDependency dependency = new OracleDependency(command);
command.AddRowid = true;
command.Notification.IsNotifiedOnce = false;
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
command.CommandTimeout = 1000;
DataTable t = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter(command);
adapter.Fill(t);
conn.Close();
This is a very straightforward code that uses Oracle Notification Service to receive notifications about particular table changes.
My problem is that when I call adapter.Fill(t); the execution simply blocks. The command executes in an instance if there is no dependency attached to it so it's not the database or the data. I can see the call back registering with the database by querying the table user_change_notification_regs and have also opened the port specified (2010):
net8://(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST='myIp')(PORT=2010)))?PR=0
I am at wits end and rand out of things to try.
I have seen an exception raised in a similar situation when I've tried to set the port number to a port already used on my machine. As soon as I commented out setting the port number it ran fine, so perhaps you could try that? And check "netstat -na" for used ports.
The exception I saw was:
Oracle.DataAccess.Client.OracleException: ORA-24912: Listener thread failed. Listen failed.
at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure, Boolean bCheck)
at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, OracleConnection conn, String procedure, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, Boolean bCheck)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior)
at Oracle.DataAccess.Client.OracleDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
The confusing thing (at least for me) was the exception is raised not when the port is set, but later when the first query was executed against it.