Use external xml file after publishing the c# desktop application - c#

I have developed a c# desktop application that needs to be hosted on a server and will be scheduled to fetch data based on queries stored in XML files. while developing, I was using the following code to read XML files:
var query = new XPathDocument(#"C:\\Documents and Settings\\XYZ\\Desktop\\productplanningquery.xml");
as you can see I had put the XML file conveniently on my desktop and it worked fine while development. What I want to do now, is to give at a path such that where ever I host the application plus the XML files, it does not throw an exception. One way i thought could be to have a folder in a directory where the application will be installed but for that i will have to figure out the path to current directory dynamically (which i could not figure out).
Please help.

You could pass the location of you XML using args this way you're code would look like so:
var query = new XPathDocument(args[0])
You can also use relative path. Make sure that when deploying your code you keep the location of the file in the same relative location. For example if you place the XML in the same directory as the application
var query = new XPathDocument("productplanningquery.xml")

I am not sure what you want to achieve whether you want to read xml using winform app and do some operation and then pass it web app or some thing else. But here is my understandings:
Case 1: If you need to create XML outside the IIS and that XML will be consumed by ASP.Net app, then :
For using a desktop application with IIS server , you need to have full administrative access to the Live Machine. If its not then you should consider building windows services to operate on the XML files or any task that will run behind the scenes to decrease the load of the asp.net app.
Still in this case if you dont own a server then you need some Virtual Private Hosting or similar kind of hosting where you have almost all previleges to access the system. Then deploy the Windows Service, set the output path in such a manner so that it can be accessed by asp.net app too. And do whatever you want.
Case 2: If you want o read XML in ASP.Net Solely, then
In this case you case read it easily by using XDocument.But note, XML should in the same application directory or under the reach of the ASP.Net app
MSDN Article for Web-Windows Services with ASP.Net

You can use something like this:
var path = string.Format("{0}\\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "productplanningquery.xml");
var pathForCurrentApp = string.Format("{0}\\{1}", Environment.CurrentDirectory, "productplanningquery.xml");

Related

Converting docx to html with dotnet-mammoth fails at deploy server

I'm using dotnet-mammoth (mammoth.js with edge.js) to convert a docx document to html in .net
I added it to my project via its nuget package.
I'm using the code provided by the sample, which is working correctly in my development enviroment (running IIS Express):
var documentConverter = new Mammoth.DocumentConverter();
var result = documentConverter.ConvertToHtml(Server.MapPath("~/files/document.docx")); // problem here at production enviroment
string theResult = result.Value
However, once I deploy it to production server, when the executed code reaches documentConverter.ConvertToHtml() method, it's redirecting me to the login page. Without displaying any error messages, without saving anything on IIS log file.
If I remove that line, everything else executes normally.
I assume it could be an issue related to permissions but I don't know what could it be. Any ideas?
The latest version of Mammoth on NuGet no longer uses edge.js, and is now just .NET code, so should work more reliably.
You can resolve this by getting the exact error when the process is trying to read the file. Below is the code from dotnet-mammoth DocumentConverter.cs. As shown below on call it is trying to read all bytes to be sent to edge
public Result<string> ConvertToHtml(string path)
{
var mammothJs = ReadResource("Mammoth.mammoth.browser.js") + ReadResource("Mammoth.mammoth.edge.js");
var f = Edge.Func(mammothJs);
var result = f(File.ReadAllBytes(path));
Task.WaitAll(result);
return ReadResult(result.Result);
}
I suppose you are giving absolute path to the input. In that case the absolute path should be accessible by app identity hosting the app pool of the web application.
If the path specified is in web root directory - (not advised) - but if it is then you can use Server.MapPath

Denied acces to a file

I have a code which is similar this:
string file;
using (StreamReader r = new StreamReader("xml.xml"))
{
file = r.ReadToEnd();
}
XElement xml = XElement.Parse(file);
using (XmlWriter w = XmlWriter.Create("xml.xml")) //The point of problem!
{
w.WriteStartDocument();
...;
w.WriteEndDocument();
}
When I try run it like a console application is everything all right. But problems start when I want to use it in an ASP.NET application. At the using line it throws UnauthorizedAccessException exception with a description "access to the path is denied". Why?
You need to check which account your application Pool is using to access your server files/folders, for example, make one code to copy one file to application folder, check all security info, copy and paste on this problem folder, normally use this account "IIS_IURRS" give full control to test only...
If IIS/the web server is configured correctly, an account with a very limited set of permissions is used. As your path points to the application directory, it is very likely that the application pool account is not allowed to write to this location.
If you run the code in a console application, your user's permissions are applied and it is more than likely that you are allowed to write to the output folder of the project as Visual Studio writes the build output there under your account.
I would not recommend to change the application pool account or the permissions of the application folder in the file system - it is a very sensible limitation that limits the amount of trouble an attacker can possibly make.
Therefore I'd recommend to either move the file to a folder that the account can write to without changing permissions or define a special one outside of the application folder hierarchy that the account is given permissions to.
Also keep in mind that multiple users might access the file at the same time, so a database might be a better choice to store the data.

How to get path to file in winforms application

How can I get the path of a file on my computer or on the local area network.
I would to show a window that allows me to browse the file system when I click a button, and I want to select a file and get the path to the file. How can I do this?
P.S. I'm not looking to upload the file; I just want to get the path.
The web application is running on the server, and you don't have access to the client file system at all. Can you imagine how much of a vulnerability that would be? I know I don't want the sites I visit inspecting my file system...
EDIT: Question is for a WinForms application
For a WinForms application, you can use the OpenFileDialog, and extract the path with something like this:
If you're looking for the file path:
string path = OpenFileDialog1.FileName; //output = c:\folder\file.txt
If you're looking for the directory path:
string path = Path.GetDirectoryName(OpenFileDialog1.FileName); //output = c:\folder
In general, the System.IO.Path class has a lot of useful features for retrieving and manipulating path information.
To do this in VB.NET use the FolderBrowserDialog.
Due to security restrictions browsers include for user safety, you can't manipulate the client file system directly. You can only use to let them pick a file, and even then it only sends the filename, not the whole path.
The FileSystem API in HTML5 allows for file manipulation, but only within a sandbox for your site specifically, not browsing across the network or other files on the client system.
Instead, provide your users easy steps on how they should use My Computer (or whatever equivalent on other OS's) to navigate to the file and copy & paste the path into a simple text input box.
Have you taken a look at the Path class from System.IO ?

Logging to TextFile from SharePoint

I'm trying to debug a webpart installed on a client's SharePoint instance. I wanted a quick and easy logging feature, so I thought of writing messages to a text file in the temp directory. SharePoint doesn't seem to like it, so what are my options?
IF you are writing to the temp directory, you will need to give the file (if it exists) or the directory rights for the IIS Application pool that the SharePoint IIS application is running under.
There are few ways of custom logging in sharepoint -
Use SPDiagnosticsService - You may write to the ULS via SPDiagnosticsService class.
Utilize diagnostics.asmx web service -
SharePointDiagnostics SharePointDiagnosticsObject = new SharePointDiagnostics();
SharePointDiagnosticsObject.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
string Response = SharePointDiagnosticsObject.SendClientScriptErrorReport(message, file, line, client, stack, team, originalFile);
For more details on usage of diagnostics.asmx refer the following link -
https://vivekkumar11432.wordpress.com/2016/09/23/how-to-do-logging-in-uls-from-csom-in-c/
For more details on logging refer the following link -
http://www.codeproject.com/Articles/620996/Five-suggestions-to-implement-a-better-logging-in
Don't use
Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Message");
According to Microsoft documentation - LogString is reserved for internal use and is not intended to be used directly from your code.
I would guess that this is a permissions issue that SharePoint is blocking you on (and probably not telling you that it is). When you try to write to a text file on the server, you need to have elevated permissions in order to do it. You can accomplish this using SPSecurity.RunWithElevatedPrivileges. Something like the following, if you want just a simple, small-code solution.
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (StreamWriter sw = new StreamWriter(#"C:\log.txt"))
{
//log information here
}
});
Try a logging framework like log4net, or write a small logging framework writing into an external database, you could also use lists to log if you want to stay inside sharepoint

how to get the path for executable file that started the application?

i am working on a web application using C#,
i know that in window application how to give the path for executable file that started the application (if (!System.IO.File.Exists(Application.StartupPath + "\gsdll32.dll")))
but i dont know how to give that path in web application using c#
please help me .
In ASP.NET you use the MapPath method:
var siteRootPath = Server.MapPath("~/");
Yet another possibility is to use the ApplicationPhysicalPath static property:
var path = HostingEnvironment.ApplicationPhysicalPath;
First thing you cannot run your executable from client end. It has to be a server side code which would run on server and for this you can use the similar logic.

Categories

Resources