facing error while uploading file in mvc5 on server - asp.net-mvc

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.

Related

Save file to path desktop for current user

I have a project ASP.NET Core 2.0 MVC running on IIS.
Want to Export some information from data grid to Excel and save it from web page to the desktop of current user.
string fileName = "SN-export-" + DateTime.Now + ".xlsx";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
fileName = rgx.Replace(fileName, ".");
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName2 = Path.Combine(path, fileName);
FileInfo excelFile = new FileInfo(fileName2);
excel.SaveAs(excelFile);
This works perfect local at Visual Studio, but not after publishing at IIS.
Using simple path string path = #"C:\WINDOWS\TEMP"; It will save this export file at the server temp folder, but not current web page user.
How to get this?
ASP.NET MVC is framework for a web application. So you have fronted and backend parts. This code will executed on the server side of your application. Even if you use Razor pages, they also generated at the backend. So there are several ways to save data on the computer:
use js to iterate data and save it, but I'm not sure that saving to excel with js is easy;
send desired data to backend, save it to excel and then return to the client.
For a second way you can use next code:
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(YourData data) {
Stream stream = await {{__get_stream_based_on_your_data__}}
if(stream == null)
return NotFound();
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
And because of security reasons you can save data only to downloads directory.

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
}
}

Get Error (error=access_denied) while logging in MVC5 application with facebook SDK

I have developed an application with ASP.NET MVC5. I have used Facebook external authentication in my application.
When I debug this application with the "Locallhost" domain, the Facebook login works well but when I publish the application in the main server,the AuthenticationManager.GetExternalLoginInfo() returns null and it gives me an error like this in the url:
http://xxxxx.com/Account/ExternalLoginCallback?ReturnUrl=%2Fen&error=access_denied#_=_
I have set the "Site URL" as "http://xxxx.com" and "Valid OAuth redirect URIs" as "http://xxxx.com/signin-facebook" in the Facebook development console.
My setting in the Startup.Outh.cs file is:
var FacebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions();
FacebookOptions.AppId = ConfigurationManager.AppSettings["Facebook_User_Key"];
FacebookOptions.AppSecret = ConfigurationManager.AppSettings["Facebook_Secret_Key"];
FacebookOptions.Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
};
FacebookOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseFacebookAuthentication(FacebookOptions);
I don't know why the external login does not work only in the server with my main domain name. please help me about this problem.
I encountered pretty much the same symptoms you describe:
shortly:
A Facebook authentication worked well on localhost, and after uploading the project to another server (and changing the site URL on Facebook console), authentication did not succeed.
I would recommend you roll back to the MVC template code, and if that works - notice any changes you have made to the middleware code (Startup.Auth.sc).
In particular pay attention to code that interacts with LOCAL configuration, such as Disk I/O and OS permissions for local services.
My particular case:
Starting from the Owin/Katana supported Visual Studio template of a WebAPI project, external login was working perfectly with Facebook, Microsoft and Google OAuth middleware, when testing on localhost.
Later I added come code to Startup.Auth.sc because I needed further authentication activity.
So this was the original code:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(
appId: 99999999,
appSecret: *******);
}
and this was replacement:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(GetFacebookAuth());
}
private FacebookAuthenticationOptions GetFacebookAuth()
{
string picRequest =
String.Format("/me/picture?redirect=false&width={0}&height={0}", ProfileInfoClaimsModel.PIC_SIDE_PX);
var facebookProvider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async (context) =>
{
var client = new FacebookClient(context.AccessToken);
dynamic me = client.Get("/me?fields=id,name,locale");
dynamic mePicture = client.Get(picRequest);
// storing temporary social profile info TO A LOCAL FOLDER
// uploading the local folder to a service WITH A LOCAL CREDENTIAL FILE
...
}
};
var options = new FacebookAuthenticationOptions()
{
AppId = 0123456789,
AppSecret = ******,
Provider = facebookProvider,
};
return options;
}
You may notice that my comments will make the problem obvious - the code points to local resources.
Then I published the project to a virtual server (by Amazon EC2) running Windows Server 2012 with IIS 8.5.
From that moment I kept getting error=access_denied in the redirect from /signin-facebook.
I decided to follow this good old concept, and go back to the original template code. Pretty soon I figured out that I forgot to configure the new server. For instance, the folder the code refers to did not exist and the site had no permission to create it.
Obviously, that solved it.

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/

Access to the path denied, trying to access remote server file

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!

Resources