File Not found in exe of wpf application - asp.net

When publishing the WPF application and generate an exe, I am unable to get the files which are placed in the templates-folder. When I copy my folder and files to bin it works, or if use
string StartUpPath = AppDomain.CurrentDomain.BaseDirectory.ToString();
// var gparent = Directory.GetParent(Directory.GetParent(Directory.GetParent(StartUpPath).ToString()).ToString()).ToString();
ReportDocument reportDocument = new ReportDocument();
StreamReader reader = new StreamReader(new FileStream(StartUpPath + #"\Templates\Invoice.xaml", FileMode.Open));
This code works fine for my local, but when I generate an exe, these files are not found.

That's because your files aren't in the exe. I had the same problem recently.
It sounds like you need to handle your resources - there are several ways to go about this, and Microsoft has a full explanation here about resources, including the difference between using Linked and Embedded Resources, and links through to other great guides.
I'm assuming you're using Visual Studio, in which case this should work;
right click the file you can't access
select properties (or press ALT + ENTER)
set Build Action to be Resource
set Copy to Output Directory to be Copy if newer
save
... and you should be good to go.

I think it throws an exception because the file doesn't exist on that machine. You can set Build Action to Content and Copy to Output Directory to Copy Always or Copy If Newer on property window.
These settings will make sure that you have the file to your output.

Related

How do I find the open folder in a VSIX extension

I'd like to write a VSIX LSP extension. I'd like this to work in the simplest possible way - that seems to be using the "Open Folder" feature to open a folder of code, and do my thing.
To start the LSP server, I need to know the directory of the opened folder. How do I know whether Visual Studio is in "open folder" mode (if it's not, the LSP should just not be started), and how do I know the path to that folder (so I can start the LSP server)?
I found https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ivssolutionevents7?view=visualstudiosdk-2017 which seems promising in that I can register for when some some specific folder is opened - an event that tells me the "open folder" functionality has been used would probably be perfect - if folder is opened, start the LSP for that folder.
The following code will get you 3 information:
// get solution reference from a service provider (package, etc.)
var solution = (IVsSolution)ServiceProvider.GetService(typeof(SVsSolution));
solution.GetSolutionInfo(out string dir, out string file, out string ops);
// dir will contain the solution's directory path (folder in the open folder case)
solution.GetProperty((int)__VSPROPID.VSPROPID_IsSolutionOpen, out object open);
bool isOpen = (bool)open; // is the solution open?
// __VSPROPID7 needs Microsoft.VisualStudio.Shell.Interop.15.0.DesignTime.dll
solution.GetProperty((int)__VSPROPID7.VSPROPID_IsInOpenFolderMode, out object folderMode);
bool isInFolderMode = (bool)folderMode; // is the solution in folder mode?

Entity Framework migration: access sql file within ASP.NET

I have a ASP.NET Web API project. I'm using Entity Framework Migrations. Currently, I have a custom script that is to be executed during a migration. I'm using the SqlFile method for this:
SqlFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Migrations/Scripts/MyCustomScript.sql"));
This works fine in the integration tests, IF I set the "Copy to Output Directory" of the script to "Copy always".
However, when running the website, the script is copied to <websiteroot>\bin\Migrations\MyCustomScript.sql, while AppDomain.CurrentDomain.BaseDirectory points to the websiteroot. Therefore, an error is thrown stating that the script cannot be found: it resides in the bin folder, not in the root.
How can I load the script so that things work both in the tests and in the actual website?
I would include the script in you dll and than load the script from the dll directly. Than you do not need any if statements and you always know you have the correct scripts included. Set the build action to Embedded resource. Then you can get the script like:
Assembly assembly = Assembly.LoadFile(dll);
using (Stream stream = assembly.GetManifestResourceStream(resourcepath))
using (StreamReader reader = new StreamReader(stream))
{
string script = reader.ReadToEnd();
I would fix it this way (it's not the best way, but it's a way)
string sqlfilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Migrations/Scripts/MyCustomScript.sql");
if (!File.Exists(sqlfilepath))
sqlfilepath = "your other path where it might exist";

How to save generated file temporarily in servlet based web application

I am trying to generate a XML file and save it in /WEB-INF/pages/.
Below is my code which uses a relative path:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).
But when deploying and running on server machine, it throws the below exception:
javax.xml.transform.TransformerException:
java.io.FileNotFoundException
C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?
Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.
Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.
Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.
Always write them to an external folder on a predefined absolute path.
Either hardcoded:
File folder = new File("/absolute/path/to/web/files");
File result = new File(folder, "filename.xml");
// ...
Or configured in one of many ways:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
Or making use of container-managed temp folder:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
Or making use of OS-managed temp folder:
File result = File.createTempFile("filename-", ".xml");
// ...
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
See also:
Recommended way to save uploaded files in a servlet application
Where to place and how to read configuration resource files in servlet based application?
Simple ways to keep data on redeployment of Java EE 7 web application
Store PDF for a limited time on app server and make it available for download
What does servletcontext.getRealPath("/") mean and when should I use it
getResourceAsStream() vs FileInputStream
just use
File relpath = new File(".\pages\");
as application cursor in default stay into web-inf folder.

Sharepoint 2010 API upload a file with metadata creating a new version from ASP.NET web application

How I can upload a file with metadata creating a new version from ASP.NET web application to SharePoint 2010?
Is there any way?
Thanks in advance.
There are multiple ways to upload a file to a document library.
Perhaps the simplest way is simply to copy the file to the document library's URL using File.Copy. SharePoint supports WebDAV so you can treat a library as a network folder, opening/saving files directly from any application, copying and renaming from Windows Explorer etc.
You do face some limitations though:
The full path of the file can't be larger than 260 characters and SharePoint will truncate it without warning.
The file name can't contain some characters that are valid for Windows Explorer, eg #
If you try to save a file with the same name as an existing one, SharePoint will create a new file with a slightly different name without asking
You have no control over the author and creation date properties. SharePoint will use the current date and the credentials of the user executing the code.
You can't set any metadata although you can update the file's ListItem properties after uploading.
Another option is to use the Client object model and upload the file using File.SaveBinaryDirect. This option is better than simply copying the file, as it allows you to overwrite an existing file, but you still don't get direct access to the file's properties. Uploading could be as simple as this:
var clientContext = new ClientContext("http://intranet.contoso.com");
using (var fileStream =new FileStream("NewDocument.docx", FileMode.Open))
ClientOM.File.SaveBinaryDirect(clientContext,
"/Shared Documents/NewDocument.docx", fileStream, true);
Another option is to connect to a library using the Client Object Model and then create a file using FileCollection.Add, eg
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
fileCreationInformation);
Check this SO question, Upload a document to a SharePoint list from Client Side Object Model on how to use both SaveBinaryDirect and FileCollection.Add. The answers display both how to upload a file and how to modify its properties

Assembly.GetExecutingAssembly() not looking in the correct path

I'm reading an embedded xml file using
C#:
var AssemblyRef = Assembly.GetExecutingAssembly();
TextReader reader = new StreamReader(AssemblyRef.GetManifestResourceStream("Text.xml"));
It has been working for some time, but starting throwing errors. I traced the path that it is looking for and it is looking for the dll in the root of the bin folder and not in the Debug or release folder.
Once it is published this is fine, but for local development I cannot get my one feature to work.
I have it set to Debug when compiling. Any help would be great.
You have:
Changed Assembly Name OR
Changed namespace OR
Moved the resource to a folder in the project
I changed the call to this and everything is fine.
TextReader reader = new StreamReader(Assembly.GetExecutingAssembly().AssemblyRef.GetManifestResourceStream("Text.xml"));
Making the call one statement made it work. I'm not sure why.

Resources