How to turn on IE9 Compatibility View programmatically in Javascript - c#

I need to turn on IE compatibility programmatically.
I know this works in C# :
Page.Header.Controls.AddAt(0, new HtmlMeta { HttpEquiv = "X-UA-Compatible", Content = "IE=EmulateIE7" });
My problem is all my windows are displayed in a JS function: for instance:
function openRadWin(idAgir) {
radopen("DemandesEnAttente_Estimate.aspx?id=" + idAgir, "RadWindow1");
}
So my question is : is there any ways to do the same thing in JS?
Thanks in advance

AFAIK, this is not possible. You can detect the compatibility mode from JS but setting it is not possible to my knowledge.
As for as your problem goes, typically you can use few solutions:
If you are using Master pages in your site, add the meta header (<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">) in the master page.
Similar to #1, if you are using a common base page class (a good and recommended practice) then you can infuse the meta header from the common base page to all your pages.
Lastly, you can use IIS configuration to add the http header to all your response.
For example, for IIS7/IIS7.5, you can use web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-UA-Compatible" />
<add name="X-UA-Compatible" value="IE=EmulateIE7" />
</customHeaders>
</httpProtocol>
</system.webServer>
I would suggest #1 or #2 - in case you don't have master page or base page class then perhaps its a good time to introduce the both.

What your C# example does, is add the following meta tag to the html page:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
If you do this manually on the page that runs the JS code, it should work.

You could try adding this HTML tag to the top of any page that requires compatibility:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
That way you shouldn't need a JavaScript solution. Of course, if you have the ability to change the HTML, then the best solution would be to fix the page so it doesn't require backwards compatibility.
I believe that the only way to influence headers from the client side is when you request a page using an XmlHttpRequest. It doesn't make sense to me to talk about modifying headers after the page has loaded, which is in effect what you are asking.

Related

Styles.Render in MVC4

In a .NET MVC4 project how does #Styles.Render works?
I mean, in #Styles.Render("~/Content/css") which file is it calling?
I dont have a file or a folder called "css" inside my Content folder.
It's calling the files included in that particular bundle which is declared inside the BundleConfig class in the App_Start folder.
In that particular case The call to #Styles.Render("~/Content/css") is calling "~/Content/site.css".
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
Watch out for case sensitivity. If you have a file
/Content/bootstrap.css
and you redirect in your Bundle.config to
.Include("~/Content/Bootstrap.css")
it will not load the css.
A bit late to the party. But it seems like no one has mentioned
bundling & minification of StyleBundle, so..
#Styles.Render("~/Content/css")
calls in Application_Start():
BundleConfig.RegisterBundles(BundleTable.Bundles);
which in turn calls
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
}
RegisterBundles() effectively combines & minifies bootstrap.css & Site.css
into a single file,
<link href="/Content/css?v=omEnf6XKhDfHpwdllcEwzSIFQajQQLOQweh_aX9VVWY1" rel="stylesheet">
But..
<system.web>
<compilation debug="false" targetFramework="4.6.1" />
</system.web>
only when debug is set to false in Web.config.
Otherwise bootstrap.css & Site.css will be served individually.
Not bundled, nor minified:
<link href="/Content/bootstrap.css" rel="stylesheet">
<link href="/Content/Site.css" rel="stylesheet">
src="#url.content("~/Folderpath/*.css")" should render styles
As defined in App_start.BundleConfig, it's just calling
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
Nothing happens even if you remove that section.
Polo I wouldn't use Bundles in MVC for multiple reasons. It doesn't work in your case because you have to set up a custom BundleConfig class in your Apps_Start folder. This makes no sense when you can simple add a style in the head of your html like so:
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/bootstrap.theme.css" />
You can also add these to a Layout.cshtml or partial class that's called from all your views and dropped into each page. If your styles change, you can easily change the name and path without having to recompile.
Adding hard-coded links to CSS in a class breaks with the whole purpose of separation of the UI and design from the application model, as well. You also don't want hard coded style sheet paths managed in c# because you can no longer build "skins" or separate style models for say different devices, themes, etc. like so:
<link rel="stylesheet" href="~/UI/Skins/skin1/base.css" />
<link rel="stylesheet" href="~/UI/Skins/skin2/base.css" />
Using this system and Razor you can now switch out the Skin Path from a database or user setting and change the whole design of your website by just changing the path dynamically.
The whole purpose of CSS 15 years ago was to develop both user-controlled and application-controlled style sheet "skins" for sites so you could switch out the UI look and feel separate from the application and repurpose the content independent of the data structure.....for example a printable version, mobile, audio version, raw xml, etc.
By moving back now to this "old-fashioned", hard-coded path system using C# classes, rigid styles like Bootstrap, and merging the themes of sites with application code, we have gone backwards again to how websites were built in 1998.
I did all things necessary to add bundling to an MVC 3 web (I'm new to the existing solution). Styles.Render didn't work for me. I finally discovered I was simply missing a colon. In a master page: <%: Styles.Render("~/Content/Css") %> I'm still confused about why (on the same page) <% Html.RenderPartial("LogOnUserControl"); %> works without the colon.
Set this to False on your web.config
<compilation debug="false" targetFramework="4.6.1" />

Allow illegal characters in textbox

I have created a textbox for my users to enter their comments. So, sometimes they copy the error that has been raised in the application and paste in the textbox along with comments. It may include illegal characters (eg. </11>) but it should be saved but my .aspx is not allowing. I don't know how to handle this. thanks!
If you want user to edit TextBox and enter html tags you can disable this via
<%# Page validateRequest="false" ...>
or in the web.config for your entire application:
<system.web>
<page validateRequest="false" />
</system.web>
Note that this ValidateRequest property is not existing without
reason. When you change its default value, insecure input will be
accepted. Because of that, you need to validate every user's input to
avoid cross-site scripting attacks, like inserting of malicious
JavaScript, ActiveX, Flash or HTML
Another smart solution is to replace via javascript text written by user to make it safe for validation.
< anyword> , instead of <anyword> is considered safe!
function validateTxt() {
$("textarea, input[type='text']").change(function () {
html = $(this).val(); //get the value
//.replace("a" , "b") works only on first occurrence of "a"
html = html.replace(/< /g, "<"); //before: if there's space after < remove
html = html.replace(/</g, "< "); // add space after <
$(this).val(html); //set new value
});
}
$(document).ready(function () {
validateTxt();
});
i assume you are talking about an exception message like "A potentially dangerous Request.Form value was detected from the client..."
that is the asp.net request validation in action. this can be disabled at the page or site level, but there are risks associated with doing so.
it is done with ValidateRequest="false" in the page directive or in web.config.
more information here:
http://www.asp.net/learn/whitepapers/request-validation
You can try to encode the content in Base64 before transferring it. But i'm not sure my solution is really good.
http://nolovelust.com/post/classic-asp-base64-encoder-decoder.aspx
It could be due to the HTML being rejected server-side, as a security precaution.
You can disable this check by either:
Adding the following attribute to the page header <%# Page validateRequest="false" %>
or making the change application wide in the Web.Config:
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>

How can I get a web site's favicon?

Simple enough question: I've created a small app that is basically just a favourites that sits in my system tray so that I can open often-used sites/folders/files from the same place. Getting the default icons from my system for known file types isn't terribly complicated, but I don't know how to get the favicon from a website. (SO has the grey->orange stack icon in the address bar for instance)
Does anyone know how I might go about that?
You'll want to tackle this a few ways:
Look for the favicon.ico at the root of the domain
www.domain.com/favicon.ico
Look for a <link> tag with the rel="shortcut icon" attribute
<link rel="shortcut icon" href="/favicon.ico" />
Look for a <link> tag with the rel="icon" attribute
<link rel="icon" href="/favicon.png" />
The latter two will usually yield a higher quality image.
Just to cover all of the bases, there are device specific icon files that might yield higher quality images since these devices usually have larger icons on the device than a browser would need:
<link rel="apple-touch-icon" href="images/touch.png" />
<link rel="apple-touch-icon-precomposed" href="images/touch.png" />
And to download the icon without caring what the icon is you can use a utility like http://www.google.com/s2/favicons which will do all of the heavy lifting:
var client = new System.Net.WebClient();
client.DownloadFile(
#"http://www.google.com/s2/favicons?domain=stackoverflow.com",
"stackoverflow.com.ico");
Updated 2020
Here are three services you can use in 2020 onwards
<img height="16" width="16" src='https://icons.duckduckgo.com/ip3/www.google.com.ico' />
<img height="16" width="16" src='http://www.google.com/s2/favicons?domain=www.google.com' />
<img height="16" width="16" src='https://api.statvoo.com/favicon/?url=google.com' />
You can use Google S2 Converter.
http://www.google.com/s2/favicons?domain=google.com
Source: http://www.labnol.org/internet/get-favicon-image-of-websites-with-google/4404/
This question is the first google search result I got when I keep searching for website favicon API. So I think it'll be still helpful in the future.
https://icon.horse/icon/[url.hostname] will give you a better site icon.
https://icon.horse/icon/stackoverflow.com
You can do it without programming in 3 steps:
1. Just open the web site, right-click and select "view source" to open the HTML code of that site. Then in the text editor search for "favicon" - it will direct you to something looking like
<link rel="icon" href='/SOMERELATIVEPATH/favicon.ico' type="image/x-icon" />
Take the string in href and append it to the web site's base URL (let's assume it is "http://WEBSITE/"), so it looks like
http://WEBSITE/SOMERELATIVEPATH/favicon.ico
which is the absolute path to the favicon. If you didn't find it this way, it can be as well in the root in which case the URL is http://WEBSITE/favicon.ico.
2. Take the URL you determined and insert it into the href-Parameter of the following code:
<html>
<head>
<title>Capture Favicon</title>
</head>
<body>
<a href='http://WEBSITE/SOMERELATIVEPATH/favicon.ico' alt="Favicon"/>Favicon</a>
</body>
</html>
3. Save this HTML code locally (e.g. on your desktop) as GetFavicon.html and then double-click on it to open it. It will display only a link named Favicon. Right-click on this link and select "Save target as..." to save the Favicon on your local PC - and you're done!
It's a good practice to minimize the number of requests each page needs.
So if you need several icons, yandex can do a sprite of favicons in one query.
Here is an example
http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/
The first thing to look for is /favicon.ico in the site root; something like WebClient.DownloadFile() should do fine. However, you can also set the icon in metadata - for SO this is:
<link rel="shortcut icon"
href="http://sstatic.net/stackoverflow/img/favicon.ico">
and note that alternative icons might be available; the "touch" one tends to be bigger and higher res, for example:
<link rel="apple-touch-icon"
href="http://sstatic.net/stackoverflow/img/apple-touch-icon.png">
so you would parse that in either the HTML Agility Pack or XmlDocument (if xhtml) and use WebClient.DownloadFile()
Here's some code I've used to obtain this via the agility pack:
var favicon = "/favicon.ico";
var el=root.SelectSingleNode("/html/head/link[#rel='shortcut icon' and #href]");
if (el != null) favicon = el.Attributes["href"].Value;
Note the icon is theirs, not yours.
In 2020, using duckduckgo.com's service from the CLI
curl -v https://icons.duckduckgo.com/ip2/<website>.ico > favicon.ico
Example
curl -v https://icons.duckduckgo.com/ip2/www.cdc.gov.ico > favicon.ico
You can get the favicon URL from the website's HTML.
Here is the favicon element:
<link rel="icon" type="image/png" href="/someimage.png" />
You should use a regular expression here. If no tag found, look for favicon.ico in the site root directory. If nothing found, the site does not have a favicon.
HttpWebRequest w = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com/favicon.ico");
w.AllowAutoRedirect = true;
HttpWebResponse r = (HttpWebResponse)w.GetResponse();
System.Drawing.Image ico;
using (Stream s = r.GetResponseStream())
{
ico = System.Drawing.Image.FromStream(s);
}
ico.Save("favicon.ico");
Sometimes we can't get the favicon image with the purposed solution as some websites use .png or other image extensions. Here is the working solution.
Open your website with a firefox browser.
Right-click on the website and click the "View page info" option from the list.
It will open up a dialog and click on the "Media" tab.
In that tab you will see all the images including favicon.
Select the favicon.ico image or click through the images to see which image is used as favicon. Some websites use .png images as well.
Then click on the "Save As" button and you should be good to go.
thanks!
This is a late answer, but for completeness: it is difficult to get even close to fetching 90% all favicons.
A while ago I wrote a WordPress plugin which attempts to get closer to 100%.
This is how it works:
It starts by searching existing favicon repositories such as Google favicons and GetFavicons for the favicon.
If none of them returns an icon, the plugin attempts to get the icon itself. This involves traversing several pages on the domain.
The plugin then inspects the physical image file, because on some servers files get returned with the incorrect mime types.
The code is still not perfect because in the details you will find many weird situations: people have wrongly coded paths, e.g. img/favicon.ico where img is not in the root, duplicate headers in HTML output, different server responses from the head and body etc.
The core of the fetching part is here so you can reverse-engineer it, but be aware that validating the response should be done (checking image filetype, mime etc.).
The SHGetFileInfo (Check pinvoke.net for the signature) lets you retrieve a small or large icon, just as if you were dealing with a file/folder/Shell item.
http://realfavicongenerator.net/favicon_checker?site=http://stackoverflow.com gives you favicon analysis stating which favicons are present in what size. You can process the page information to see which is the best quality favicon, and append it's filename to the URL to get it.
You can use Getfv.co :
To retrieve a favicon you can hotlink it at... http://g.etfv.co/[URL]
Example for this page : http://g.etfv.co/https://stackoverflow.com/questions/5119041/how-can-i-get-a-web-sites-favicon
Download content and let's go !
Edit :
Getfv.co and fvicon.com look dead. If you want I found a non free alternative : grabicon.com.
Using jquery
var favicon = $("link[rel='shortcut icon']").attr("href") ||
$("link[rel='icon']").attr("href") || "";

Why is a meta refresh tag and title tag sitting outside of the <head> tag in ASP.NET?

When I render a page in ASP.NET, the following happens
</head>
<NOSCRIPT>
<meta http-equiv="REFRESH" content="0;URL=/Default.aspx?id=84&epslanguage=en-GB&jse=0" />
</NOSCRIPT>
<title>Page title goes here.</title>
<body>
My masterpage looks like this:
<title>Page title goes here.</title>
</head>
<body>
So what I'm asking is, where the heck has this refresh meta tag come from, why has it put it between my head tag and body tag, and why has my page title jumped outside of the head?!
When viewing the page's generated source in firebug, it shows the title tag and this new meta tag within the head tag, but viewing the source in any browser, it looks like the above. When using wget to scrape the page, it also comes out incorrectly as displayed above.
Any ideas why browsers may be interpreting this in different ways, and more importantly where this new meta tag has come from?
Thanks! Karl.
Edit:
Hi!
Thanks for your replies guys, very informative!
I've discovered that the problem is this line of code:
Page.Header.Controls.Add(ctrl);
Putting the mysterious meta tag in using this line puts it outside the head tag. When commenting this out, the title tag drops back into the right place, and all is well!
Any further thoughts?
Thanks!
Karl.
On the matter of why browsers will be interpreting it differently there are two answers. Firstly the firebug output as you say is generated source. That means its gone through a certain amount of processing already and clearly firefox is doing some magic to say "Well, its a meta and a title tag, they should be in the header so I'll put them there."
The other browsers you are comparing their raw source it sounds like which is before the browser has tried to make sense of it. I suspect you'd get the same if you viewed the raw source in firefox (ctrl-u).
I'd have expected all browsers to do much the same thing as you have described firefox as doing but if not then that's not really somethign to be concerned about. When invalid HTML like this is received the browsers have no real rules of what to do. This means that browsers are welcome to do whatever they want from trying to guess what you meant to just ignoring it entirely.
As for what is causing it, the epslanguage query paramter is from episerver - I don't know if that was in the request url or not so it may be that it is just being persisted or it may be episerver trying to redirect to a page with an explicit language instead of just assuming the default. Unfortunately I'm not familiar with episerver so I can't say any more specific to that.
It is of course definitely the case that there is something on your server side that is causing this to happen.
Do you get that for all pages out of interest or just one specific one or just in one specific circumstance?
Quite often it's a case of an element not being properly closed. Most browsers will try to adjust the markup so that it makes sense, but in most cases the markup will be incorrectly parsed.
You should probably share more of your master page (and the web form using it)!
Maybe your HEAD-tag doesn't have runat="server"?

Style Sheet is not working in one web page

Style sheet in master page is not working for one web page of asp.net application but it works for another web page.
If you are referencing a css file from a master page you should ensure it has an absolute path, that way it will work everywhere. For example:
<head runat="server">
<link type="text/css" rel="stylesheet" href="~/_styles/mystylesheet.css" />
</head>
The important thing to note here is that the head tag has the runar="server" attribute and that i am specifying the full virtual path using a tilde ("~").
Are none of its style elements being included? Is it being over ridden( they are Cascading Style Sheets)? Does it have the correct CSS include statement?
Are your pages in different levels of folders ?
For example,
..\main.css
..\folder1\MasterPage.master
..\folder1\css_working.aspx
..\folder1\folder2\css_not_working.aspx
in this scenario you should define your css in masterpage as :
<link rel="stylesheet" type="text/css" href="../main.css" />
And take your pages to same level, like that :
..\main.css
..\folder1\MasterPage.master
..\folder1\css_working.aspx
..\folder2\css_not_working.aspx
If you are using update panels there are some cases where the styling may be lost for AJAX toolkit controls. To fix this you need to put hte full name of hte class items into the stylesheet instead of letting hte toolkit handle this.
Also be sure to use a relative url where possible so that if a file moves it won't loose it's mapping.
Use Firebug or Debug Bar, these tools will show you all the styles being employed on each element, so you can see what stylesheets it is using and which ones it is not.
Also, when you build check for any warnings about stylesheets that it can't reference etc.
it could be a permission issue on the folder... if you have deny users="?" in your web config.. make sure you have an allow users on the folder where you have your style sheets

Categories