Access to the path denied, trying to access remote server file - asp.net-mvc

I'm having a hard time trying to access a remote server file from other server with my asp .Net application (C#) hosted in it. The scenario is the following:
I wrote an MVC web application that is hosted on SERVER A; and in some instance, it has to let the user modify a XML configuration file that is located on SERVER B. So, here is the part of the code where I try to read that file from a shared folder on SERVER B:
(C# - Controller)
WindowsImpersonationContext impContext = null;
try
{
impContext = NetworkSecurity.ImpersonateUser(
Settings.Default.ImpersonationDomain,
Settings.Default.ImpersonationUser,
Settings.Default.ImpersonationPass,
LogonType.LOGON32_LOGON_NETWORK,
LogonProvider.LOGON32_PROVIDER_DEFAULT);
}
catch (ApplicationException ex)
{
// write to log file
}
if (null != impContext)
{
try
{
//get the location of the configuration file
string remoteConfigFile = Settings.Default.RemoteDesktopMonitorCnfgFile;
//open the configuration file
XDocument xmlFile = XDocument.Load(#"\\SERVERB\Folder\configurationFile.exe.config");
So, my exception is here, when I try to open that configuration file, I'm getting the exception:
Access to the path '\\SERVERB\Folder\configurationFile.exe.config' is denied
As you could see, I'm impersonating the user before I try to read the file, that impersonation is well done; and I already gave full access to the shared resource to the user that I'm impersonating with. I even tryied joining that user to the Administrators group on both Servers (A and B) and the same exception occurs.
Maybe worth to say that both Servers are on the same Windows Domain, and that I'm using a user account that exists on the domain and that the password is correct.
Any help you could give me would be appreciate.
Thanks in advance.

There is a solution to your problem already on StackOverFlow
Check it out!

Related

saving word document as pdf using Interop results in COMException: command failed

I have an ASP.NET MVC app which application pool is configured to run as a custom identity account, for example, MyDomain\MyUser.
I have a problem when creating a pdf file from a word docx file: I get a "COMException command failed" when trying to save file as pdf to a temporary folder within app folder: C:\inetpub\wwwroot\MyAspNetMvcApp\Data\Documents\Temp
I have added the application pool custom identity account (MyDomain\MyUser) to the app folder with full control permissions but it does not work, there is no way to save pdf into app folder.
I have debugged it using process monitor on the server to handle incomings file system events from app folder, and I can see that when using SaveAs2 method provided from Interop, WINWORD.EXE on the server is called/executed but using the domain user account that is logged in the client machine instead of using the application pool custom identity account (MyDomain\MyUser), so when trying to write the new pdf file to C:\inetpub\wwwroot\MyAspNetMvcApp\Data\Documents\Temp the exception "COMException command failed" is thrown because it has no rights to write there.
I have set Identity as "The interactive user" for Microsoft Word DCOM Component.
Since application pool custom identity account has rights to write to that app folder, how can I force to execute Interop SaveAs2 method using the application pool custom identity account?
Below the code snippet:
public void ConvertToPDF(string myDocFile)
{
// myDocFile contains "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myDocxFile.docx"
Document myDoc = GetMyDoc(myDocFile);
string myPdfFile = Path.Combine(Path.GetDirectoryName(myDocFile), Path.GetFileNameWithoutExtension(myDocFile) + ".pdf");
// myPdfFile now contains: "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myPdfFile.pdf"
// How can I force below SaveAs2 method to execute using the application pool custom account (the same account which runs w3wp.exe)?
myDoc.SaveAs2(myPdfFile, WdSaveFormat.wdFormatPDF); // <--- HERE IT CRASHES: COMException command failed!!
...
}
public Document GetMyDoc(object docfile)
{
// docFile contains "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myDocxFile.docx"
Application wApp = new Microsoft.Office.Interop.Word.Application();
Document myDoc = wApp.Documents.Open(ref docFile);
return myDoc;
}

Azure Cloud Service - Configure Session from RoleEnvironment

Our application is hosted as a Cloud Service in Azure and we have all our connection strings and other connection-like settings defined in the ServiceConfiguration files. We are also using a Redis Cache as the session state store. We are trying to specify the Redis Cache host and access key in the ServiceConfig and then use those values for the deployment depending on where the bits land. The problem is session is defined in the web.config and we can't pull RoleEnvironment settings into the web.config.
We tried altering the web.config in the Application_Startup method but get errors that access is denied to the web.config on startup, which makes sense.
We don't really want to write deployment scripts to give the Network Service user access to the web.config.
Is there a way to setup session to use a different Redis Cache at runtime of the application?
The error that we are getting is "Access to the path 'E:\sitesroot\0\web.config' is denied'. I read an article that gave some examples on how to give the Network Service user access to the web.config as part of the role starting process and did that and then now we have access to the file but now get the following error "Unable to save config to file 'E:\sitesroot\0\web.config'."
We ended up being able to solve this using the ServerManager API in the WebRole.OnStart method. We did something like this:
using (var server = new ServerManager())
{
try
{
Site site = server.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_Web"];
string physicalPath = site.Applications["/"].VirtualDirectories["/"].PhysicalPath;
string webConfigPath = Path.Combine(physicalPath, "web.config");
var doc = System.Xml.Linq.XDocument.Load(webConfigPath);
var redisCacheProviderSettings = doc.Descendants("sessionState").Single().Descendants("providers").Single().Descendants("add").Single();
redisCacheProviderSettings.SetAttributeValue("host", RoleEnvironment.GetConfigurationSettingValue("SessionRedisCacheHost"));
redisCacheProviderSettings.SetAttributeValue("accessKey", RoleEnvironment.GetConfigurationSettingValue("SessionRedisCacheAccessKey"));
redisCacheProviderSettings.SetAttributeValue("ssl", "true");
redisCacheProviderSettings.SetAttributeValue("throwOnError", "false");
doc.Save(webConfigPath);
}
catch (Exception ex)
{
// Log error
}
}

facing error while uploading file in mvc5 on server

I have MVC5 application , where I need to upload file excel and then then create data table of this excel. I use devexpress control to upload file. I use following code to store uploded file and then read in datatable and then store in database.
if (e.UploadedFile.IsValid)
{
e.UploadedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/" + e.UploadedFile.FileName));
var Filepath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/" + e.UploadedFile.FileName));
DataTable dtReport = new DataTable();
try
{
dtReport = CreateDataTableFromExcelFile(Filepath, "A1:U", true, "Sheet1").Tables[0];
}
catch
{
}
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
System.Data.SqlClient.SqlBulkCopy sqlcopy = new System.Data.SqlClient.SqlBulkCopy(con);
sqlcopy.DestinationTableName = "table_Name";
sqlcopy.WriteToServer(dtReport);
con.Close();
If I host this application on IIS on my machine then it works fine. But If I host it on another server then it shows error
Access to the path 'C:\inetpub\wwwroot\MVC_Project_v3\App_Data\UploadTemp\dxupload_19aafa62643d42418b2fe5eaadede3cfcugxrc4e.nrt.tmp' is denied.
Please suggest right solution
The credential you are using to host the WebSite (the credential you enter in the application pool identity) does not have the privilege to access that directory.
Add a valid credential here.

File.Move on client machine Asp.net MVC

Silly question but here goes...
Is it possible to write an intranet windows auth asp.net mvc app that uses File.Move to rename a file on a users machine? Or will the File.Move and using Path.GetDirectory and other System.IO functions look on the IIS server directory structure instead of the client machine?
[HttpPost]
public ActionResult Index(HttpPostedFileBase file, string append)
{
try
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
DirectoryInfo filepath = new DirectoryInfo(file.FileName);
string parentpath = Path.GetDirectoryName(filepath.FullName);
DirectoryInfo searchablePath = new DirectoryInfo(parentpath);
var directories = searchablePath.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo d in directories)
{
if (!string.IsNullOrEmpty(append) && !d.Name.Contains(append))
{
string fName = Path.GetFileNameWithoutExtension(d.Name);
string fExt = Path.GetExtension(d.Name);
System.IO.File.Move(d.FullName, Path.Combine(d.DirectoryName, fName + append + fExt));
}
}
}
}
catch (Exception ex)
{
}
return View();
}
I have tried this but am getting a filenotfoundexception.
Any ideas?
The ASP.NET code runs on the server, so it will look at the files on the server.
You can't rename a file on the client machine, however it would be possible to rename a file on the computer that is used as client, if:
the server and computer are on the same network
the server knows the name of the computer
the server knows which folder to look for in the computer
the folder is shared with the user account running the ASP.NET code on the server with enough privileges to change the name of a file
In that sense the computer is not a client to the server, but the server communicates directly with the computer via the file system, not via IIS.
These will indeed work only on the server.
You may look at the various file and filesystem related specifications for client-side javascript APIs provided by the user's browser:
http://www.w3.org/TR/FileAPI/
http://www.w3.org/TR/file-system-api/
http://www.w3.org/TR/file-writer-api/

Am I doing this wrong or do I need to ask my hosting service to change permissions?

I am attempting to upload files to my server using ASP.NET MVC. Here is the code that handles the upload request:
foreach (string file in Request.Files)
{
var hpf = Request.Files[file];
if (hpf.ContentLength == 0)
{
continue;
}
var savedFileName = Path.Combine(#"~/uploads", Path.GetFileName(hpf.FileName));
hpf.SaveAs(Server.MapPath(savedFileName));
}
I keep getting this error:
Access to the path 'C:\HostingSpaces\andersle\anders-leet.com\wwwroot\uploads\{filename}' is denied.
I set the permissions of the upload folder to 777, so from that end it should be OK. Would I have to talk to my hosting company about other permissions (since this is ASP.NET)?
Or is my upload logic completely wrong?
Thanks!
Should it not be
var savedFileName = Path.Combine(#"~/uploads/", Path.GetFileName(hpf.FileName));
See the extra / after uploads.. or is this something I have missed!
Another thought do you have impersonation switched on as your FTP user?
Turns out I have to change the permissions from my control panel rather than my FTP client. It is now working.

Resources