XML does not get saved in asp.net - asp.net

I have a problem saving my xml-file.
i use this XMLwriter :
using (XmlWriter writer = XmlWriter.Create("CarsXML.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("CarsXml");
foreach (Car item in cars)
{
writer.WriteStartElement("Car");
writer.WriteElementString("Brand", item.Brand);
writer.WriteElementString("Type", item.Type);
writer.WriteElementString("Price", item.Price);
writer.WriteElementString("Effect", item.Effect);
writer.WriteElementString("Year", item.year);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}
Seems ok right? No compile errors..
I´ve also tried this just for testing :
XDocument doc = new XDocument(
new XElement("Root",
new XElement("Child", "content")
)
);
doc.Save("Root.xml");
Still no luck.. `ve trid this in a console app, and it works so the code must be fine..
I´ve also tried with a piece of code i found somewhere - using XmlDocument instead - but its the same deal.
What am i doing wrong?

When you are in a web application, the current directory is not the root directory of the web application. It's the directory where the IIS executable is, so that's somewhere in the Windows system directories.
Naturally you don't have write access to that directory from the web application, so you get some exception when you try to create a file there.
Specify the full path of the file that you want to create. You can use the MapPath method to get the physical path to a file from a virtual path. Example:
string fileName = Server.MapPath("/xmldata/CarsXML.xml");
using (XmlWriter writer = XmlWriter.Create(fileName))
...

Related

What is the path of the Json file in Android at Xamarin.Forms?

I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.
\MyApp\MyApp.Android\JsonData\Setting.json
In the properties, we set the Copy when new.
The following folders in the local environment contain the files.
\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json
I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.
Could not find a part of the path "/JsonData/Setting.json."
Try
{
var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
var error = exception.Message;
}
What is the path of the file in Android?
I think you're using File Handling in Xamarin.Forms incorrectly.
From the parameter of function File.ReadAllText, the app will access the file system to getSetting.json from folder JsonData in your android device.
The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
And you can read the file by code:
string text = File.ReadAllText(fileName);
In addition, from your code,I guess you want to Load your Embedded file( Setting.json) as Resources,right?
In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.
And GetManifestResourceStream is used to access the embedded file using its Resource ID.
You can refer to the following code:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd ();
}
For more , you can check document : File Handling in Xamarin.Forms.
And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .

FailedToExecuteCommand ghostscript gswin64c.exe on azure

I am trying to convert pdf into images using magickNET and ghostscript. It works well on local and windows VMS servers. But when i push to azure servers it gives me the error saying FailedToExecuteCommand ghostscript gswin64c.exe. Details of error in attachements.
I tried changing the path for ghostscript dll but found no luck. The path is correct and dll file is there. One thing I am sure of. I have put dll inside wwwroot/GhostScriptDll. on error it shows "D:/home/site/wwwroot/wwwroot/GhostScriptDll/gswin64c.exe" which is also correct there are 2's wwwroot.
can someone help me to use ghostscript without webjobs things.
C# code i tried is like this
enter image description here
string rawpath = _hostingEnvironment.WebRootPath + "\\GhostScriptDll"
MagickNET.SetGhostscriptDirectory(rawpath);
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new Density(300, 300);
List<string> intList = new List<string>() { };
using (MagickImageCollection images = new MagickImageCollection())
{
images.Read($"{rawFileLocation}{model.OriginalDocName}", settings);
int page = 1;
string tempName = "";
foreach (MagickImage image in images)
{
tempName = System.IO.Path.GetRandomFileName().Replace(".", string.Empty) + "_processed_" + page + ".png";
image.Write($"{processedFileLocation}{tempName}");
intList.Add(tempName);
page++;
}
}
i doubt in this part of error D:/local/Temp/magick-MB0cs71xMgZUfIHIwbzlzehBIlLL-NED"' (The system cannot find the file specified.
) # error/delegate.c/ExternalDelegateCommand/475 ...i dont find the local/temp/.. folder in server though

FileUpload control in asp.net throwing exception

I am trying to read an Excel sheet using C# which is to be loaded by end user from fileUpload control.
I am writing my code to save the file on server in event handler of another button control(Upload). But when I click on Upload Button I am getting this exception:
The process cannot access the file 'E:\MyProjectName\App_Data\sampledata.xlsx' because it is being used by another process.
Here is the code that I have used in event handler:
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
Even deleting the file is not working, throwing the same exception.
Make sure, some other process is not accessing that file.
This error might occurs whenever you are trying to upload file, without explicitly removing it from memory.
So try this:
try
{
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
}
catch (Exception ex)
{
throw ex.Message;
}
finally
{
file_upload.PostedFile.InputStream.Flush();
file_upload.PostedFile.InputStream.Close();
file_upload.FileContent.Dispose();
//Release File from Memory after uploading
}
The references are hanging in memory, If you are using Visual Studio try with Clean Solution and Rebuild again, if you are in IIS, just do a recycle of your application.
To avoid this problems try to dispose the files once you used them, something like:
using(var file= new FileInfo(path))
{
//use the file
//it will be automatically disposed after use
}
If i have understood the scenario properly.
For Upload control, I don't think you have to write code for Upload Button. When you click on your button,your upload control has locked the file and using it so it is already used by one process. Code written for button will be another process.
Prior to this, check whether your file is not opened anywhere and pending for edit.

c:\windows\system32\inetsrv\Test.pdf is denied

I have a requirement to generate a pdf document on a button click on using visual web part- sharepoint 2010.
I am using the the open source library http://www.itextpdf.com/ for the same. I am able to execute the below code using the project type as a Windowns Application. But, when I want do it on a button click , I am receiving c:\windows\system32\inetsrv\Test.pdf' is denied. error.
Below is the code that I am using
public static void Main(string[] args) --Console Application
{
Console.WriteLine("PDF demo");
Document myDoc = new Document(PageSize.A4.Rotate());
try
{
PdfWriter.GetInstance(myDoc, new FileStream("Salman.pdf", FileMode.Create));
myDoc.Open();
myDoc.Add(new Paragraph("First pdf File made by Salman using Itext"));
}
catch (DocumentException ex)
{
Console.Error.WriteLine(ex.Message);
}
myDoc.Close();
}
}
But I want do the same on a button click event.
protected void pdfGenerator_OnClick(object sender, EventArgs e)
{
Document myDoc = new Document(PageSize.A4.Rotate());
try
{
PdfWriter.GetInstance(myDoc, new FileStream("Salman.pdf", FileMode.Create));---I get an error here
myDoc.Open();
myDoc.Add(new Paragraph("First pdf File made by Salman using Itext"));
}
catch (DocumentException ex)
{
Console.Error.WriteLine(ex.Message);
}
myDoc.Close();
}
}
Please help me , i dont understand the reason for the error. I am tyring it for the first time.
The problem is you are trying to create a PDF in a directory you do not have access to. This is because you are not specifying the directory to save the path; which causes it to default in the same location as the current working directory. In many cases, such as for ASP.NET; the default is the same as the location of the process. For ASP.NET, the process is w3wp.exe and resides in c:\windows\system32\inetsrv. Most identities that w3wp will run as (Network Service or AppPoolIdentity) do not have access to that directory. In fact, only system administrators do.
You need to save it somewhere else that the process has write permissions to here:
PdfWriter.GetInstance(myDoc, new FileStream("Janaki.pdf", FileMode.Create))
Should be something like:
PdfWriter.GetInstance(myDoc, new FileStream(#"C:\directoryIcanWriteTo\Janaki.pdf", FileMode.Create))
If you want to save it in the same place as the website, you would use HttpContext.Current.Server.MapPath:
PdfWriter.GetInstance(myDoc, new FileStream(HttpContext.Current.Server.MapPath("~/Janaki.pdf", FileMode.Create))
Regardless, the identity will still need write permissions to the directory if it doesn't have them. But you definitely shouldn't put them in inetsrv.
Just don't use "FileStream" which requires write permissions on the server. Replace it with MemoryStream and then flush its content on the user's browser.

FileUpload problem with Struts on server

I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.

Resources