Dynamically setting CSS values using ASP.NET - c#

I'm working on a site where the images and other resources will be located on a separate domain from the main content of the site. We will use something like 'www.example.com' for the main site, and then 'images.example.com' for all extra resources for styles, etc.
When developing the site I will keep all of these resources on local dev. machines. The challenge here is keeping CSS references consistent between the production server and development environments.
What I was thinking of doing was creating a web.config key that would store the URL of the images server. Then, when switching from development to production I could just change the web.config value and everything would be done.
Is there any way to add a value to a CSS file, dynamically or otherwise, from some place in a config or C# class? Or am I going about this the wrong way?
Also, I'm limited to using .NET 2.0 if that makes a difference.
UPDATE
To expand on this a little more, I know I can use a web.config setting for server controls' URLs. Those are already generated dynamically. What I'm more interested in is what options I have for modifying (or doing "something") to static CSS files that will allow me to change URLs for things such as background image resources that would be referenced in CSS. Is there anything I can do besides find/replacing the values using my IDE? Perhaps something that can be done automatically with a deployment script?

Is keeping the CSS file on the image server an option? If that it possible, you could make all the image references relative, and then you just need to update the link to the css file.
<link rel="stylesheet" href="<%= ConfigurationManager.AppSettings("css-server") %>style.css" />
If you still want to send or generate a css file dynamically:
css files don't have to end in css. aspx is fine. You could do this:
<link rel="stylesheet" href="style.aspx" />
and then in your style.aspx page:
protected void page_load(){
Response.ContentType = "text/css";
if (ConfigurationManager.AppSettings("css-server") == "local") {
Server.Transfer("css/local.css");
} else {
Server.Transfer("css/production.css");
}
}
If you still want to dynamically generate a css file, I'd use an HttpHandler, set the contenttype to "text/css", then generate the css with Response.Write. If you insist on having the page end in css, you could always register css to go to asp.net in IIS, then on incoming requests in global.asax application_Begin request, if the file ends in .css, use httpcontext.current.rewritepath to your handler.
This will have a net effect of style.css being dynamically generated at runtime.

What about putting a place holder on the web page and then selecting which CSS file to utilize (PROD, TEST, etc.) at run time and add it to the place hodler?
I think that Update had the right idea...
<link rel="stylesheet" href="<%= ConfigurationManager.AppSettings("css-server") %>style.css" />

Sounds like a job for a NAnt [link] script to me. They're pretty easy to work with and well documented.
That way your code has isn't changing your css links, they're being updated at deploy time. This isn't a code issue, it's a deployment issue, so addressing it as such feels more "right" to me. That way you know if it loads correctly (with the right images) the first time it will load every time. NAnt scripts are a good thing to have in your toolbox.
The other solutions will work, but that code will be running every time the page loads for a change that should have happened once -- when the app was deployed.

You duped your own question:
https://stackoverflow.com/questions/449236/dynamically-setting-css-values-using-asp-net

This is a common problem. What we do is have seperate web.config files for each environment. There is a appSettings key in the web.config and any config values go there like this.
<appSettings>
<add key="ImagePath" value="d:\websites\www.site.com\www\images\" />
<appSettings>
When setting the image control in the code behind, use the following:
myImage.ImageUrl = + _
System.Configuration.ConfigurationSettings.AppSettings("ImagePath") + "image1234567890.jpg"
Just change your ImagePath key to correspond with the path on the production or qa servers. Also, you could make the test server have the same path, but in my experience this solution works.

I would create a server control for my CSS that registered the css script block on page load. You could very easily change all paths at that point programmatically.

Perhaps you can do something with the hosts file on your dev server(s)? That way you won't have to actually change any code.
It IS possible to send files with the .css extension through the asp.net engine, though. You could also have .ashx handlers that return valid css and reference those handlers in the tags. Seems like kind of a waste of processor for stuff that is 90% static text though.

Related

Change an appsettings.json value on publish netCore6

Is it possible to increase a value in the appsettings.json when I publish a project?
I want to add some kind of number to all css and js files, because it seems they keep getting cached. I want a value in my appsettings.json (or somewhere), I'll add to all css/js includes.
When I publish the project, I would like this number to increase.
Is there a way to do this? Or is there some other way to force a refresh of css/js on the client-side when changes are made?
You can use the built-in asp-append-version if you're referencing your CSS and JS files directly. Like
<script src="your-file-here.js" asp-append-version="true"></script>
That will append a "version" to the file path (which is calculated from a hash of the file content, thus it will update whenever the file does). In my experience it works pretty well :-)
https://www.c-sharpcorner.com/blogs/aspappendversion-feature-in-asp-net-core

Can Override Bootstrap CSS in ASP.NET MVC5 Application?

I am relatively new to using ASP.NET MVC5. It is nice that Bootstrap is built in but it seems to be very abrasive to altering the CSS based on the Site.css file.
My style sheet (Site.css) is in the Content folder in my solution.
Similar questions are out there but those are the answers I have tries (show below and obviously having the file AFTER the bootstrap...)
I have had some success using just the inline CSS and jQuery but I want to be able to use my style sheet.
It seemed that switching from relying on the bundle to this line...
#Styles.Render("~/Content/css")
for the reference was better fit... but it STILL doesn't consistently update to my styling.
so then after some digging through old questions I found this...
<link href="#Url.Content("/~Content/Site.css")" rel="stylesheet" type="text/css" />
and it seems like one in a while it works but NOT consistently...
I thought at first it had to do with the strongly types bootstrap file with the elements getting more specific styling points, but even when experimenting with the strongest id/elementname/nesting combinations I could it STILL wouldn't work. (i want to do hovers and such, but even easy things like changing the text color don't work)
Is there some giant flaw in this strategy?
Is there something I'm missing?
To the best of my knowledge this shouldn't be a huge problem, I would appreciate it greatly for someone to help me out or at least tell me why I'm sooooo wrong.
Thanks.
Although the solution provided by EdSF is good it is still not very understandable for someone who has just started with mvc5. So I will try to explain it a little bit more.
Go to
/App_Start/BundleConfig.cs
this is the file where all your stylesheets are bundled.
bundles.Add(new StyleBundle("~/bundles/css").Include(
//"~/Content/css/bootstrap.min.css",
"~/Content/css/Site.css",
"~/Content/css/jquery-ui-1.10.4.min.css"));
comment out the line of bootstrap if you don't want to use it and add you css just like the above. But remember It will remove bootstrap completely and unless you have written you own bootstrap-ish stylesheet for responsive webpage design, you should keep it.
When your view page is rendered in the browser inspect the element that's design is not according to your stylesheet and check the class name on that element and override that class with your own stylesheet class and add !important tag on the style attribute so that it will not be overidden by anything else.
Try these steps. Good luck.
Just to make sure: there's nothing about ASP.Net/MVC etc that imposes anything about styles.
You can use Bootstrap or not, or any other styling framework
Bootstrap isn't "built in", it's just the default when an MVC application is scaffolded for you
That out of the way, you don't have to use Bootstrap if you don't want to.
/App_Start/BundleConfig.cs - this is where you define what CSS and javascript frameworks, files you want to be bundled with your application. Modify (add/remove/etc) it to your needs.
Other than that, overriding CSS classes is pretty much the same as it is anywhere (nothing is imposed by the ASP.net framework).
Hth
RESOLVED: what seemed to be the main issue was not clearing my cache between tests. Although this seems a little tedious, I was finally able to get some Styling in.
but there were 2 more things I tried (from other question on Stack-Overflow) which seemed to all combine to getting it working better. (though it would still be nice if changes consistently reloaded on refresh without restarting the app! (I run parallels so it takes quite a long time!)
ANYWAYS! The (3) changes I made that were most effective
Clearing the cache (so the browser is forced to re-render the script
Changing the name in the "Bundle_Config" from "site/css" to match "Site/css" (not positive why it is like this in the scaffold.. or if it matters...but it seemed to make communication with the file more consistent.
Adding another reference (THIS HELPED THE MOST) adding an additional stylesheet reference to the relative path aside from the built in "renderStyles" from the budleconfig that takes place in the _Layout.cshtml.
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
granted I still need to clear the cache once in a while and restart the app to see changes, I am at least able to change the styling...
thanks for the help everyone!

Could a Web.UI.Page object (C#) correspond to a .html file, rather than a .aspx file?

I was checking the System.Web.UI.Page class methods and instantiation examples listed here: https://msdn.microsoft.com/en-us/library/system.web.ui.page(v=vs.110).aspx
In this case, the front-end file is an .aspx file and is linked to the back-end .cs file via this meta header:
<%# Page Language="C#" CodeFile="pageexample.aspx.cs" Inherits="MyCodeBehindCS" %>
Could a Page object also be tied to a pure .html file? If yes, then how are they tied to each other?
You cannot produce a page ends with "html" as a result, because the IIS have to know what kind of page it's dealing with, in order to follow the .Net life-cycle.
However, you can consider the Page is already produces a pure HTML file, since it's the only code that the browsers can understand. If you want to have the same on developer's view, just don't use the benefits of .aspx objects.
But of course, you can find workarounds too. You can create an HTML file with Javascript codes which triggers the .aspx pages needed, and puts the results. By the look of the user, it's all will be looking like an HTML file. (And Javascript ofcourse)
One option, though keep in mind you're technically fooling IIS in this instance:
Open IIS Manager and select the target website.
Open HandlerMappings applet
Copy the mapping where Path is *.aspx into a duplicate where path is *.html.
Then, add a handler in your config to tell IIS what to do with this file type:
<httpHandlers>
<add path="*.html" verb="*" type="System.Web.UI.PageHandlerFactory" />
</httpHandlers>
Note: If you have HTML pages without server-side code in them, this could end up being troublesome. You may be better off just exempting extensions altogether and look at using routing.

C# asp.net application, changes to Site.css do not seem to affect Site.Master

I just started an asp.net c# project and I was trying to change the text-align of the .title and background color of the .header. I add the required code to the style sheet, but nothing changes in the header of the form. I'm probably missing something simple here, can someone point me in the right direction?
Stylesheets are usually cached by the browser to speed up browsing.
You can either force-refresh (SHIFT+F5) or append a value to the stylesheet path to cache-bust it.
style.css?v1
By changing v1 whenever you want a change to be forced out to all browsers, it will replace the cached version as resources are cached per URI.
Just try stopping your Local development server and do clean and build solution before running the application.
Even clear your temporary internet folder which may contain stale copy of your css file.
Right clicking in the markup view , you should see an options that says view in browser. This should reload anything cached.

Using C# to dynamically generate CSS files

I have a site that gets deployed to over a dozen clients. The main website has a base template, and each client has a client folder that overrides the colours. The problem is that there are a lot of CSS files, so making a change that forces us to update every client takes a long time. The automated build process takes care of replacing the updated files.
I would like to change the CSS files to be usercontrols instead, and those usercontrols could then inherit from another usercontrol where client specific values are stored.
So instead of having a forms.css file and then a /client/forms.css file I would have a Forms.ascx file that inherits from a usercontrol that contains the colours.
Ex:
<%# Control Language="C#" ClassName="Forms" %>
<%# Register TagPrefix="css" TagName="Client" Src="~/css/ClientStyling.ascx" %>
/* CSS Document */
body
{
color:<%=Client.BodyColor%>
}
Then the masterpage would inherit from the usercontrol instead. This would make the maintenance of the client sites much easier.
So is this solution efficient and recommended? Or is there a better way to accomplish the same end result?
If this is possible, would it also be possible to have the Forms.ascx control output the markup as CSS? Or make the extension .css and still have the ascx properties?
Instead of a Web Control, you're likely better off creating a Generic Handler. This won't have the overhead that a web control has.
In your handler, accept the clientID via querystring - this allows you to cache on a client level
In your .master file, you can link to it < link src="MyCssHandler.ashx?ClientID=<%=ClientID%>" >
In your handler you have a few ways to work with the CSS.
Just have a bunch of response.write for the css, and put in relevant client values
Create an external CSS file with it's own special identifier - maybe <% %>. You could then load all the client specific values in a NameValuePair Collection, and then loop through the external CSS file, parsing <% NAME %> and replacing with the correct value. Then response.write this file. More complicated true but it allows for a hell of a lot cleaner CSS files
Another option to consider may just be to use a "CSS compiler" -- such as SASS, LESS or even HSS which may support handy constructs like "mixins" and including other files. This approach may allow a system that, while not dynamic, is easily configurable to your different client's needs.
For instance, with a "CSS compiler" the entire color schema could be stored in a single file as exportable variables or templates (depends on "compiler") -- modify that file, "recompile"** and wham, new color-scheme interface is everywhere (SASS also supports math on colors -- such as Hue shifting). This may make the deployment/management of using static content feasible enough for your purposes.
I use SASS (it fit my needs/style whereas LESS/HSS did not). I would not switch back unless I really, really had to (which is to say: uhh, never) -- SASS in SCSS mode also understands CSS syntax so you can micro-evolve or mix and match (LESS and HSS also work like this, but HSS only works with a stricter subset of CSS syntax). CSS compilers can also be used in conjunction templates engines (such as TT4) or take advantage of including dynamically generated files (not dynamic-dynamic as in the question, but dynamic in the sense that they come from some other data-source) if extra power is needed.
While just normal CSS cascading and class names/selectors can go a long ways, I find it much easier to separate the "logical cascade" (CSS, where CSS/cascading is vital) and "geeze, I wish this worked like a template" (CSS compiler, which should handle cases where CSS/cascading is abused).
** Both SASS and LESS can monitor files and recompile them automatically for you. SASS even allows monitoring entire directories
Write it out as a file and let the browser pick it up as it would any other CSS file.
Making inline stylesheets prevents the client cache mechanism, forcing your CSS to be served up with every page.
This is entirely possible. You might want to consider cascading your stylesheets too, so that the dynamic one imports a (presumably larger) static one.
Asp.NET has support for themes, too, but to be honest CSS is much more powerful.
Why are you thinking ASCX instead of ASPX though? I'd have thought that since one css file represents an entire response, it could all fit in a page.
an ashx is probably the lightest, fastest form of handler you can implement, so you might want to look at that...
Oh and make sure you get your caching parameters right!

Categories

Resources