Is it possible to have an XML file embedded in the project that can be accessed from code behind and directly from XAML using XMLDataProvider?
When I set the XML file as "Embedded Resource", I can access it from code, but not from XAML.
When I set the XML file as "Resource", I can access it from XAML, but not from code.
Now it is possible to load a Resource from using a Pack Uri from code, however the xml file is in a 'service' library and I don't feel like referencing PresentationFramework, WindowBase, etc. to make this work.
External XML file is also not an option since a lot of unit tests will break. The solution would be to add an attribute to those tests, only there are A LOT.
Any suggestions?
You can easily set xml files are Resource and then read them in code as follows
Uri uri = new Uri("/file.xml", UriKind.Relative);
StreamResourceInfo info = Application.GetResourceStream(uri);
if (info != null)
{
using (StreamReader reader = new StreamReader(info.Stream))
{
string xml = reader.ReadToEnd();
}
}
Here file.xml is Resource so replace to whatever name you have
Related
I have an issue with a class library; I am preparing a library with an interface that represents a specific data storage signature. The purpose is to use the interface as a basis for implementing a number of specific classes storing configuration information in different formats (text files, xml files, etc.) while retaining the same usage profile to the application using it. I have a problem, though. In this case I am trying to embed an xml file as a resource - this file is one type of format to store configuration data. The file is located as an embedded resource in a subfolder to the project, as shown in the attached illustration.
In the following code snippet it is shown how I have implemented the functionality until now.
public ConfigInfoXmlSource()
{
if (!string.IsNullOrEmpty(Settings.Default.CurrentConfigFile))
FileNameAndPath = Settings.Default.CurrentConfigFile;
else
FileNameAndPath = DefaultConfigFileName + DefaultFileExtension;
// Prepare XML.
System.Reflection.Assembly a = Assembly.GetExecutingAssembly();
XmlDocument doc = new XmlDocument();
Stream manifestResourceStream =
a.GetManifestResourceStream("TestTool.Config.Config1.xml");
if (manifestResourceStream == null)
{
// ???
}
...
doc.Load(manifestResourceStream);
...
}
In the section marked "Prepare XML" I am trying to read a stream from the embedded resource. After the reading, it is tested whether a stream was indeed created. If the file is found, the manifestResourceStream will contain the xml data - so far so good. The problem arises if the file for some reason has been accidentally deleted - in that case I want to create a new file as an embedded resource to replace the deleted file. That is supposed to happen in the conditional in the part shown as "???".
I have tried everything I could think of, searched Google for answers, etc. - to no avail.
Does anyone have a clue to how this is accomplished? Any help will be greatly appreciated.
Thanks in advance.
Best regards.
If you have a embedded resource,it is built into your binaries.It is not an physical file,rather something which is present inside the built file(dll in this case).So,once it is included,I do not think it can ever be deleted. As per my knowledge embedded resource can only be set while building your project binaries and you can not explicitly do it at runtime as it is not needed due to reasons mentioned above.
I have a class library that contains some generic proceesing functionality - call it "Engine".
I include the class library in a number of web applications.
The engine library needs an XML file as input, but the content is unique to each project.
At the moment I manually copy the XML file into each project. The engine always looks for a file in the application route.
However, I've gotten a little confused with regards to embedded resources. In order to validate the XML, I've created an XSD in my engine project and set the Build Action to EmbeddedResource.
I can't see the difference between setting the BuildAction to Content and EmbeddedResource in this case, which has led me to doubt the way that things are currently set up.
I've not a lot of experience at this level, so need some guidance. Any advice would be appreciated.
EmbeddedResource means that the xsd is embedded inside the assembly during build, while Content means it is just copied along to the output folder. You want the embedded resource thing it sounds like.
You can access Embedded resources through code like this:
string resourceName = "SomeNameSpace.SomeFile.xsd";
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
if ( stream == null )
throw new ArgumentException("resource not found", "resourceName");
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
return result;
}
}
Using Sitecore 7.5, I am trying to store several html files inside of the Media Library. Then in my sublayout codebehind I am attempting to grab the inner content of those html files.
I had this working when I was storing the html file on the server. I would upload the file into the Media Library using 'upload as file', and then use the following code to read the content:
string filename = htmlMediaItem.Fields["File Path"].ToString();
string path = Server.MapPath(filename);
string content = System.IO.File.ReadAllText(path);
However I now would like to do this without storing the files on the server and instead only have them inside the media library. Is there anyway I can do this?
So far I have had a hard time trying to find information on the subject.
Thank you.
From what I understand you want to read content of an html file stored in Media Library.
Sitecore.Data.Items.Item sampleItem = Sitecore.Context.Database.GetItem("/sitecore/media library/Files/yourhtmlfile");
Sitecore.Data.Items.Item sampleMedia = new Sitecore.Data.Items.MediaItem(sampleItem);
using(var reader = new StreamReader(MediaManager.GetMedia(sampleMedia).GetStream().Stream))
{
string text = reader.ReadToEnd();
}
I'm trying to build a wp7 application that must allow user to read ebooks in epub format. Since there isn't any available library to read epub file on a windows phone, I'm trying to create one. So I must unzip the file and then parse it.
The problem is that I can't unzip the epub file. I'm using SharpZipLib.WindowsPhone7.dll but I get an exception:
Attempt to access the method failed: System.IO.File.OpenRead(System.String)
on this line:
ZipInputStream s = new ZipInputStream(File.OpenRead(path_epubfile));
Can any one help me, please?
It's going to depend on how the content is obtained. There's three possible options here;
Option 1: If the content is added to your project with a Build Action of "Content" you can obtain a stream by using the StreamResourceInfo class (In the System.Windows.Resources namespace)
StreamResourceInfo info = Application.GetResourceStream(new Uri("MyContent.txt", UriKind.Relative));
using (info.Stream) {
// Make use of the stream as you will
}
Option 2: If you've added it to your project and set the Build Action to "Embedded Resource" then you'll need to use GetManifestResourceStream()
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ProjectName.MyContent.txt")) {
// Make use of stream as you will
}
Note: You'll need to replace "ProjectName" with the name of your project. So if your project was "EPubReader" and the embedded resource was "Example.txt" you'd need to pass "EPubReader.Example.txt" to GetManifestResourceStream(). You can use GetManifestResourceNames() to see what resources are available.
Option 3: If you've obtained the content at run time, it'll be stored in IsolatedStorage.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
using (IsolatedStorageFileStream stream = store.OpenFile("MyContent.txt", FileMode.Open)) {
// Make use of stream as you will
}
}
I want to add an ability to an application that I'm developing for accessing configuration.
The application will search by default in the app.config file for a section that I give it.
If it was not found in the app.config, it will look for it in the DB, in a specific table that has the following columns:
SectionType, SectionName, SectionData
The SectionData column is a text column, that contains the data of the section in XML format (exactly like it should be in the app.config file)
I can take the SectionData content, but I can't load it into the custom ConfigurationSection, like I would have done if it was in the app.config file:
var mySectionObj = ConfigurationManager.GetSection("myCustomSection");
To simplify, my question is actually how can I get the custom ConfigurationSection object from a XML string instead of a configuration file?
You could load the string into an XDocument object and read it from there.
I don't think that's possible at all - with the ConfigurationManager class from .NET, it is as far as I know not even possible to open whatever file you want - you are restricted to the app.config file. Reading configuration data from another source than a file? No can do.
You can either analyse the XML-String yourself (with "XmlDocument.LoadXml(string)") or you modify the app.config file and read it again.
The question would be: Why wouldn't there be the CustomSection in the config file? Should this be considered an error (then updating the config file would be best, I think). Or is it intended, that some config files don't have the CustomSection?
If the settings may be in the XML-File, adding the setting to the file would be like this:
XmlDocument appconfig = new XmlDocument();
appconfig.Load("[config_filename]");
XmlNode root = appconfig.DocumentElement;
XmlDocument mysection = new XmlDocument();
mysection.LoadXml([SectionData]);
XmlNode customSection = mysection.DocumentElement;
XmlNode tempNode = appconfig.ImportNode(customSection, true);
root.AppendChild(tempNode);
appconfig.Save("[config_filename]");
...
var mySectionObj = ConfigurationManager.GetSection("myCustomSection");
if this is not desirable, I see two possibilities:
First:
Do it nevertheless: Change the .config file, read it, and then change it back.
(or copy the file, change the original, read it, delete it, rename the copy back to the original name).
This way is not nice, it's somehow impure, in my opinion, but it has some great advantages: It works and it is easy to maintain.
Second:
Load your XML string into a XmlDocument: XmlDocument.LoadXml(xmlstring)
Then analyse the xmldocument, with "doc.ChildNodes" or "doc.SelectNodes(xpath)" or "doc.SelectSingleNode(xpath)".
This will be much more work, especially since you will have to maintain to routines to get the configuration settings into your project, so I would not recommend this method. Strongly not recommend.