How do you dynamically load a CSS file into a Flex application? - css

I know that you can apply CSS in order to style objects in Flex using the StyleManager:
http://livedocs.adobe.com/flex/3/html/help.html?content=styles_07.html
You can also load compiled CSS files (SWFs) dynamically:
http://livedocs.adobe.com/flex/3/html/help.html?content=styles_10.html
However, I'm dynamically creating my CSS files using a web GUI and a server-side script.
If the CSS is changed, then the script would also need to compile the CSS into an SWF (which is not a viable option). Is there any way around this?

In this comment to an issue related to this in the Adobe bug tracker T. Busser is describing what might be a viable solution for you:
"I've created a small class that will 'parse' a CSS file read with an
HTTPService object. It takes apart the
string that is returned by the
HTTPService object, break it down into
selectors, and create a new
CSSStyleDeclaration object for each
selector that is found. Once all the
properties are assigned to the
CSSStyleDeclaration object it's added
to the StyleManager. It doesn't
perform any checks, you should make
sure the CSS file is well formed, but
it will be sufficient 99% of the time.
Stuff like #font, Embed() and
ClassReference() will hardly be used
by my customers. They do need the
ability to change colors and stuff
like that so they can easily theme the
Flex application to their house
style."
You could either try to contact this person for their solution or alternatively maybe use the code from this as3csslib project as a basis for writing something like what they're describing.

You can also implement dynamic stylesheet in flex like this . Here i found this article :
http://askmeflash.com/article_m.php?p=article&id=6

Edit: This solution does not work. All selectors that are taken out of the parser are converted to lowercase. This may work for your application but it will probably not...
I am leaving this answer here because it may help some people looking for a solution and warn others of the limitations of this method.
See my question: "Looking for CSS parser written in AS3" for a complete discussion but I found a CSS parser hidden inside the standard libraries. Here is how you can use it:
public function extractFromStyleSheet(css:String):void {
// Create a StyleSheet Object
var styleSheet:StyleSheet = new StyleSheet();
styleSheet.parseCSS(css);
// Iterate through the selector objects
var selectorNames:Array = styleSheet.styleNames;
for(var i:int=0; i<selectorNames.length; i++){
// Do something with each selector
trace("Selector: "+selelectorNames[i];
var properties:Object = styleSheet.getStyle(selectorNames[i]);
for (var property:String in properties){
// Do something with each property in the selector
trace("\t"+property+" -> "+properties[property]+"\n");
}
}
}
You can then apply the styles using:
cssStyle = new CSSStyleDeclaration();
cssStyle.setStyle("color", "<valid color>);
FlexGlobals.topLevelApplication.styleManager.setStyleDeclaration("Button", cssStyle, true);

The application of CSS in Flex is handled on the server side at compilation and not on the client side at run time.
I would see two options then for you (I'm not sure how practical either are):
Use a server side script to compile your CSS as a SWF then load them dynamically.
Parse a CSS Style sheet and use the setStyle functions in flex to apply the styles. An similar example to this approach is the Flex Style Explorer where you can check out the source.
Good luck.

Related

Set up seperate CSS files for Apps Script UI Service

With Apps Script UI service, the CSS Styling can be set with the setStyleAttributes() method of the various classes.
setStyleAttributes
Multiple CSS style attributes can be set at the same time with setStyleAttributes(). The CSS style settings can be put into an key:value object assigned to a variable, and then the variable can be used in the setStyleAttributes method.
var cssHome = {"color":"red", "cursor": "pointer", "textDecoration" : "underline", "fontSize": "small", "font-family":"Arial Black"}
var menuHome = app.createMenuItem('HOME')
menuHome.setStyleAttributes(cssHome)
Right now all my code and variables are in one .gs file, and everything is in the doGet function. Is there a way to put the CSS into another file, and call it?
If you are happy authoring the CSS as key value pairs you could either wrap them in a separate function and call it at value assignment or you could store in a flat file in Drive and UrlFetch it. Neither solution allows for conventional CSS authoring but does you ask.
As it is for a doGet the former might be preferable. You could reuse this styling across multiple scripts by wrapping in another GS and referencing it as a library.
If you used HtmlService instead of UiService your CSS options are increased by convention.

gwt no CssResource'WithLookup' method

I've stumbled into a situation with gwt that does not seem to have a way around.
I've created a Composite widget with many dynamic clipped Image's so I can move the clipping like a tile-map. All went well until I start using a json as a TextResource describing the layout. The ui-binder does not work in my case.
I got ClientBundleWithLookup and ConstantsWithLookup working fine, but there is no lookup for the CSS classes. The lookup of the style() [as in the many examples] gives you this obfuscated chunk of the original css file - but there is no way to map these giberish names to what was originally in the css and in the json definitions.
I then thought of a way around is to send my css as a TextResource rather than the CssResource and process it manualy. After spending the entire day doing this - there is no styles on the browser since the generated gwt javascript look for these giberish names once running in the browser.
I need a way to lookup css style names at runtime, the ideal would be to have a CssResourceWithLookup class as well. Also there's no reflection so I cant map the java methods to pass to the setStyleName()'s.
I also spotted somewhere on google a way to produce a debug map of these names - however I don't see how this will actualy help me since these names change after every compile. So I'm throughly stuck. I just dont understand how the gwt team failed this 'lookup' functionality on half of the resource bundles.
Any one with a way around this - please?
#external may help you : it turns class names obfuscation off.
In MyStyles.css:
#external .style1, .style2;
.style1{
color: green;
}
.style2{
color: red;
}
In your Java code:
myTile1.addStyleNames("style1");
myTile2.addStyleNames("style2");

What does "property=''" do?

I'm working on a Drupal site/theme. The CSS and PHP modifications are fairly easy; they just take a little time to learn and get working exactly how I want.
However, I'm having issues applying CSS styles to some elements because of what I think is a property function.
The code looks like <h2 property="dc:title" datatype="" class="node-title">.
What is a property function and what does it do or control within the page? Also how can I modify or remove it?
It's not a property function; it's an attribute that is used from RDFa, and that is added from the RDF module.
The easier way to remove those attributes is to disable the module, but I would not suggest doing it, as the purpose of that module is to enrich your content with metadata to let other applications better understand its relationships and attributes.
Alternatively, if the problem is just with that property, used for the nodes, then you can implement code similar to the following one:
function mymodule_preprocess_node(&$variables) {
if (isset($variables['title_attributes_array'])) {
$variables['title_attributes_array']['property'] = NULL;
}
}
The module should be executed after the RDF module, to allow its hook to be executed after the one implemented by the RDF module.
I have not seen any compatibility problem between the attributes added by the RDF module and the JavaScript code executed by Drupal core or third-party modules. It would probably be the case to investigate why you are having problems with the JavaScript code when those HTML attributes are added.
in your css file, put:
h2[property="dc:title"]{color:#FFFFFF;}
or if it is a link, you may need:
h2[property="dc:title"] a {color:#FFFFFF;}
From wikipedia, check out RDFa
RDFa (or Resource Description
Framework – in – attributes) is a W3C
Recommendation that adds a set of
attribute-level extensions to XHTML
for embedding rich metadata within Web
documents.
It is basically a way to add more metadata to XHTML docs for better semantics.

User defined CSS / Styles

We are looking into providing users of our application the ability override the default site CSS.
Currently they can choose a site theme but it would be nice to allow them to change properties such as background color, font color, font face etc.
I'm torn between giving each site a "user defined" stylesheet that can be edited from the administration area or providing some kind of CSS builder.
The first option provides the most flexibility but could also be the most problematic and requires the user to have some basic understanding of CSS.
So aside from the obvious, (which is the best solution?) I have a few additional questions:
User Defined Css:
Is there a web based CSS editor available?
Is there a server side (.net) CSS validator available (for verifying the css the user enters)
Css Builder:
Is there a web based CSS builder already available?
What is the best way of generating the CSS based on the rules provided by the user (I thought about using some kind of templating engine to do this (NVelocity, Razor etc.)?
Thanks
Solution
I've added an answer below with the solution we went for.
however never used, recently I looked at Brosho Design in the Browser jQuery Plugin
With this Plugin you can style your
markup right in your browser with a
build-in element selector and CSS
editor. Generate the CSS code of
altered elements with one click and
use it in your own stylesheet.
demo here
I'd recommend to build a custom css editor since it's the easiest way to limit which elements and attributes the user will be able to edit / customize, and how. Just keep it simple and you will do just fine.
To validate CSS you could use the API of the W3 CSS Validator, http://jigsaw.w3.org/css-validator/api.html
I've built an application that does exactly this. It's a little more involved as there are multiple master pages and themes, and the user can attach custom urls to load themes - example: /someclienturl would load a specific theme.
Anyway, here's the schema I used. One thing I wish I added is the ability for power users to add custom styles to the stylesheet that's eventually written. Basically, a theme section would apply to a selector #header, for example. And ThemeSectionCssStyle holds user added customizations for that selector. If you have any more questions let me know. It ended up being a fairly involved sub-project. I'm curious to see what anyone else came up with.
I think the key factor here is whether you want your users to 'play with the codez'
If you do then something like this (posted by #Caspar) can be helpful in generating the css. If you do allow direct access to the css then the W3 CSS Validator (posted by #Trikks) is definitely necessary.
In my case I didn't want to provide direct access to the Css. Looking around at various sites that allow you to change simple style properties (background-color, font-face, color etc.) it seems that they have just created their own interfaces for this. There are plenty of javascript plugins around for making this process quite slick (color pickers etc.).
Once you have the styles stored somewhere you need some way of rendering them out.
I couldn't find any .net Css writers. I think it may be possible in Less but the solution was quite simple just using what's built into asp.net mvc.
I created a Css action result (courtesy of #Darin Dimitrov):
public class CssResult : PartialViewResult {
public override void ExecuteResult(ControllerContext context) {
context.HttpContext.Response.ContentType = "text/css";
base.ExecuteResult(context);
}
}
Then in my controller (a simple example):
[HttpGet]
public ActionResult Index()
{
var styles = new Dictionary<string, string>()
{
{ "color", "red" },
{ "font-family", "Consolas, Courier, Serif" },
{ "font-size" , "12px" }
};
return this.Css(styles);
}
Then my view (views/css/index.cshtml):
body {#foreach (var item in Model) {
#string.Format("{0}: {1};", item.Key, item.Value)
}
}
This will essentially render out the styles in the passed in dictionary. Of course you may want to create a specific class for holding these styles so that you could also specify the dom element name/class/id.
Finally to render out the stylesheet on our page we can call Url.Action("index", "css").

Preferred method for linking to stylesheets from a UserControl?

We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript.
So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think.
Does anyone have any preferred methods, and if so, what and why?
I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think.
It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag & drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well.
This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not.
Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it.
When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself.
What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page_Load of the UserControl, but that just seems like ass.
I could use #import I guess but I think link tags are preferred, correct?
It sounds like you're rolling your own theme engine... why not use ASP.NET Themes?
If you're determined to do it yourself, here's some code from the CssFriendly project that may be of interest to you. (I think it should be ok to post the code as long as I cite where it's from.) The .css files are flagged as Embedded Resource and the code below is used to include them as needed.
string filePath = page.ClientScript.GetWebResourceUrl(type, css);
// if filePath is not empty, embedded CSS exists -- register it
if (!String.IsNullOrEmpty(filePath))
{
if (!Helpers.HeadContainsLinkHref(page, filePath))
{
HtmlLink link = new HtmlLink();
link.Href = page.ResolveUrl(filePath);
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
page.Header.Controls.Add(link);
}
}
I think what you're supposed to do is use Page.RegisterScriptBlock to register your script blocks. Best-case you shouldn't have them inline in your ascx inside script blocks. This isn't always possible, but theoretically it's the best way.
Ideally your styles should be separate from your markup as well. Your controls can have classes and IDs, but your style is based on your application and not your controls. Controls can theoretically be used in other applications where you might want a different style.
It depends on how big your app is, and whether or not it's dependent on Themes elsewhere, IMHO.
If you're using a .skin file, or if the majority of the app is also plugged into the theme, you might as well go with the theme.
But if it's just a few styles you need, you're better off to set the stylesheet manually, keep your css file external (inline styles are a PITA and defeat one of the core purposes of css).
In either case, don't forget to set the CssClass attribute on your controls.
To be proper I would have an import.css file - structure the naming of the classes to follow your controls, and import the styles within the header of the document.
If you have a module called "30DayPricingCalc" then you could name the classes/id's:
30DayPricingCalc.css
.30daypricingcalc_main_content
{
...
}
Also if you haven't I would setup a list of generic reusable styles to save you room. Since elements will allow multiple classes per object.
Also, link tags matter a lot less now than they used to. we're well past support for IE5 generation browsers and IE6 supports the #import tag.
Cheers!

Resources