Access to the path 'xxxxxxxxx' is denied - asp.net-3.5

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

Related

MS Dynamics 365 Online Plugin External Rest API access gives error

I am trying to access an external third party API from a Dynamics 365 Online plugin using the following code:
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in plug-in debugging.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
try
{
tracingService.Trace("Downloading the target URI: " + webAddress);
try
{
//<snippetWebClientPlugin2>
// Download the target URI using a Web client. Any .NET class that uses the
// HTTP or HTTPS protocols and a DNS lookup should work.
using (WebClient client = new WebClient())
{
byte[] responseBytes = client.DownloadData(webAddress);
string response = Encoding.UTF8.GetString(responseBytes);
//</snippetWebClientPlugin2>
tracingService.Trace(response);
// For demonstration purposes, throw an exception so that the response
// is shown in the trace dialog of the Microsoft Dynamics CRM user interface.
throw new InvalidPluginExecutionException("WebClientPlugin completed successfully.");
}
}
catch (WebException exception)
{
string str = string.Empty;
if (exception.Response != null)
{
using (StreamReader reader =
new StreamReader(exception.Response.GetResponseStream()))
{
str = reader.ReadToEnd();
}
exception.Response.Close();
}
if (exception.Status == WebExceptionStatus.Timeout)
{
throw new InvalidPluginExecutionException(
"The timeout elapsed while attempting to issue the request.", exception);
}
throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
"A Web exception occurred while attempting to issue the request. {0}: {1}",
exception.Message, str), exception);
}
}
catch (Exception e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
}
}
But I am getting the error:
Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.'
I have checked MS documentation but nothing suggests why I am unable to do this. I know about sandboxed plugins but according to MS I should be able to do this using their own sample code.
This is expected in CRM Online, as this is SaaS and you're in a shared tenant in cloud. You can do either webhook or Azure service hub to trigger external endpoint with CRM context for processing. Read more
And if you've got CRM Online, then the normal solution is to offload the processing to an environment that you have more control over. The most common option is to offload the processing to Azure, using the Azure Service Bus or Azure Event Hub. The alternative, new to CRM 9, is to send the data to a WebHook, which can be hosted wherever you like.

Error on restoring Actor Backup - Method not found: 'Void System.Fabric.RestoreSettings..ctor(Boolean, Boolean)'

Trying to restore a backup for an ActorService and receiving the following error: Method not found: 'Void System.Fabric.RestoreSettings..ctor(Boolean, Boolean)'
There is no inner exception.
It is a custom actor service which Extends ActorService and Implements an interface which Extends IActorService
I have checked the backupFolder that's passed in and it is valid and has the backup within it. Given that it's restored I don't think it's relevant, but this is a backup that has been retrieved from Azure blob storage
This is the line the exception is thrown by:
await restoreCtx.RestoreAsync(restoreRescription, cancellationToken);
This is the method it sits within:
protected override async Task<bool> OnDataLossAsync(RestoreContext restoreCtx, CancellationToken cancellationToken)
{
try
{
string backupFolder;
backupFolder = await this.backupManager.RestoreLatestBackupToTempLocation(cancellationToken);
RestoreDescription restoreRescription = new RestoreDescription(backupFolder, RestorePolicy.Force);
await restoreCtx.RestoreAsync(restoreRescription, cancellationToken);
DirectoryInfo tempRestoreDirectory = new DirectoryInfo(backupFolder);
tempRestoreDirectory.Delete(true);
return true;
}
catch (Exception e)
{
ActorEventSource.Current.Message("Restoration failed: " + "{0} {1}" + e.GetType() + e.Message);
throw;
}
}
As suggested by #VaclavTurecek the problem was that the Service Fabric Nuget packages were a version ahead of the runtime installed on the server (in this case my local machine). Updating via the Web Platform Installer has resolved the problem.

Set Active User to AEM background job throws Exception unexpectedly

We have background job running that requires a user to be active. The following way works fine but we have to hard-code the password which is not ideal.
try {
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
} catch (RepositoryException ex) {
log.error("SessionHelper - login issue", ex);
}
We attempt a better way to set active user without setting password as follows:
Map<String, Object> params = new HashMap<String, Object>();
params.put(ResourceResolverFactory.SUBSERVICE, "theService");
ResourceResolver resolver = null;
try {
resolver = resolverFactory.getServiceResourceResolver(params);
} catch (LoginException e) {
log.error("LoginException", e);
}
Session session = resolver.adaptTo(Session.class);
// Next, create pages and add properties ...
We then try to create pages and set properties. This works fine for couple of milliseconds where some pages are created but then throws Exception to indicate session is closed although never closed and the location where exception gets thrown is unpredictable.
javax.jcr.RepositoryException: This session has been closed. See the chained exception for a trace of where the session was closed.
...
Caused by: java.lang.Exception: Stack trace of where session-admin-20077 was originally closed
We want to know whether there is any way to set the timeout? Any recommendations appreciated.
You should obtain the session always through the ResourceResolverFactory using the getServiceResourceResolver method (getAdministrativeResourceResolver method is actually deprecated and should be avoided), execute than your code in the same try/catch block and define a finally block where you can make sure that the obtained resolver/session is closed properly. If you follow this princip, you will probably never experience problems with closed or unclosed sessions.
#org.apache.felix.scr.annotations.Component(...)
public class MyComponent {
#org.apache.felix.scr.annotations.Reference
private org.apache.sling.api.resource.ResourceResolverFactory resourceResolverFactory;
public void myaction() {
org.apache.sling.api.resource.ResourceResolver resolver = null;
try {
Map<String, Object> authInfo = new HashMap<String, Object>();
authInfo.put(ResourceResolverFactory.SUBSERVICE, getClass.getName());
resolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
javax.jcr.Session session = resolver.adaptTo(javax.jcr.Session.class);
javax.jcr.Node node = session.getNode("/jcr/path/to/the-node");
// do something with the node
session.save();
} catch(LoginException e) {
// Handle cannot obtain instance of the resource resolver
} catch(RepositoryException e) {
//handle the repository exception
} finally {
//do not forget to close the resolver, otherwise this can cause huge performance problems
if(resolver != null) {
resolver.close();
}
}
}
}
In order to obtain service resource resolver, you need also to configure the user.mapping in the OSGI-Service org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl for example as follows.:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="sling:OsgiConfig"
user.mapping="[tld.mycompany.mypackage=admin]"
user.default="admin"/>
This way you can set and offer very advanced access control policies for your services.
If you are in a sling servlet, be carefull which resource resolver you are using. In the normal case, you will not need a resource resolver with administrative rights, but take the one provided by the SlingHttpServletRequest. The resource resolver is closed by sling at the end of the request, don't close it manually.
If you are using the admin session I suggest to not log it in like you did, but with the following method (asuming from your code you have the SlingRepository already injected with #Reference):
repository.loginAdministrative(null);
And to prevent the error I would use the following pattern:
Session session = null;
try {
session = repository.loginAdministrative(null);
//do what you need to do
} catch (RepositoryException e) {
//handle exception
} finally {
if (session != null && session.isLive()) {
session.logout();
}
}
And one last note, open and close the sessionin the same thread, so not keeping the session alive in a service, except it is an EventListener.

Error in uploading a file using Jersey rest service

I am using jersey for building rest service which will upload a file. But I am facing problem in writing a file to required location. Java throws a system cannot find specified path error. Here is my Web service :
#POST
#Path("/fileupload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file")InputStream fileUploadStream, #FormDataParam("file")FormDataContentDisposition fileDetails) throws IOException{
StringBuilder uploadFileLocation= new StringBuilder();
uploadFileLocation.append("c:/logparser/webfrontend/uploads");
uploadFileLocation.append("/"+dateFormat.format(Calendar.getInstance().getTime()));
uploadFileLocation.append("/"+fileDetails.getFileName());
writeToFile(fileUploadStream, uploadFileLocation.toString());
return Response.status(200).entity("File saved to " + uploadFileLocation).build();
}
private void writeToFile(InputStream uploadInputStream, String uploadFileLocation)
{
log.debug("UploadService , writeToFile method , start ()");
try{
int read = 0;
byte[] bytes = new byte[uploadInputStream.available()];
log.info("UploadService, writeToFile method , copying uploaded files.");
OutputStream out = new FileOutputStream(new File(uploadFileLocation));
while ((read = uploadInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
catch(Exception e)
{
log.error("UploadService, writeToFile method, error in writing to file "+e.getMessage());
}
}
From looking at just the code (it's usually helpful to include the exception and stack trace), you're trying to write to a directory based on a timestamp which doesn't exist yet. Try adding a call to File.mkdir/mkdirs. See this question/answer: FileNotFoundException (The system cannot find the path specified)
Side note - Unless you have a reason not to, I'd consider using something like Apache commons-io(FileUtils.copyInputStreamToFile) to do the writing.

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.