How to save the file to a specific folder (Network Drive or local folder) on a client machine? - asp.net-mvc

I have an asp.net web app which is published as an Azure cloud service.The application downloads the files from the server and saves it locally on the client machine.However,It does not seem to work when published as a cloud service.It works fine when published locally using IIS.
The code below is the where the file gets saved.
foreach (var item in userids)
{
//item.contractorpath= user filepath(client machine path eg, C:\test\)
string filePath =
Path.Combine(Server.MapPath("~/Content/Downloads"),
SessionInfo.CompanyId.ToString(), "Bill",
item.ContractorId.ToString());
if (Directory.Exists(filePath))
{
//System.IO.Directory.CreateDirectory(filePath);
DirectoryInfo di = new DirectoryInfo(filePath);
FileInfo[] TXTFiles = di.GetFiles("*.pdf");
if (TXTFiles.Length > 0)
{
foreach (FileInfo file in TXTFiles)
{
string fileName = file.Name;
if (!Directory.Exists(item.FolderPath))
{
System.IO.Directory.CreateDirectory(item.FolderPath);
}
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(Path.Combine(filePath, file.Name), Path.Combine(item.FolderPath, file.Name));
System.IO.File.Delete(Path.Combine(filePath, file.Name));
}
}
}
}
}

Related

Report Server authentication in .net core 2.1 linux container

I am migrating a .net core 2.1 app from windows server to linux container. It uses SQL Server 2008 report server.
The old app version is running on IIS (windows server), application pool with identity configured (active directory user).
The new app version is running on an alpine container using kestrel .net core server standalone, no identity configured.
When the app tries to reach SQL Server 2008 report server there is an error:
LoadReport error: One or more errors occured. (NTLM authentication is not possible with default credentials on this platform.)
How can I configure credentials (username and password)(same one set in my old application pool) in my new app based on linux container?
Part of my appsettings.json:
"Reporting": {
"ServerUrl": "http://myserver/ReportServer",
"ReportPath": "/Folder/Reports/"
},
Part of the source code:
private ServerReport PrepararRelatorio()
{
ReportSettings settings = new ReportSettings
{
ReportServer = this.configuration["Reporting:ServerUrl"]
};
ServerReport serverReport = new ServerReport(settings);
return serverReport;
}
protected FileContentResult CarregarRelatorio(
string nomeRelatorio,
string extensao,
Dictionary<string,string> parametros)
{
var renderType = this.ObterTipoRenderizacao(extensao);
if (ReportRenderType.Null.Equals(renderType))
{
throw new BusinessException("Erro ao definir o tipo do arquivo a ser exportado.");
}
ServerReport serverReport = this.PrepararRelatorio();
ReportRequest request = new ReportRequest
{
RenderType = renderType,
Path = this.configuration["Reporting:ReportPath"] + nomeRelatorio,
Name = nomeRelatorio,
ExecuteType = ReportExecuteType.Export,
Parameters = parametros
};
ReportResponse response = serverReport.Execute(request);
if (response.Status != 0)
{
throw new BusinessException(response.Message);
}
return File(response.Data.Stream, response.Data.MimeType, nomeRelatorio + "." + extensao);
}
Microsoft don't provide support for .NET Core/.NET 5, since the SSRS
library is intricately linked with WebForms, which are no longer
supported.
Refer this link
Usually, we use NetworkCredential option to pass username and password while in ASP.NET MVC.
You can able to supply report server's username and password to ReportSettings.Credential as shown in below.
Configuration:
"Reporting": {
"ServerUrl": "http://myserver/ReportServer",
"ReportPath": "/Folder/Reports/",
"UserName": "xxxxxx",
"Password": "yyyyyy"
},
Source Code:
private ServerReport PrepararRelatorio()
{
ReportSettings settings = new ReportSettings
{
ReportServer = this.configuration["Reporting:ServerUrl"],
Credential = NetworkCredential(this.configuration["Reporting:UserName"], this.configuration["Reporting:Password"])
};
ServerReport serverReport = new ServerReport(settings);
return serverReport;
}

why asp.net mvc does not include the image uploaded folder in the project?

what I have found that the images uploaded by my application are not included in the project and that I have to include them manually image by image so what is the correct way of asp.net mvc project to let the images uploaded to be included in the project.
The following code is the one that upload the images to the folder and creates a unique name for each image. but still those images are not included in the project explorer.
public ActionResult Create(Job job, HttpPostedFileBase JobImage)
{
var value = "999999999";
var result4 = from app in db.Job where app.UniqueJobImageName.Contains(value) select app;
if(result4.FirstOrDefault() != null)
{
value = generateRandom();
}
if (ModelState.IsValid && CheckFileType(JobImage.FileName))
{
string ext = Path.GetExtension(JobImage.FileName);
var fileName = Path.GetFileName(JobImage.FileName);
job.JobImage = JobImage.FileName;
job.UniqueJobImageName = value + ext;
var path = Path.Combine(Server.MapPath("~/Images"), value + ext);
JobImage.SaveAs(path);
job.UserId = User.Identity.GetUserId();
job.jobUrl = "";
job.Month = DateTime.Now.ToString("MMMM");
job.DateAndTime = DateTime.Now;
AllJobModel all = new AllJobModel
{
JobTitle = job.JobTitle,
JobDescription = job.JobDescription,
JobImage = job.JobImage,
UniqueJobImageName = job.UniqueJobImageName,
locationName = job.locationName,
minimumSalary = job.minimumSalary.ToString(),
maximumSalary = job.maximumSalary.ToString(),
jobUrl = job.jobUrl,
PostedDate = DateTime.Now.ToString("dd/MM/yyyy"),
UserId= User.Identity.GetUserId(),
};
db.AllJobModel.Add(all);
db.SaveChanges();
db.Job.Add(job);
db.SaveChanges();
return RedirectToAction("Index","Home");
}else if (!CheckFileType(JobImage.FileName))
{
}
return View(job);
}
enter image description here
This doesn't make any sense. The uploaded images are content created by the user. They are not a deployable component of the site (or, they shouldn't be anyway). They are user-generated content, not developer resources.
If you are looking to effectively migrate your data (i.e. copy database entries and other user-generated content such as image files) from one environment to another, then that is a separate task for which you can create a separate process and/or automated script. Don't confuse it with the job of uploading a new version of your application code.
P.S. Even if what you were asking for was a sensible goal, it's impossible anyway - the executable version of your code is not the same as the code you see in Visual Studio in your project. In a modern ASP.NET application the executable code is in a different folder (even when you're running in debug mode in Visual Studio) and it has no concept or knowledge of the original project it was compiled from, or where to find it, or how to interact with it.

Messages not rendered when a pst is created from email messages located in another machine on a same network

I am creating a pst from message files which are located in another machine on a same network. But when I loaded the pst, messages are not rendered. I have added a screenshot. And code is below:
Issue do not occur when message files are imported from my local machine.
private static void GeneratePST(string [] messageFiles, string outputPstPath)
{
RDOSession pstSession = null;
RDOPstStore store = null;
RDOFolder folder = null;
RDOMail rdo_Mail = null;
RDOItems items = null;
try
{
pstSession = new RDOSession();
store = pstSession.LogonPstStore(outputPstPath, 1, Path.GetFileNameWithoutExtension(outputPstPath));
folder = store.IPMRootFolder;
folder = folder.Folders.Add("Loose Messages");
foreach (string messages in messageFiles)
{
items = folder.Items;
rdo_Mail = items.Add("IPM.NOTE");
rdo_Mail.Import(messages, rdoSaveAsType.olMSG);
rdo_Mail.Save();
}
}
catch (Exception ex)
{
//log exception
}
finally
{
Marshal.ReleaseComObject(rdo_Mail);
Marshal.ReleaseComObject(folder);
Marshal.ReleaseComObject(store);
Marshal.ReleaseComObject(items);
pstSession.Logoff();
Marshal.ReleaseComObject(pstSession);
GC.Collect();
}
}
I have also impersonated the network machine before importing message file. But still the issue persist.
The problem only exists for files in another machine. Messages are rendered for msg file located in my machine. Also, I noticed issue is only with message files. Eml file are rendered. So, it might not be the issue of impersonation.
Any help please.
Microsoft does not support accessing PST files on network drives. They must be on a local machine.
Also, there is no reason to continuously retrieve the RDOItems object - you never release on the old value, so those objects stay alive until your app exits. Ditto for the rdo_Mail object:
folder = folder.Folders.Add("Loose Messages");
items = folder.Items;
foreach (string messages in messageFiles)
{
if (rdo_Mail != null) Marshal.ReleaseComObject(rdo_Mail);
rdo_Mail = items.Add("IPM.NOTE");
rdo_Mail.Import(messages, rdoSaveAsType.olMSG);
rdo_Mail.Save();
}

Upload and access to images on server with nginx and meteor

I have a Meteor application deployed with nginx.
I try to upload images from the application to save the images on the server. When I'm in localhost, I save my images in the myapp/public/uploads folder. But, when I deploy, this folder become myapp/bundle/programs/web.browser/app/uploads. So, when I upload an image, it saved in a new folder in myapp/public/uploads. But so, I can't access to it. When I'm in localhost I access to my images like that : localhost:3000/uploads/myImage.png but when I do myAdress/uploads/myImage.png I access to the myapp/bundle/programs/web.browser/app/uploads folder and not the one where the images are saved (myapp/public/uploads).
This is my code to save images :
Meteor.startup(function () {
UploadServer.init({
tmpDir: process.env.PWD + '/app/uploads',
uploadDir: process.env.PWD + '/app/uploads',
checkCreateDirectories: true,
uploadUrl: '/upload',
// *** For renaming files on server
getFileName: function(file, formData) {
//CurrentUserId is a variable passed from publications.js
var name = file.name;
name = name.replace(/\s/g, '');
return currentTileId + "_" + name;
},
finished: function(fileInfo, formFields) {
var name = fileInfo.name;
name = name.replace(/\s/g, '');
insertionImages(name, currentTileId, docId);
},
});
});
So, do you know how can I do to save and access to my images when the application is deployed ? Maybe save the image in the myapp/bundle/programs/web.browser/app/uploads folder or access to the myapp/public/uploads folder with an url.
This is what we do.
Use an external dir for uploads, say, /var/uploads. Keeping the uploads in public folder makes the meteor app to reload in the dev environment, on any file upload.
Now, at local, use Meteor to serve these files at a certain url. In production, use nginx to serve the same at the same url.
For Development
1) Symlink your upload dir to a hidden folder in public.
eg:
ln -s /var/uploads /path/to/public/.#static
2) Serve the public hidden folder via Meteor by using:
The url /static will server the folder public/.#static by using the following code on the server. Ref: How to prevent Meteor from watching files?
var fs = require('fs'), mime = require('mime');
WebApp.rawConnectHandlers.use(function(req, res, next) {
var data, filePath, re, type;
re = /^\/static\/(.*)$/.exec(req.url);
if (re !== null) {
filePath = process.env.PWD + '/public/.#static/' + re[1];
try {
stats = fs.lstatSync(filePath);
if (stats.isFile()) {
type = mime.lookup(filePath);
data = fs.readFileSync(filePath, data);
res.writeHead(200, {
'Content-Type': type
});
res.write(data);
res.end();
}
}
catch (e) {
// console.error(filePath, "not found", e); // eslint-disable-line no-console
next();
}
}
else {
next();
}
});
For production
1) Use nginx for serving the upload dir
server {
...
location /static/ {
root /var/uploads;
}
...
}
That's it. /static will server the content of your uploads dir i.e. /var/uploads

Xamarin.iOS: Saving files to windows shared folder

I have an iOS app written using Xamarin. Is there a way to save some file (in my case Image) to a shared folder on Windows PC? iOS device and PC are in the same WiFi network, so I can get access to PC machine by IP address. But how can I save a file to that shared folder?
If that is possible I would be grateful for some code example.
Are you try SharpCifs.Std?
NuGet Package is here.
drives SMB on Xamarin.iOS, like this.
var file = new SmbFile("smb://UserName:Password#ServerName/ShareName/Folder/NewFileName.txt"));
file.CreateNewFile();
var writeStream = file.GetOutputStream();
writeStream.Write(Encoding.UTF8.GetBytes("Hello!"));
In my Xamarin application (on iPad Pro 12.9") I kind of worked around this problem by activating FTP on my Windows10 machine (see Google how to do this) and then uploaded the image to the Windows folder via FTP:
private void UploadImage(UIImage image, string fileName)
{
try
{
string ftpPath = "ftp://192.168.47.79/"; // IP of my Windows10 pc
string ftpTargetFilePath = $"{ftpPath}{fileName}";
var credentials = new NetworkCredential("ftpuser", "ftp");
FtpWebRequest request = (FtpWebRequest) WebRequest.Create(ftpTargetFilePath);
request.Credentials = credentials;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false; // in my case I needed passive mode to be deactivated
using (Stream imageStream = image.AsPNG().AsStream())
{
using (Stream ftpStream = request.GetRequestStream())
{
imageStream.CopyTo(ftpStream);
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Uploading Image: Failed! ({ex.Message})");
}
}

Resources