ASP.NET MVC on IIS6 rendering issue - c#

I have a small asp.net mvc app running on WIN2k3 and IIS6.
I'm using a wildcard mapping under the application settings in IIS as described in this article http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx . The application works fine under my local asp.net development server. When I publish from VS2008 out to the production server above the styles are looking partially rendered. For instance. I have an overflow: hidden; set on the body {} and the browser is showing a scrollbar horizontally and vertically. Also, the z-index on all my layers are incorrect. Any ideas would be much appreciated.
Here's a sample of my document head.
<head>
<meta http-equiv="Content-Language" content="en-us" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>page title | <%= ViewData["PageTitle"]%></title>
<link rel="shortcut icon" href="/content/images/misc/favicon.ico" type="image/x-icon" />
<%= Html.MooFrameworkConfig("Default")%>
<%= Html.JavaScript("/scripts/framework.js")%>
</head>
framework.js includes the CSS like so:
this.loadCSS("layout.css", "screen");
here is the loadCSS method:
framework.loadCSS = function(fileName,mediaType) {
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = '/content/skins/' + skinBase + '/css/' + fileName;
cssNode.media = mediaType;
headID.appendChild(cssNode);
}

Just as a test, does linking to the CSS file in the HTML (as opposed to loading it with JS) fix the problem?

It is unlikely to be a problem with the web server, per say. Is it possible that the stylesheet you're using isn't being served by the webserver? Maybe the URL to it is slightly different? Check by navigating manually to the stylesheet or by checking that it is being loaded in firebug.

Did you include the CSS fix from the article?
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
I think you may need to post snippets from your website where you include the CSS file and where you simulate the article so that you can get better tips.

You can use Fiddler tool to check if all the files are loaded correctly, I mean no HTTP 403 or 500 or some other status codes for all the files (.css,.js) included in your page.
There maybe some server settings preventing displaying your page correctly.

Related

ASP.NET C# function in HTML

I have faced a lot of issues with CSS and JS caching, so i decided to add timestamps to CSS and JS files.
so i added this param at the end of links:
?t=<%= DateTime.Now.Ticks %>
So here how it looks like:
JS:
<script type="text/javascript" src="Scripts/global_scripts.js?t=<%= DateTime.Now.Ticks %>"></script>
CSS:
<link rel="stylesheet" type="text/css" href="Styles/mysite.css?t=<%= DateTime.Now.Ticks %>" />
The JS file work fine. But for CSS files this param ?t=<%= DateTime.Now.Ticks %> gets recognized as a string. Why? I cannot find the difference
You can easily solve your problem with this simple adjustement
<link rel="stylesheet" type="text/css" href="Styles/uberhint.css?t=<%= "" +DateTime.Now.Ticks %>" />
Just add "" +.
ASP.NET is treating the link as an HtmlLink control, and rendering the contents of the href attribute as a literal. Inserting that Extra string forces ASP.NET to accept that you are trying to generate a dynamic string
While this is not an answer to your original question, I can suggest you to use a different approach altogether. Instead of adding ticks, you can use default Microsoft libraries to make bundles. When you do it that way, the engine will automatically add a string like ?v=dfsdf9fsdfasd which will be a hash of the content, so every time it changes it will be different. Then you can just cache forever the resources forever on the client.
Your approach is problematic since the browser will download js every time, this is extremely inefficient.
You can get some details on how to use bundles with minification e.g. here. Please see my answer for some details on how to make script bundles properly.
P.S. If you don't want to do bundling yourself, you can still implement the hash of the file content yourself. Another easy option is to do ?v=1, where you get the version from config, then by changing the config, you will be able to force cache update on all you clients.
With all of the approaches you should set cache for 1 year (max if I remember correctly).
If the above answers dont work, you can try to add a
<asp:placeholder runat="server" id="ph">
above script and css tag, and in the page_load you can bind placeholder.
ph.DataBind();

Downloading file with webscraper sometimes yields HTML page

I have a C# application to access data from a third party website. I'm using WebClient and I call DownloadData and process the bytes(DownloadFile would yield similar results).
This worked fine until recently. Now, more often than not, instead of the desired XML file, I get an html page similar to:
<!-- _localBinding -->
<!-- _lcid="1033" _version="" -->
<html>
<head>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8" />
<meta HTTP-EQUIV="Expires" content="0" />
<noscript>
<meta http-equiv="refresh" content="0; url=/_layouts/spsredirect.aspx?noscript=1" />
</noscript>
<script language="javascript" src="/_layouts/1033/init.js"></script>
<script language="javascript" src="/_layouts/1033/core.js"></script>
<script language="javascript">
var requestedUrl = escapeProperly(window.location.href);
STSNavigate("/CustomErrors/ErrorPage.aspx?oldUrl=" + requestedUrl);
</script>
</head>
<body></body>
</html>
I'm stumped as to why this went from consistently working to consistently giving me problems. Sometimes, I can still get the expected XML file. Do you have an idea of what this issue might be and how I can fix it?
It might be worth noting that if I were to click the download link manually in a browser, a javascript window would pop up and close before the file downloads. I'm using WebBrowser to intercept the non-static URL of that popup and pass that link (and headers/cookie information) to WebClient. The link would look something like https://foo.bar/Something.axd?Session=1234vv1234Format=XML
Thanks for your time
It looks like the third-party page is throwing an exception. This could be due to parameters you are passing it, or it could be a problem on their end. The best course of action would be to contact the provider and see what errors are being logged (hopefully they are logging them somewhere). Otherwise you are just going to be guessing at what you are doing wrong.
Is it possible that there are encoded\escaped characters in the session querystring param that are not being handled properly? That would be my first guess since there aren't any real error details.
If it's throwing an error, I'd attempt to collect the HTTP status code, you can do this by using the HttpWebRequest and HttpWebResponse (I believe these pre-dated WebClient). There's tricky ways to still use WebClient and retrieve the status code as well, I'd check the content type as well before you actually download.
In any condition, even if serving an error page, the server should respond with an appropriate HTTP status code. (At least in a perfect world).

Navigating trough objects of a web page, using an embedded web browser

I have a Windows Forms application that uses a WebBrowser control to display an embedded web page. The file is (successfully) loaded using:
webHelp.DocumentStream=
Assembly.GetExecutingAssembly()
.GetManifestResourceStream("MyAssembly.help.html");
In order for this to work (i.e. the file to be loaded/displayed) I set the webHelp.AllowNavigation = false;. I don't fully understand why, but if it's set to true, the page is not displayed.
In my HTML document (see bellow) I want to be able to navigate trough different sections. But when I click on a link, the browser control does not go to the targeted element. The web page works fine in the stand-alone Internet Explorer 10, so it must have something to do with the control, more specifically the AllowNavigation property. MSDN didn't help much.
How can I achieve this navigation behavior? Is there another way of loading the HTML file without setting the AllowNavigation property to false?
This is my simple HTML file:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Using this tool</title>
</head>
<body>
<h3>Description</h3>
<div><p id="contents">Contents</p></div>
<div>
<p id="general">Using the file converter</p>
<p>*converter description*</p>
Go To Top!
</div>
<div class="divBlock" >
<p id="selectOption">Selecting a conversion action</p>
<p>*action selection*</p>
Go To Top!
</div>
</body>
</html>
EDIT: After additional tests I found the root of the problem. The problem appeared after setting a value for the URL property, running the application and afterwards clearing this value. The embedded page is not loaded any more, unless the AllowNavigation property is set to false. There are two solutions, described in my answer bellow.
I also have my own WebBrowser. I've tested it and it loads your HTML file perfectly.
I simply used:
webBrowser1.Navigate("C:\\myPath\\SofNavigate.html");
When I click on links it goes to "#contents" without problems.
I am not sure why you need to use webHelp.Docstream instead of simple Navigate.
By the way, when I turn off navivation, then I am not able to go anywhere from the page that I started on. So Navigation must be on in order to go anywhere from the "home page".
Try to debug that part, as it appears to be the bigger problem that you have.
Here is a good example on how to set up simple webBrowser. Try to use it as a base and see what you do differently that messes up your navigation.
[EDITED] Win8/IE10, your code works for me unmodified inside Form.Load event on a simple form which has just a single WebBrowser control with all default settings (and WebBrowser.AllowNavigation is true by default). Check the properties of your WebBrowser control in the Designer, you may have something wrong in there.
[/EDITED]
You're using HTML5, which handles anchor links via id attribute (i.e. <p id="contents"> ... <a href="#contents">. By default, WebBrowser control works in legacy IE7 mode with HTML5 disabled. You need to turn it on with FEATURE_BROWSER_EMULATION feature control, before WebBrowser object gets created. The best place to do this is a static constructor of your form:
static MainForm()
{
SetBrowserFeatureControl();
}
private static void SetBrowserFeatureControl()
{
// http://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx#browser_emulation
// FeatureControl settings are per-process
var fileName = System.IO.Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
// make sure the control is not running inside Visual Studio Designer
if (String.Compare(fileName, "devenv.exe", true) == 0 || String.Compare(fileName, "XDesProc.exe", true) == 0)
return;
// web pages containing standards-based !DOCTYPE directives are displayed in Standards mode
using (var key = Registry.CurrentUser.CreateSubKey(
#"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
RegistryKeyPermissionCheck.ReadWriteSubTree))
{
key.SetValue(fileName, (UInt32)9000, RegistryValueKind.DWord);
}
}
Try it and your links should work as expected. This solution does NOT require admin rights, the affected key is under HKEY_CURRENT_USER.
[UPDATE] There may be a better solution, it works at least for IE10 here on my side. Add <meta http-equiv="X-UA-Compatible" content="IE=edge" /> as below and leave the registry intact. If you see document.compatMode: CSS1Compat, document.documentMode: 10, you should be good to go, but test with older IE versions too.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<script type="text/javascript">
window.onload = function () {
info.firstChild.data =
"document.compatMode: " + document.compatMode +
", document.documentMode: " + document.documentMode;
}
</script>
</head>
<body>
<pre id="info"> </pre>
</body>
</html>
EDIT: After finding the cause of the problem (see the edit to the question) I can now propose three solutions:
1. WebBrowser control replacement:
Simply delete the existing WebBrowser control and add a new one. This solution does not require any modification of the AllowNavigation property. DO NOT modify the URL property.
2. When deleting and adding a new WebBrowser control is not an option:
Since the AllowNavigation property was influencing the loading and displaying of the web page, there was no reason for it to be left to false afterwards. Setting back the property in the Shown event solved the navigation problem, without requiring other alterations (e.g. in the HTML file or the Registry):
private void helpForm_Shown(object sender, EventArgs e)
{
webHelp.AllowNavigation = true;
}
3. Reseting the Document
It seams that the Document property gets (automatically) initialized if URL property is at one time set and reset. Adding webHelp.Document.OpenNew(true); before loading the resource stream solves the problem without the need for re-adding the WebBrowser and without modifying the AllowNavigation property.

asp.net cache css and script but not the page

In my master page in the Page_Load method, I have this line:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Basically, I don't want to cache the page. I do want to cache the .js and .css files but when I reload the page, these files don't get loaded from the browser cache but instead get reloaded.
What do I need to fix?
Thanks.
Add these lines in the html meta section
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="0">
<META HTTP-EQUIV="PRAGMA" content="NO-CACHE">
in ASP page
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
This article can be usefull to resolve your issue
http://www.codeproject.com/Articles/11225/Disabling-browser-s-back-functionality-on-sign-out
P.S. If it didn't help. You can use cheat like this: <%= here you should add some random number for example Ticks %> - add it for elements which shouldn't be cached.
For example:
<link rel=stylesheet href="main.css?<%= ... %>">
You need to set up caching for static resources (.js and .css) files. This is not enabled by default.
See this SO answer for more details: https://stackoverflow.com/a/2196848/69868
Also note that when you are reloading the page using F5/Ctrl+F5, some browsers will ignore caching instructions and they will always fetch fresh content (for example Firefox and Ctrl+F5). If you want to test caching, reload the page by re-entering the URL in location text box.

ASP.Net - Path Problems caused by Encoded URLs

I am building a web store and I am having a bit of a problem with some of the urls.
I have a large directory of departments and categories in my database that I am using to form my main menu.
The URLs have the form Application/Store/Department/Category
(All store URLs are rewritten to store.aspx?Querystringstuff)
The problem is that some of the urls generated by my code work, but prevent the page's CSS from loading properly.
It is specifically the URLs who's source text contain slashes.
I am URL encoding the source text of course but I'm still having the problem.
My css is linked in a master page-
<link rel="stylesheet" type="text/css" href="~/CSS/Layout.css" runat="server">
Example Links that work -
Ice Machines
http://localhost:1079/ABCWeb/Store/Refrigeration+Equipment/Ice+Machines.aspx
Steam Table Pans
http://localhost:1079/ABCWeb/Store/Catering+%26+Buffet/Steam+Table+Pans.aspx
Example Links that break-
Napkin Holders/Dispensers
http://localhost:1079/ABCWeb/Store/Tabletop/Napkin+Holders%2fDispensers.aspx
Salamanders/Cheesemelters
http://localhost:1079/ABCWeb/Store/Cooking+Equipment/Salamanders%2fCheesemelters.aspx
If it matters here is my code for building URLs-
The array contains an array of items in the path
The first element is not encoded as it contains the the current store path.
private static System.Text.StringBuilder AppendAnchor(this System.Text.StringBuilder str, string[] path)
{
return str.Append("<a href='")
.Append(path.Aggregate((a, b) => a + "/" + HttpUtility.UrlEncode(b)))
.Append(".aspx'><span>")
.Append(HttpUtility.HtmlEncode(path[path.Length-1]))
.Append("</span></a>");
}
Thanks for the help!
Try including your style-sheets using a path relative to the web root. An easy way to do this in ASP .NET webforms is to use ~ on a server-side control eg.
<link rel="Stylesheet" type="text/css" href="~/Css/MyCssFile.css" runat="server" />
ASP.NET should then resolve the correct URL for you, regardless of what the URL is.
Well I looked a little further into it-- The "~" actually seems to be where the problem is occurring.
The links are working correctly but I think the server isn't parsing it correctly when it generates the relative paths...
Here is the css link from the generated code on a working link
../../CSS/Layout.css
Here is the css link on a broken page at the same depth
../../../CSS/Layout.css"
Here is a very ugly fix that works- not sure if there is a better way though
<link rel="stylesheet" type="text/css" href="<%=Request.ApplicationPath+"/Css/Layout.css" %>" />
The strange thing is that the navigation links generated from similar paths in the sitemap are working fine. Maybe it understands the full hierchy better when it is generating paths from the site-map and doesn't try to build a relative path.

Categories

Resources