Image as resource in Asp.Net 5 class library - asp.net

In .net 4.5 i was able to add a resource file to my project, add images as bitmaps to this resource file and access them by Properties.Resources.ImageName. How do i compile images in 4.6 dnx?
Thanks in advance!

You can specify the files that will be compiled into the assembly under the "resources" section in project.json, like so:
"resources": [
"path/to/yourfile.png"
],
After which, assuming your project's name is YourProject, the file can be accessed via:
const string path = "YourProject.path.to.yourfile.png";
Assembly.GetExecutingAssembly().GetManifestResourceStream(path)
Note how the slashes in the filesystem path are converted into periods in the resource path.
Note: In 1.0.0-rc1 (and possibly -beta8, haven't checked) the project setting is renamed from resources to resource

Related

absolute File path to relative file path

I have a class library project (D:/projectName/SampleClassPrj) and a console application project D:/projectName/ConsolePrj.
In class library project, a json file test.json and a class sample.cs (read and deserialise json) both present.
d:/projectName/SampleClassPrj/test.json
d:/projectName/SampleClassPrj/sample.cs
This works with absolute path like,
d:/projectName/SampleClassPrj/test.json
but not working with relative path.
with relative path, by using file not found error as it is trying to find the file in the console (running) application assembly folder.
D:/projectName/ConsolePrj/bin/test.json
please help to find the solution
first, check json file property "copy if newer".
then, use Appdomain.CurrentDomain.BaseDirectory
string result = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ConnectionString.txt"));
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\")));
StreamReader r = new StreamReader(Path.Combine(path, "sample.json"))
for .NET core 3.1
This worked for me

Vaadin Flow 14, Jetty embedded and static files

I'm trying to create app based on Jetty 9.4.20 (embedded) and Vaadin Flow 14.0.12.
It based on very nice project vaadin14-embedded-jetty.
I want to package app with one main-jar and all dependency libs must be in folder 'libs' near main-jar.
I remove maven-assembly-plugin, instead use maven-dependency-plugin and maven-jar-plugin. In maven-dependency-plugin i add section <execution>get-dependencies</execution> where i unpack directories META-INF/resources/,META-INF/services/ from Vaadin Flow libs to the result JAR.
In this case app work fine. But if i comment section <execution>get-dependencies</execution> then result package didn't contain that directories and app didn't work.
It just cannot give some static files from Vaadin Flow libs.
This error occurs only if i launch packaged app with ...
$ java -jar vaadin14-embedded-jetty-1.0-SNAPSHOT.jar
... but from Intellij Idea it launch correctly.
There was an opinion that is Jetty staring with wrong ClassLoader and cannot maintain requests to static files in Jar-libs.
The META-INF/services/ files MUST be maintained from the Jetty libs.
That's important for Jetty to use java.util.ServiceLoader.
If you are merging contents of JAR files into a single JAR file, that's called a "uber jar".
There are many techniques to do this, but if you are using maven-assembly-plugin or maven-dependency-plugin to build this "uber jar" then you will not be merging critical files that have the same name across multiple JAR files.
Consider using maven-shade-plugin and it's associated Resource Transformers to properly merge these files.
http://maven.apache.org/plugins/maven-shade-plugin/
http://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html
The ServicesResourceTransformer is the one that merges META-INF/services/ files, use it.
As for static content, that works fine, but you have to setup your Base Resource properly.
Looking at your source, you do the following ...
final URI webRootUri = ManualJetty.class.getResource("/webapp/").toURI();
final WebAppContext context = new WebAppContext();
context.setBaseResource(Resource.newResource(webRootUri));
That won't work reliably in 100% of cases (as you have noticed when running in the IDE vs command line).
The Class.getResource(String) is only reliable if you lookup a file (not a directory).
Consider that the Jetty Project Embedded Cookbook recipes have techniques for this.
See:
WebAppContextFromClasspath.java
ResourceHandlerFromClasspath.java
DefaultServletFileServer.java
DefaultServletMultipleBases.java
XmlEnhancedServer.java
MultipartMimeUploadExample.java
Example:
// Figure out what path to serve content from
ClassLoader cl = ManualJetty.class.getClassLoader();
// We look for a file, as ClassLoader.getResource() is not
// designed to look for directories (we resolve the directory later)
URL f = cl.getResource("webapp/index.html");
if (f == null)
{
throw new RuntimeException("Unable to find resource directory");
}
// Resolve file to directory
URI webRootUri = f.toURI().resolve("./").normalize();
System.err.println("WebRoot is " + webRootUri);
WebAppContext context = new WebAppContext();
context.setBaseResource(Resource.newResource(webRootUri));

Pyexcel, loading a file to create a book in memory

This is solved; thanks to #vmontco's solution: I was missing MEDIA_URL, now it works perfectly.
----------original question below-----------
I welcome suggestions from every angle; I am fairly new to Django and Python. I'm sure I am missing something simple.
Using a Model Form, with a FileField, I upload and save an Excel file to a folder structure under MEDIA_ROOT. This works.
I want to read that same file later to perform operations using Pyexcel. This is where I am stuck. I am attempting to upload the file using the FileField stored in the DB.
This is where I have problems, and I am not sure if am misunderstanding MEDIA_ROOT, or some other aspect of Django.
When I pass the pk to the 2nd view, I then instantiate an object based on the Model. It has the FileField 'docfile', which I am trying to use to access the file to do some operations using Pyexcel,
here is the FileField declaration from models.py:
docfile = models.FileField(
verbose_name="Choose file to upload:",
upload_to='Excel_CSV_Assets/%Y/%m/%d')
EDIT: If I hard-code the pth to the file like this, everything works, including operations afterwards:
thedocfile='site_static/site/original_assets/Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
book=pyexcel.get_book(file_name=thedocfile)
:END OF EDIT
Here is the code from the 2nd view, where I attempt to read the file into memory, and make a 'book' class object using Pyexcel. I am stuck here:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=asset.docfile)
Here is my error description:
Here is the info right at where my code breaks:
Although it says "Wrong filename", I can see the file is in the folder:
I'm able to open the file by double-clicking; the file is not corrupted.
EDIT:
If I cast the 'asset.docfile' to str, like so:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=str(asset.docfile))
I get a different error:
[Errno 2] No such file or directory: 'Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
...but this is the correct directory, located beneath the MEDIA_ROOT file structure.
Here is settings.py MEDIA_ROOT:
MEDIA_ROOT = 'site_static/site/original_assets/'
Here is urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^e/', include('excel_to_mongo.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here is the url.py of that app:
url(r'^efactory/(?P<assetid>\d+)/$', 'display_sheet_column_choices', {}),
I think your problem is that you don't fully understand the media files management with Django.
What are media files?
Media files are all the files that are user-uploaded (at running time).
You must not mistake them with Static files that are assets needed by your project to work and that you add at development time (CSS, background picture and JS files for instance).
You shouldn't mix them because they are managed differently by the server and that it could lead to security problems (cf. the warning here):
Static files management :
You put your static files as a part of the code either in one static subdirectory from the installed django applications, either in one of the locations you added to STATICFILES_DIRS.
Static files have to be gathered before starting the server by calling ./manage.py collectstatic, this command will collect (copy) the static files into the a directory (STATIC_ROOT's value).
You then have to set STATIC_URL to choose with wich url you should serve your static files. An usual choice would be /static/. To access the static file you should then try to reach /static/path/to/static/file/in/static_root/dir.
Media files management :
Your media files are added at running time. They are stored in the MEDIA_ROOT location that has to be an absolute path. Hence the fact I suggested you to join the BASE_DIR value (an absolute path) and the subdir you would choose with something like :
MEDIA_ROOT = os.path.join(BASE_DIR, "/media/subdir")
You then have to set an URL for your media files, by using the MEDIA_URL variable. To access your media files, the urls will start with the value you choose :
MEDIA_URL = '/media/'
Then, add this to your urls.py file :
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
With the current example, your mymediafile.txt will be located at /path/to/your/project/media/subdir/path/in/media/root/mymediafile.txt and served at http://127.0.0.1:8000/media/path/in/media/root/mymediafile.txt.
But this is suitable only for a development use as told here. And this would work only for DEBUG == TRUE
For a production use, you should consider deploying your media files with your http server (apache for instance).
Conclusion :
Take the time to understand this. Because I suspect you don't really understood what you did and this lack of understanding could lead to future bugs and errors.

Why is my jar not loading?

I am using the Jsoup jar file in my Coldfusion application. I was originally storing it in a local lib folder, but for security purposes we decided to store it in the cfroot lib folder. I uploaded the jar to the /lib folder in root, and added this code to Application.cfc:
this.javaSettings = {
loadPaths: [
"./lib/"
],
loadColdFusionClassPath: true
};
However, my code (that was working before) now generates the following error:
ERROR
Object Instantiation Exception.
Class not found: org.jsoup.JsoupObject Instantiation Exception.
...
It seems the code is not finding/loading the jar file. How can I point the code towards the Jsoup jar file stored in root?
Try backslash instead of forward-slash,
this.javaSettings = {
loadPaths: [
".\lib\"
],
loadColdFusionClassPath: true
};

Disable auto scanning for JDO classes datanucleus exploded war

When I deploy an exploded war file datanucleus fails with following error
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "JDOTutorial.war.WEB-INF.classes.com.blogspot.jkook.daytrader.jdo.QJDOOrderData" was not found in the CLASSPATH
This does not occur when war is deployed. Seems DN is scanning for classes which use JDO annotations when loading the JCA. With exploded deployment it is scanning all the classes inside the exploded folder and fails to load since the location of the class and the class in the class path does't match. (class name is com.blogspot.jkook.daytrader.jdo.QJDOOrderData , but DN is looking for
JDOTutorial.war.WEB-INF.classes.com.blogspot.jkook.daytrader.jdo.QJDOOrderData)
I am using settings below but DN is still scanning the exploded folder
datanucleus.autoStartMechanism = Classes ,
datanucleus.autoStartClassNames = com.blogspot.jkook.daytrader.jdo.JDOOrderData
Question : How to hint DN to stop scanning the exploded folders ?
finally solved jboss has feature to add external deployment folder
default = deployment -- placed the datanucleus-jca-3.0.0-m6
myPath = extdeployments -- placed the JDOTutorial.war (exploded folder)
Now DN doest scan for classes inside exploder folder :)

Resources