Skip to main content

How to Register Stylesheet Created in Runtime

Here is an example from MSDN:
// Create a Style object for the  section of the Web page.
Style bodyStyle = new Style();
bodyStyle.ForeColor = System.Drawing.Color.Blue;
bodyStyle.BackColor = System.Drawing.Color.LightGray;
// Add the style to the header of the current page.
Page.Header.StyleSheet.CreateStyleRule(bodyStyle, this, "BODY");

It is the simple and handy method but has a few flaws.
1. Output is far from optimal. For example, following code that adds a border
someStyle.BorderColor = System.Drawing.Color.Red;
someStyle.BorderStyle = BorderStyle.Solid;
someStyle.BorderWidth = new Unit("1px");
produces this output
border-color:Red;border-width:1px;border-style:Solid;
instead of
border:Solid 1px Red;

It has no matter if you don't pay attention to the size of pages you develop, but it is taken into consideration if you take into consideration your visitor's needs (sorry for tautology). But it's a trifle, of course. I mentioned it just for completeness. There is a more serious flaw.

2. Number of style attributes that can be registered in such way is very limited. You can't add padding or margin attributes or even particular border (e.g. border-left).

The code overview

Class StylesController has four public static methods:
//includes registered styles into page header
public static void RegisterStyleSheetBlock(Page page, string key, string styles)
{
LiteralControl ctrl = new LiteralControl(string.Format(@"<style type=""text/css"">
{0}
</style>", styles));
ctrl.ID = key;
page.Header.Controls.Add(ctrl);
}
//includes link to the newly created stylesheet file into page header
public static void RegisterStyleSheetInclude(Page page, string key, string styles)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(key);
string base64Key = Convert.ToBase64String(bytes).Replace('+', '!');
LiteralControl ctrl = new LiteralControl(string.Format(@"<link
type=""text/css"" rel=""stylesheet"" href=""{0}?key={1}""/>",
page.ResolveUrl("~/stylesheet.css"),
base64Key));
ctrl.ID = key;
page.Header.Controls.Add(ctrl);
HttpContext.Current.Session[base64Key] = styles;
}
//checks whether inline styles with specified key have been already registered
public static bool IsStyleSheetBlockRegistered(Page page, string key)
{
return (page.Header.FindControl(key) != null);
}
//checks whether a file with styles with specified key have been already registered
public static bool IsStyleSheetIncludeRegistered(Page page, string key)
{
return (page.Header.FindControl(key) != null);
}
The class StylesController implements IHttpHandler interface and serves as HttpHandler that produces the stylesheet file.
public class StylesController : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
{
...
#region IHttpHandler Members
bool IHttpHandler.IsReusable
{
get { return false; }
}
void IHttpHandler.ProcessRequest(HttpContext context)
{
context.Response.Clear();
context.Response.ContentType = "text/css";
string key = context.Request["key"];
if (key != null)
{
object script = context.Session[key];
if (script != null)
{
context.Response.Write(script.ToString());
HttpContext.Current.Session.Remove(key);
}
}
context.Response.End();
}
#endregion
}
HttpHandler has to be registered in web.config
<httpHandlers>
<add verb="GET" path="StyleSheet.css" type="TypeName, AssemblyName"/>

</httpHandlers>
where AssemblyName is the name of the assembly, where the class StylesController is located,
TypeName is the fully qualified name of the StylesController, including the namespace.

How to use

string styles = "div{padding:2px 5px;background-color:red;}";
if (!StylesController.IsStyleSheetBlockRegistered(this, "Red Divs"))
StylesController.RegisterStyleSheetBlock(this, "Red Divs", styles);
or
string styles2 = "a,a:link {text-decoration:none;background-image:url(img/back.gif);}";
if (!StylesController.IsStyleSheetIncludeRegistered(this, "New Links"))
StylesController.RegisterStyleSheetInclude(this, "New Links", styles2);

Source code - 1kB

Comments

Popular posts from this blog

How to merge cells with equal values in the GridView

My solution is not the first; however, I think, it is rather universal and very short - less than 20 lines of the code.

The algorithm is simple: to bypass all the rows, starting from the second at the bottom, to the top. If a cell value is the same as a value in the previous (lower) row, then increase RowSpan and make the lower cell invisible, and so forth.

The code that merges the cells is very short:
public class GridDecorator { public static void MergeRows(GridView gridView) { for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--) { GridViewRow row = gridView.Rows[rowIndex]; GridViewRow previousRow = gridView.Rows[rowIndex + 1]; for (int i = 0; i < row.Cells.Count; i++) { if (row.Cells[i].Text == previousRow.Cells[i].Text) { row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : prev…

Merging columns in GridView/DataGrid header

As necessity to show header columns in a few rows occurs fairly often it would be good to have such functionality in the GridView/DataGrid control as an in-built feature. But meanwhile everyone solves this problem in his own way.

The described below variant of the merging implementation is based on irwansyah's idea to use the SetRenderMethodDelegate method for custom rendering of grid columns header. I guess this approach can be simplified in order to get more compact and handy code for reuse.
The code overview
As it may be required to merge a few groups of columns - for example, 1,2 and 4,5,6 - we need a class to store common information about all united columns.
[Serializable]
private class MergedColumnsInfo
{
// indexes of merged columns
public List<int> MergedColumns = new List<int>();
// key-value pairs: key = the first column index, value = number of the merged columns
public Hashtable StartColumns = new Hashtable();
// key-value pairs: key = the first column in…

JIRA REST API: Cookie-based Authentication

Three authentication methods are proposed by the JIRA REST API documentation: Basic Authentication is a simple but not very safe approach. Credentials are sent in the header on every request and encoding to Base64 is not a proper protection in this case; HTTPS connection is required. OAuth authentication - looks a bit complex and requires additional configuration at the JIRA server that is not always possible. Cookie-based Authentication - this approach seems to be the most convinient one: credentials are checked once, then the authentication cookie only is sent on subsequent requests. However, trying to use the cookie-based authentication I encountered an issue. The approach described in the documentation worked partially: I was able to create a new session and get the response containing the session cookie but all subsequent requests using this session cookie were rejected as unauthorized. Spending some time investigating this I found the cause of the issue: JSESSIONID is not th…