Change DocType dynamically

I have a single page(created before Master pages were available) that loaded dynamically one or another user control.Some child controls have css for quirk mode, but for new controls I want to use latest DocType
<!DOCTYPE html>
The solution is to set it dynamically in code-behind depending on current control to load(the code is copied from http://stackoverflow.com/questions/174916/how-do-you-specify-your-content-type-in-asp-net/6932768#6932768)

=========aspx===============
<%@ Page Language=“C#” AutoEventWireup=“true” CodeFile=“Default.aspx.cs”
Inherits=“_Default” %>

<asp:literal runat=“server” id=“DocType”></asp:literal>

<html xmlns=“http://www.w3.org/1999/xhtml”>
<head runat=“server”>
==============code behind=========
protected void Page_Load(object sender, EventArgs e)
{
string docType;
if(PageId==”OLD”)
docType= “<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0
Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>”;
else
docType= “<!DOCTYPE html>”

this.DocType.Text= docType;

}

Set Offset to not attached div doesn’t work correctly in IE

We want to dynamically show an image below a span html element. 
The javascript creates a div element, than assigns new offsets using jQuery offset() and then appends the div to document.
It worked as expected in FireFox, but moved the new element to the bottom of the page in IE.
I found, that if I will call offset after document.body.appendChild, it will assign values correctly.

In the test page below if offset is called  after document.body.appendChild,
new img assigned left: -8, top: 110
img left: -8, top: 110  -expected
If offset is called  before document.body.appendChild,
new img assigned left: -8, top: 110
img left: 0, top: 214   -wrong

The test page OffsetAfterAppend.htm: <!
DOCTYPE html> <html> <head>     <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body>  <p style="height:"100px">Offsets to show</p>  <p id="currentP"> Hello <span id="curr" style="background-color:Green">span to be above the image </span></p>    <p></p>   <script>       var p = $("p:first");        var s = $("span:last");        var currentOffset = s.offset();        p.html("span left: " + currentOffset.left + ", top: " + currentOffset.top);            var currentHeight = 20;         YOffset = 40;       XOffset = -55;       sImageURL = "http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif";                  var divMapContainer = document.createElement('div');         var imgMap = document.createElement('img');         $(imgMap).attr('src', sImageURL);         $(imgMap).attr('alt''');         $(divMapContainer).append($(imgMap));         newLeft = currentOffset.left + XOffset;         newTop = currentOffset.top + currentHeight + YOffset;         p.html(p.html() + "<BR/>new img assigned left: " + newLeft + ", top: " + newTop);         //$(divMapContainer).offset({ top: newTop, left: newLeft });          document.body.appendChild(divMapContainer);          $(divMapContainer).offset({ top: newTop, left: newLeft });          var img = $("img:last"); var imgOffset = img.offset();          p.html(p.html() + "<BR/>img left: " + imgOffset.left + ", top: " + imgOffset.top)   </script> </body> </html>

 

Combining javascript files

I’ve read Combining Client Scripts into a Composite Script and wanted to use it.
Then I’ve read Julian Jelfs concerns ScriptManager.CompositeScript issues

However the article Combining javascript files with Ajax toolkit library describes workarounds, that make the solution workable.
You also can use Script reference profiler: http://aspnet.codeplex.com/releases/view/13356

Related posts:

Using ScriptManager with other frameworks

MSDN documentation: CompositeScriptReference

The older implementations, that has been superseded by CompositeScript class:
ToolkitScriptManager

Combining, Compressing, Minifying ASP.NET ScriptResource and HTML Markups

Implementations of HTML TidyLib for .Net

I was considering to add the HtmlValidator class to codeplex,  but noticed that there are a few different implementations of HTML TidyLib for .Net. Not sure if any of them support my requirement to validate only structural errors, i.e. unmatched(not closed) open tags and unmatched(extra) close tags. But standard Tidy functionality will be good for most of users.

1. TidyManaged (https://github.com/markbeaton/TidyManaged)
Recent development (June 12, 2010), Positive reviews(e.g. here),Not much user activity in forums

Pro: Wrapper-easy upgrade to latest version of TidyLib.
Cons: As a wrapper  it won’t work in things like silverlight, and it requires you know the platform you’ll be executing on at compile-time.  Still, for many uses those restrictions aren’t an issue.(reason from Eamon Nerbonnes StackOverflow post)
 

2. TidyForNet (http://tidyfornet.sourceforge.net/ Wrapper for HTML Tidy and wvWare, using C# and interop.Release Date 2007-02-24

The same Pro& Cons for a wrapper Not much user activity

3. Tidynet.(http://tidynet.sourceforge.net/ )

A native .NET implementation -port from C.

Updated 2005-06-28,Not much user activity in forums
As not wrapper, opposite pro&cons: it will work on any .Net platform, but will not have any fixes from native TidyLib development.

4. A managed wrapper for the HTML Tidy library Code Project C++
Sample,how it can be done with single method implemented.

5. .NET Wrapper for HTML Tidy, based on a COM+ Wrapper for HTML Tidy

Related
http://stackoverflow.com/questions/4002346/c-version-of-html-tidy

Validation of Html file

We’ve used HtmlAgilityPack based function IsValidHtmlFragment(string html) to validate dynamically loaded Html Fragments before inserting into main page(or do not insert if it is invalid) and recently noticed that it doesn’t return false for some fragments with not closed tags.

I decided to find some other tool to call from the code and found that most of HTML parcers are too forgivven(like browsers) or too strict- to check full XHTML conformance.
I am going to add manual procedure to run Tidy.EXE (parameters are listed here)or use Tidy Online to FIX the errors before adding new html into the system, but still want to ensure, that Html with incorrect structure not inserted.

I found an article “C# Validate XHTML” with source code and decided to use it as a start point. Unfortunately there are quite a few things in the original code, that didn’t work as I expected/wanted, so I had to spend much more time to change it that I originally thought. Thanks to Sam Allen for very responsive answers.
I’ve put source code of this class to http://geekswithblogs.net/mnf/archive/2011/06/01/htmlvalidator-class.aspx  and consider to add it to codeplex at http://htmlvalidator.codeplex.com/

Other options, that I’ve looked :

TidyManaged– I noticed it after writing the class and not checked it yet. It may be solve what I want to have. 

http://www.webpronews.com/using-the-api-for-the-wc-html-validator-2006-11 -USELESS, because download link is broken.

http://www.blackbeltcoder.com/Articles/strings/parsing-html-tags-in-c (code project has slightly older version of the same article http://www.codeproject.com/Articles/57176/Parsing-HTML-Tags-in-Csharp.aspx) -does parsing, but not validation.

http://social.msdn.microsoft.com/Forums/en/regexp/thread/6aebedb1-9dc2-468b-9bb4-a1ecda3d0311 How to write a regular expression to validate text input as Html? –
regex isn’t the best solution for parsing HTML.

W3C Markup Validator library in C # http://sourceforge.net/projects/w3cmarkupvalida/

If I understood it correctly, it assumes that file is a valid XML document. Also it has restrictive GNU license.

 

Free Broken Links Validators

From http://www.thefreecountry.com/webmaster/htmlvalidators.shtml

W3C Link Checker

Worried about broken links in your web documents? This online validator from the W3 Consortium is able to recursively check your document for dead links. You simply enter a URL in the form provided, and it will visit your site and check the links.


Doesn’t validates frame pages from frameset, quite slow.e.g my site main page document processed in 264.04 seconds.

Xenu Link Sleuth: Find Broken Links

Xenu is a utility for Windows that checks your web site for broken links. It can work both with a “live” website as well as on a copy of your web site residing on your own hard disk. It’s a favourite of many webmasters for checking broken links on their site.


I haven’t try it yet.

JavaScript function to Redirect parent of IFrame to specified URL

    /// <summary>
   /// Redirects parent of IFrame to specified URL
   /// If current page doesn’t have parent, redirect itself
   /// </summary>
   /// <param name=”page”></param>
   /// <param name=”url”></param>
   public static void NavigateParentToUrl(Page page, string url)
   {
    String script = @”
try
{
var sUrl='” + url + @”‘;
if (self.parent.frames.length != 0)
    self.parent.location=sUrl;
else
  self.location = sUrl;
}
catch (Exception) {}
“;
    page.ClientScript.RegisterStartupScript(TypeForClientScript(), MethodBase.GetCurrentMethod().Name, script, true);
   }
   /// <summary>

Insert CSS link with updatable version number in URL

More than a year ago I wrote a post Code Render Blocks does not work inside HEAD server controls about the problem, that prevented me to update URL of CSS file, when version of assembly incremented.
Now I’ve created a function  

  
       /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="cssFileHref">e.g. "~/StyleSheet.css"</param>
        /// <returns></returns>
        public static HtmlLink AddStyleSheetLink(this Page page, string cssFileHref)
        {
            if (page.Header == null) { throw new NullReferenceException("page.Header is null"); }
            HtmlLink link = new HtmlLink();
            link.Href = cssFileHref;
            link.Attributes.Add("rel", "stylesheet");
            link.Attributes.Add("type", "text/css");
            page.Header.Controls.Add(link);
            return link;
        }  

 
and called it from markup aspx.

<% //this.AddHeadItems();CSSHelper.AddStyleSheetLink(this,“MyStylesFile.css?v=”+Utility.AssemblyVersionNumber()); %> 

Similar function in VB has been described in StyleSheetsManage class for DotNetNuke  post.

Note that I intentionally calling it from markup instead of code behind to be able manually change URL(e.g to ?v57=”) without new version rebuild to force refresh of CSS file in client browsers.
 
Initially it failed with the error:
Additional information: The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).
 , but I was able to delete code render blocks out off HEAD block.
 
Then I found, that if I am calling AddStyleSheetLink after <HEAD runat=”server”> block, the call has no effect and link to CSS file is not inserted.
But when I’ve put AddStyleSheetLink before HEAD, it works as expected 

<% //this.AddHeadItems();
CSSHelper.AddStyleSheetLink(this,“MyStylesFile.css?v=”+Utility.AssemblyVersionNumber()); %>

<HEAD runat=”server”>
….
</HEAD>
 
and generates  desired html: 

 <HEAD><meta content=”Microsoft Visual Studio 7.0″ name=”GENERATOR” /><meta content=”C#” name=”CODE_LANGUAGE” /><meta content=”JavaScript” name=”vs_defaultClientScript” /><meta content=”http://schemas.microsoft.com/intellisense/ie5” name=”vs_targetSchema” />
<link href=”MyStylesFile.css?v=2.0.0.0″ rel=”stylesheet” type=”text/css” />
</HEAD>

Alternative approach suggested in automatically-version-your-css-and-javascript-files/ is to append the number to the file name itself and then use RewriteRule processor (e.g. utilizing “URL Rewriting Using ISAPI_Rewrite” http://www.helicontech.com/articles/provocative_SEF_URLs.htm )