Why is runat="server" required for controls in skin files? - asp.net

Like the title says.. why ?
I know why its required on the normal ASP.NET controls, there are numerous questions on SO about that.
But since you can only define .NET controls (no normal HTML markup) in the skin files, why is the runat="server" still required for every control in the skin file?
It has nothing to do with styles or themes.
Is there any reason why I still need ot add it to all controls in my skin files? Does anyone know what happens with it 'behind the scenes'?

Again, you have to understand how server side languages work.
All ASP.NET tags are transformed to browser-understandable HTML (a browser has no notion of what an <asp:button> is, for instance) by a server side pre-processor before the page is rendered. This means that all controls/modules/anything served by ASP.NET that's not just HTML needs to have these attributes.
I venture that the pre-processor was written originally to know what it needed to operate on based on the presence of that attribute. Otherwise it would have to process every tag even if it did nothing. It could've been written to just look for the namespace, but that would require extra processing.
A skin file is a special ASP.NET concept, for tags defined within the framework. Hence, it makes sense that these tags have to have the "runat=server". MS could've written a special rule into their pre-processor such as "if it's a skin file, assume it's all ASP tags"...but such rules really don't scale. Plus they're bad documentation.
As a web developer, you should understand which of your tags are actually HTML and which are convenience tags provided by the framework. The "runat=server" attribute makes that delineation explicit.
You can add runat="server" to plain HTML tags such as <input> but generally there's little reason to and it's a bad practice.
For portability moving forward, you may want to consider moving away from skin files and leveraging CSS. Attributes are very verbose for setting styles, which makes the end rendered pages larger (taking longer to load, providing poor user experience) and un-semantic.

Related

Allowing user-created templates in an ASP.NET site

I have a website I’m converting from Classic ASP to ASP.NET. The old site allowed users to edit the website template to create their own design for their section of the website (think MySpace, only LESS professional.)
I’ve been racking my brain trying to figure out how to do this with .NET. My sites generally use master pages, but obviously that won’t work for end-users.
I’ve tried loading the HTML templates as a regular text file and parsing it to ‘fit around’ the content place holders. It is as ugly as it sounds.
There’s got a be something generally regarded as the best practice here, but I sure can’t find it.
Any suggestions?
How much control do you want your users to have?
There are a few ways to implement this. I'll give you a quick summary of all the ideas I can think of:
Static HTML with predefined fields.
With this approach you get full control and you minimize the risk of any security vulnerabilities. You would store per-user HTML in a database table somewhere. This HTML would have predefined fields with some markup, like using {fieldName}. You would then use a simple parser to identify curly brackets and replace fieldName with a string value pulled from a Dictionary<String,String> somewhere.
This approach can be fast if you're smart with string processing (i.e. using a state-machine parser to find the curley brackets, sending the rebuilt string either directly to the output or into a StringBuilder, etc, and importantly not using String.Replace). The downside is it isn't a real templating system: there's no provision for looping over result-sets (assuming you want to allow that), expression evaluation, but it works for simple "insert this content into this space"-type designs.
Allow users to edit their own ASPX or ASCX files.
Why build your own templating system if you can use ASP.NET's? Well, this approach is the simplest if you want to build a quick 'n' dirty reporting system, but it fails terribly for security. Unfortunately you cannot secure any <% %> / <script runat="server"> code in ASPX files in a sandbox or use CAS owing to how ASP.NET works (I looked into this myself earlier: Code Access Security on a per-view ASP.NET MVC basis ).
You don't need to store the actual ASPX and ASCX files in the website's filesystem, you can store the files in your database using a VirtualPathProvider implementation, but getting it to work right can be a bit of a pain (especially as the ASP.NET runtime compiles ASPX files, so you'd need to inform it if an ASPX file was modified by the user). You also need to be aware that ASPX loading is tied into the user's request path (unless you're using Routing or MVC) so you're better off using ASCX, not that it matters really.
A custom ASP.NET handler that runs in its own CAS sandbox that implements a fully-fledged templating engine
This is the most painful option, and it exists between the two: you get the flexibility of a first-class templating engine (loops, fields, evaluation if necessary) without needing to open your application up to gaping security flaws. The downside is you need to build pretty much everything by yourself. I won't go into detail here.
Which option you go for depends on what your requirements are. MySpace's system was more "skinning" than "templating", in that the users were free to set a stylesheet and define some arbitrary common HTML rather than modify their page's general template directly.
You can easily implement a MySpace-like system in ASP.NET assuming that each skinnable feature is implemented as a Control subclass, just extend your Render method to allow for the insertion of said arbitrary HTML. Adding custom stylesheets is also easy: just add it inside a <style type="text/css"> element in your page's <head>.
When/if you do allow the user to enter HTML directly, I strongly recommend you parse it and filter out any dangerous elements (such as <script>, <style>, <object>, etc). If you want to allow for the embedding of YouTube videos and related then you should analyse <object> elements to ensure they actually are of YouTube videos, extract the video ID, then recreate the element from a known, trusted template. It is important that any custom HTML is "tag-balanced" (you can verify this by passing it through a strict XML parser instead of a more forgiving HTML parser, as XHTML is (technically) a subset of HTML anyway), that way any custom markup won't break the page.
Have fun.

What's the purpose of an asp:hyperlink, and how many strings is too many in a resource file?

I developed a (small) company website in Visual Studio, and I'm addicted to learning more. I really just have two simple questions that I can't google.
1 - Asp:hyperlinks:
What is the purpose of an asp.hyperlink? I know I can't use these in my resource files -- I have to convert 'em all back to html links. At first, asp:hyperlinks looked sophisticated, so I made all my links asp:hyperlinks. Now I'm reverting back. What's the purpose of an asp:hyperlink, if any?
2 - Resource Files and strings:
In localizing my website, I have found that I'm putting the .master resource files in the directory's App_LocalResources folder VS created, because you can't change the top line stuff in a .master file and put a culture/uiculture in there. But all of my regular .aspx pages are going into the root App_GlobalResources folder into 1 of 4 language resource files (de, es-mx, fr, en). I'm making 2 or 3 strings per .aspx page. So when you have 47 pages in your website, that's about 100 strings on a resource page.
I just learned about all of the resources stuff from this forum and MSDN tutorials, so I have to ask, 'cause it's a lot of work. Is this okay? Is it normal? Am I going about this the wrong way?
I've never used resources, so can't comment on that.
Differences between asp:hyperlink and a tag that I know of:
asp:hyperlink is converted to an A tag by the ASP.NET engine when output to the browser.
It is possible asp:hyperlink could make browser specific adjustments, to overcome browser bugs/etc.. which is kind of the point of ASP.NET, or at least one of them. If not already in it, they could be added later, and by using those objects you'll get that when/if added.
Both can be used in code behind (you can set runat="server" for an A tag), but the asp:hyperlink has better compile-time checking in most cases -- strong type-casting for more items vs generic objects.
asp:hyperlinks are easier to get HTML bloat, but only if used with a poor design. For example, it is easy to set font styles and colors on them.. but I wouldn't, since that generates in-line styles that are usually pretty bloated compared to what you would do by hand or in a CSS file.
asp:hyperlinks support the "~/Folder/File.ext" syntax for the TargetUrl (href), which is nice in some projects if you use a lot of different URLs and sub-folders and want the server to handle mapping in a "smart" way.
The purpose of is to display a link to another webpage.
With the resource files, since you're not a programmer and just developing a small program, use something you're comfortable with. Resource files are easy to use for beginners when you want to localize your web content -- and yes, it's normal to be adding many strings if you need them.
For #1
Using a hyperlink control over just a piece of text will allow you to access the control at runtime and manipulate its contents if you want to change the link dynamically, if you have static links that will never change then its simpler to just use plain text ie. <a href=''>

Why are ASP.NET pages (both forms and MVC) dynamically compiled?

There is a pattern in ASP.NET - whenever there is a piece of markup that generates code (like the .aspx/.ascx files in WebForms or .cshtml files in MVC3), these files are dynamically compiled at runtime. aspnet_compiler will produce another assembly for them, which references your code-behind assembly.
This approach seems awkward to me and I don't understand why it hasn't been discontinued already. A much better approach (in my opinion) is like in Winforms or resource files - you have your .whatever file, and then there is .whatever.desginer.cs file. This designer file is created at runtime as you type. When you compile, the compiler doesn't care about your .whatever file, it just takes the .whatever.designer.cs file and produces a single solid assembly.
This provides several benefits:
You can inherit your forms from each other, similar to windows forms;
You can always see the code that is being generated, possibly adjusting your markup to generate better code;
You can easily instantiate strongly typed instances of your forms;
The only benefit I can see from dynamic compilation is that
You can change the markup file anytime and don't need to recompile the app.
To be honest, I've often wanted for one of the first three benefits, but never for the last one. Recompiling the app to see your changes isn't that big of a deal. Especially since you have to do it anyway when working with code-behind, where the most of your time will be. And when you deliver your app to the client, you deliver it as a monolithic, precompiled block. When you update, you update everything, not just individual .aspx files - there's no point to.
So... why is it like this? What am I missing?
It sounds like you are referring to an ASP.Net Website. An ASP.Net Web Application is like an ASP.Net Website, but uses .designer.cs files and produces a single assembly.
See ASP.NET Web Site or ASP.NET Web Application?.
One thought that comes to mind is that the primary difference between winforms and webforms has to do with the common development model.
Namely, there is a whole class of developers and designers who work strictly in html/css/javascript. They use a host of tools ranging from notepad on up to competing development products to build these pages.
Further, in the case of WinForms, MS has complete and total control of what can make up a form. Any controls that can be dropped on it have to descend from their specified code.
However, with HTML they don't have this same level of control. Spec changes occur out of sync with VS releases, additional features are added that are browser specific, etc. In short, they can't guarantee that a particular element in the HTML file is a valid element at all. All they can hope for is that whatever is sent was done so on purpose and that the browser knows how to deal with it.
Now they have tried to implement a model that provides visual inheritance. It's called "master pages". However, I believe the only tools that properly work with master pages are VS and Expression. Getting the other vendors to go down this path would be nearly impossible. Also, they've added the concept of "nested master pages" such that you can get multiple levels of inheritance out of them.
The code behind model helps to implement non-visual inheritance allowing people to completely revamp page processing (hence how MVCx works).
Which leaves us with the parts that MS does know about. Obviously they do have a .designer file which backs the .aspx pages. This designer file maintains the server control list that is accessible by the code behind. You could add runat="server" to every regular element in an html page (excluding artifacts like css) but this would increase the amount of processing required for the page.
To sum up, I think they've picked the best model they could for web development given the lack of control they have over how the web works. Other vendors have tried similar paths (e.g. Adobe Contribute, previously by Macromedia). I believe some of those even predate MS's model.

I thought Themes should be all about visual presentation?

Themes are control based and not html based – and as a result themes allow you to reuse almost any control property.
1)
a) Are there any control properties which affect the visual appearance of the control, but can’t be expressed through CSS?
b) If there are such properties, then I assume these properties are translated into Html and not CSS?! But that doesn’t make much sense, since CSS is far more capable of describing the visual appearance of a control!
c) Anyways, could you name me some of these properties?
2) I thought themes should be ( just like CSS ) all about presentation ( ie visual aspects of a Html document ), but that doesn’t seem to be the case, since controls also have many properties that don’t define the visual appearance of the rendered control?! In other words, I don’t see much usefulness for themes also specifying non-visually related control properties. Or am I missing something?
Thanx
Themes is an attempt at trying to replace CSS for redistributable controls. The main point of themes is that you have a more strongly typed syntax and a pre-built "skinning" framework.
In my opinion, Themes are a failure, for exactly the reasons you are describing - properties don't cover a wide enough range of DOM attributes to be more than marginally useful in specifying custom rendering for webcontrols. The additional coding needed to get obscure properties in negates the usefulness of themes the first time you need to code one. Additionally, having to learn an entirely new property syntax in order to abstract away CSS is counter-productive, since non-ASP.Net websites will never use it - in other words, it's just not standard.
Every webforms project I've worked on that started with Themes ended up dropping them for embedded CSS web resources.
To answer your questions:
a) Are there any control properties which affect the visual
appearance of the control, but can’t
be expressed through CSS?
I suppose it depends what you mean by "visual appearance". Adding an extra column to a grid, for example, certainly changes its appearance, but can't be done in CSS.
b) If there are such properties, then
I assume these properties are
translated into Html and not CSS?! But
that doesn’t make much sense, since
CSS is far more capable of describing
the visual appearance of a control!
Since a web page is basically HTML + CSS + Script, it makes sense that if the visual change isn't done with CSS, that it's probably HTML.
c) Anyways, could you name me some of
these properties?
How about the "Text" property on a <asp:Label>?
Themes are not "all about presentation."
Themes are simply a collection of CSS files, JavaScript files, images and skin files that work together. A Theme might contain a single CSS file, and have nothing at all to do with controls.
Skin files, though, are control-oriented. Skin files let you set property defaults for your controls. Most properties are default-able, not just the ones that control appearance. For example, if you're using GridViews in your application, skin files allow you to establish a standard appearance, rather than having to repeat the same property assignments every time the control is used.
StyleSheetThemes allow you to override those defaults on the page. Regular Themes take precedence over properties you assign on the page.
Also, collecting property defaults for your controls in a single place (the skin) makes them easier to manage, similar to what CSS classes do for HTML.

How can I design an ASP.NET website delaying the style/theme?

I need to build a prototype for an intranet website, and I want to focus on usability (layout, navigability, etc) and leave the theme for later (I have very bad taste, so this will probably be done by someone else)
I know about ASP.NET's capability of switching themes instantly, but how do I have to design the WebForms for it to be easy later?
Should I create controls with a class attribute pointing to something that will exist in the future css?
Or do I simply create the controls without worrying about this and it'll be handled easily when we create the theme?
If you're planning on using ASP.NET Themes, then you can design all of the controls generically and add Skins later on. Depending on the complexity of the design (meaning how many different styles you have for textboxes or gridviews, etc), this might not save you a lot of work, but it's one way to use the built-in .Net support for theming.
Make sure you use a MasterPage so that all of your sub pages will have a common base, and give all of your elements good IDs, because you will still need to get your hands dirty with CSS to put it all together.
Here's a link to a decent Themes & Skins tutorial. Knowing what you'll have to do in the future to add this in will make it easier to design for it now.
I'd like to make the argument for ignoring themes altogether and using nothing but CSS. It's never been clear to me what value themes add; it's a very Microsoft-specific approach, and its output isn't always standards-compliant. By using CSS you will widen the pool of potential designers able to work on your project, and you will have a better chance of having a cross-browser and standards-compliant site.
If someone else is going to be styling this later, I'd just make sure that you provide enough "hooks" for them to be able to design this. This means adding CSS classes to pretty much everything you do that will be styled similarly, and wrapping things in divs or spans with CSS classes where appropriate, for example
<div class="ButtonContainer">
<asp:linkbutton runat="Server" cssclass="Button Cancel" command="Save" text="Save" />
<asp:linkbutton runat="Server" cssclass="Button Save" command="Cancel" text="Cancel" />
</div>
If you don't have a solid understanding of CSS and you don't have in-house naming conventions or standard style sheets, though, you won't really know how to structure your divs and classes. In our shop, the way we handle this is the programmer just writes standard ASP.NET markup, and the designer goes through and adds divs, spans, and class names that work with the style sheet they will develop.
Skins are probably the answer, but something about that irks me (maybe because I don't like being that vendor specific and I'd like my skills to be applicable to other web languages and platforms than .NET). I prefer to use CssClass attributes on all of my ASP.Net controls and carefully class everything else and to use as much semantic markup as possible. Then, when I get the controls set up and working, I use CSS to style everything (although I usually have to tweak the HTML and JavaScript stuff at this point).
Another developer I work with prefers to do everything the Microsoft way with Skins and page directives and so on. It's probably the best way to do it, but it feels to me like it's mixing too much of the presentation into the middle and back-end of the application.
just wrap your controls in divs. will make layout/style much easier in the end

Resources