How to load css into html dynamically? - c#

My C# program uses a web browser control and I programmatically set its html property by laoding it from a html string variable. This almost works well ,but I noticed it lost the reference to the css file. I think a simplest solution is to make the path of the css file absolute,but I want it remains relative to the C# executable.So let me ask how to let the html reference to the css file in such a context.
Thank you in advance.
Edit: I am sorry . My c# application is a desktop one ,although it uses a web browser control.
Edit: Let me put some code. I first load the document from an html file then store it in a variable then for the 2nd time or later I load the document from the variable.
//first load
web_browser_control.Url = new Uri( dir + #"\HTML\default1.html" );
void wB2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{ html_string = web_browser_control.DocumentText; }
//second load or later
web_browser_control.DocumentText = html_string;

You need to have a look at what path it THINKS its resolving, it would be best if you could please include some code, chances are its not resolving to where you think it is as its executing out of the bin directory (is your path correct relative to the path of the executable and the html),
For example is the html its looking at still where you think it is or is it now in a different directory so the relative paths are now obsolete ?
More code would be good and an indication of the control you are using.

Seems you can change property of css file to be "content" and make property "copy to output directory" - "always", so the wep app dll will be in the same directory with css file.
Or you can use MapPath method.

Related

How can I add images into my .resx file?

By other than using AddResource button of Visual Studio, of course.
I submit a form, and an image file with it. In my controller action, I get the HttpPostedFileBase object, and its file name by using Path.GetFileName(). If I just use SaveAs() function to save the image file in my application, I cannot access it later for testing, because it gives me the "Not allowed to load local resource" error.
So I want to add the image to a .resx file and retrieve it later using ResourceManager or something. My question is, how can I add the image I have in the controller action into my .resx file?
I should also ask if this is the good approach for the purpose of adding and retrieving image files in my application.
EDITED:
Ok, using .resx to store images is not a good idea. My original problem was that I could save the image file, but when I tried to show it in my view, it gives "Not allowed to load local resource" error.
Here's the controller code:
public ActionResult UrunEkle(Urun urun, HttpPostedFileBase image)
{
Directory.CreateDirectory(Server.MapPath("~/App_Data/Images"));
var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
image.SaveAs(path);
urun.ArtUrl = path;
// other stuff....
}
And in my view, I try to retrieve the image like this:
<img alt="#urun.name" src="#Url.Content(urun.ArtUrl)" />
But using Google Chrome, I get this "Not allowed to load local resource". How can I avoid this?
Forget trying to add the image to a RESX file; it's not designed to be modified at runtime.
Please post some code. The most likely thing is that the URL that you're serving up to use the image later is incorrect. Probably because you're returning the path of the file on the server, not a URL to the image within the context of the web site.
The error message from Chrome is telling you that it's trying to load a resource from the local file system on the client.
Url.Content converts a relative virtual path into an absolute virtual path and needs a URL starting with ~. You're currently passing in the absolute physical path to the image file and Url.Content is returning it, unchanged. You need the relative virtual path (~/App_Data/Images/Untitled.png) in urun.ArtUrl. This is the value that you passed in to Server.MapPath.

Getting path of file

I am using the C# code below to get the url to an xml file. The current page is News.aspx and the XML file is in the same folder, which is why this works fine.
xUrl = Request.Url.GetLeftPart(UriPartial.Path).Replace("News.aspx", "news.xml");
But it feels a little wrong to me, what if News.aspx changed? Is this the right way to do this sort of thing? Or is there a better way to get the URL of a file?
Thanks
I would use Server.MapPath to get the URL of a file.
private string GetPathOfMyXMLFile(string name){
return Server.MapPath("~/Resources/"+name+".xml");
}
you can then get this in your code
// Bla bla load file
string path = GetPathOfMyXMLFile("News");
You could add www.donetnukelabs' suggested answer and pop the name of your xml file into a settings store (web config perhaps), if it's likely to change.
There are many ways you can resolve this, you can introduce constant in the system, or you can use appSettings in web.config to store relative path to the folder for news.xml.
You are right, your current method is not considered good practice.

Loading FlowDocument.xaml that is part of my solution

I created a FlowDocument.xaml in my current WPF project. What i want to do is when the user clicks a button the XAML document will be loaded in the code behind, have some data on the document modified, and then print it out. The sticking point is i don't know how load the flow document so that i can modify it.
When I do:
FileStream fs = File.Open("FlowDocument.xaml", FileMode.Open)
It says that it can't find the file. The file is part of the project and I'm guessing it gets packaged with the rest of the project when compiled.
Any help is appreciated
Assuming it is configured to be a Resource, then you can load it like so:
FlowDocument doc= Application.LoadComponent(new Uri("/Path/FlowDocument.xaml", UriKind.RelativeOrAbsolute)) as FlowDocument;
This looks like it might be a path/relative path issue...just for testing purposes, try specifying the entire physical/absolute path in the File.Open statement...
You could also do
string path = Directory.GetCurrentDirectory();
to check to see what the current directory is and then make sure that the file FlowDocument.xaml is in that directory

Accessing Resources at Runtime

I have an XML file included as part of my Silverlight 4.0 project that I'd like to access at runtime. I have the file saved in a directory named Resources with the Build Action set to "Content" and the Copy to Output Directory set to "Do not copy". If I decompress the XAP file, I see the XML file in the location I expect it to be, but I'm not sure how to reference it from code. I currently have the following:
Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(#"/AssemblyName;component/Resources/MyFile.xml")
Unfortunately, stream is null after running the code above. In addition to the path mentioned above, I've tried "/Resources/MyFile.xml", "/MyFile.xml" and "MyFile.xml", but they all experience the same behavior.
What is the correct way to access an XML file embedded as a resource in a Silverlight application?
A resource with build action "Content" just gets embedded into the xap file, with the same relative directory structure as the application. It does not get embedded as a resource in the assembly.
When set to build action "Content", you should be able to just load the file using something like (or whatever suits your needs):
XElement.Load(<relative directory>/<file>)
The method you're using currently (using a resource stream) is for embedded resources (which have their build action set to "Resource"). And for those, although I haven't tried yet if your method works, usually you'll get the resources using
Application.GetResourceStream
I have used the code snip below to get access to drawables. Not sure it's completely relevant, but hoping this will give you a hint one way or another ...
Resources res = getResources();
spec = tabHost.newTabSpec("groups").setIndicator("Groups", res.getDrawable(R.drawable.ic_tab_groups)).setContent(intent);
As was mentioned by Willem van Rumpt, "content" resources are not usual resources (they aren't stored in assembly). I've checked out this article and could't found at all that you could reference resource, marked as "content" from other assembly.
So, you have two options:
Define XML as embedded resource
Define XML as resource
In first case stream request looks like:
var a = Assembly.Load("AssemblyName");
var s = a.GetManifestResourceStream(#"DefaultNamespace.Resources.XMLFile2.xml");
In second case:
var a = Assembly.Load("AssemblyName");
var rm = new ResourceManager("AssemblyName.g", a);
using (var set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true))
{
var ums = (UnmanagedMemoryStream)set.GetObject(#"Resources/XMLFile1.xml", true);
}
Hope this helps.

Calculating Relative Path Change

Assuming I have a .css file with the following line
body { background-image: url('../images/bg.png') }
My build process does some CSS magic and eventuall move this file from
~/Content/styles/styles.css
To
~/temp/styles.css
This invalidates the url statement in the file and needs re-written to ../Content/images/bg.png
This is my question - given the original file location, the new file location and the background-image url in the file is there a reusable way calculate a new relative path for the image?
In case someone doesn't know css urls should be relative to the css file it is contained within.
Solution 1
If you use ASP.NET themes, you can work around this issue. However, it also means you will have to restructure the way your files are.
Simply add a an App_Themes folder and a folder below that with a theme name ('Default' would be a good choice for a site with only 1 theme).
Add your theme name to the <pages> element in web.config:
<pages theme="Default">
Then put your css file inside of the theme folder. REMOVE any code that you use to reference the css file because ASP.NET will automatically wire it up to all of your pages.
If you want more control over the pages you add the css to, you can simply add the theme to the #page directive on the pages or do it in code behind in your base page in the Page_PreInit event instead of the web.config file.
Now, if you also put images below your theme folder, they can be referenced like this from css:
background-image: url('Images/Buttons/login-sprite.gif');
This example assumes your image file is in the location
[AppFolder]/App_Themes/Default/Images/Buttons/login-sprite.gif
and your css file is in the location
[AppFolder]/App_Themes/Default/Styles.css
Solution 2
If you prefer not to rearrange your files, you can also dynamically generate the file or read it into a string and replace a token of your choosing (example #MyImageFile#) with the actual url after calling ResolveUrl to make sure it is correct.
You could put code such as this in a file named Styles.aspx:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'This is a wrapper for the CSS file that allows us to inject
'any image URLs directly into the file, accounting for any relative
'path differences between different environments.
Dim FileName As String = Server.MapPath("Styles.css")
Dim sr As StreamReader
Dim contents As String
sr = File.OpenText(FileName)
Try
contents = sr.ReadToEnd
Finally
sr.Close()
End Try
'Now that we have the contents of the file, run our
'function on it to replace the tokens
contents = Me.ProcessConfigurationTokens(contents)
Response.Clear()
Response.AddHeader("content-type", "text/css")
Response.Write(contents)
Response.End()
End Sub
And then change your page references from Styles.css to Styles.aspx.
There is a performance hit with this approach, but it could be offset using caching. However, I think using Themes is the best approach because it solves the problem using the framework alone without writing any extra code.
You might consider using less to describe the image-path in a variable (pre-generating this as part of the build). Then you only have one thing to update?

Categories

Resources