get html element font-size - c#

I would like to get the font-size for an html element in a web page, for example a <p> tag.
This should be valid even for element without a style or class attribute, so it has to know dynamically inherited css attributes.
I've tried with html agilitypack, a very good lib, but of course it doesn't consider css rendering. Tried also with WPF webbrowser, but it seems it cannot get font size for every element, and for many of them it returns a percentage.
Javascript getComputedStyle() is not suitable since all should run server side.
Any ideas?

Try this:
Element.prototype.getStyle = function (prop) {
if (document.defaultView)
return document.defaultView.getComputedStyle(this, null)[prop];
else
return this.currentStyle[prop];
}
call:
document.getElementById("div1").getStyle("font-size");

Related

Getting element by Id

Selenium, NUnit testing, C#, Visual Studio.
How, in Selenium WebDriver, can I locate element in a page source that looks like following, and set some text in its <p> tag:
<body contenteditable="true" class="cke_editable cke_editable_themed cke_contents_ltr cke_show_borders" spellcheck="false">
<p></p>
</body>
This is body tag from CKEditor component present on a page (not a main page <body> element ).
Actually, I need to set some text in <p> element. What is confusing to me , is that class attribute is complicated, contains from several strings. I am aware of command: driver.findElement( By.className( "some_class_name" )); but how to use it in this case and to set some text in <p> element?
If you give the p tag an ID like so
<p id="derp">Text here</p>
You can send text to it using Selenium like this
driver.find_element_by_id("derp").sendKeys("herp");
Hope this helps!
EDIT: Without adding an ID to the element, you might be able to do something like this
driver.findElement(By.className("some_class_name")).findElement(By.tagName("p")).sendKeys("herp");
If you want the p elelement then this relative xpath should work.
//body[#class='cke_editable cke_editable_themed cke_contents_ltr cke_show_borders']/p
That is assuming that there is only a single body element with this class attribute.
As you are saying, there is no id usable for location, so you have to come up with a different solution.
Selenium is capable of using css selectors - it's the same scheme found in CSS files to specify to which elements the following styling rules should apply.
One possible locator would be the following:
body.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders > p
Advantage over XPath: CSS selectors are aware about groups, so they don't handle them only as strings. Using just an XPath expression against the exact class attribute, your recognition would fail if there would be another, new class withing the attribute. Using CSS selectors, it's possible to really just identify per class.
Simplified and boiled down to the classes that really describe your editable element, the following should be sufficient:
body.cke_editable.cke > p

How to get html control by ID that has hyphens?

I have a front end written in html that I am converting to asp, and many of the controls have names with "-" in them. This is causing crazy headaches, as there is no time to rename everything, and the ctrl-f and replace somehow breaks my css. Is there any way to access these controls in the code behind while they have the dashes? I have tried the code below.
//Can find when there is no dash in it, but that breaks the css after find/replace of full solution
HtmlGenericControl body = (HtmlGenericControl)this.Page.FindControl("page-list");
body.Attributes.Add("class", GlobalVariables.webAppSkin);
//I have also tried this, but logout stays null
WebControl logout = (WebControl)Page.FindControl("logout-link");
This is the html control:
<body id="page-list">
Sorry, that's not gonna happen.
You cannot have an element with an id containing "-", and still be a runat="server" ASP.NET control.
Microsoft's docs about the control's IDs states:
http://msdn.microsoft.com/en-us/library/system.web.ui.control.id.aspx
Only combinations of alphanumeric characters and the underscore character ( _ ) are valid values for this property. Including spaces or other invalid characters will cause an ASP.NET page parser error.
If you tried adding runat="server" to the body tag you showed: <body id="page-list">, it would give you the following line in aspx.designer.cs:
protected global::System.Web.UI.HtmlControls.HtmlGenericControl page-list;
Which is obviously throwing an exception on C# syntax.
<body id="page-list"> is not a HTML Control (i.e. an instance of (a subclass of) System.Web.UI.Control because it doesn't have the runat="server" attribute. If you were to add runat="server" then you would get a JIT compile-time error message informing you that "page-list" is not a valid identifier.
ASP.NET Web Forms 4.0 added the ClientIDMode attribute, however it doesn't allow you to set a completely custom ID attribute value. There's no easy solution for this without using <asp:Literal> or implementing your own control (or my preferred option: switching to ASP.NET MVC).
You can access controls in code behind with their ID if you write runat="server". Here is the example for your case
<body runat="server" id="testID">
In code behind you can access it like this:
body.Attributes.Add("class", value);

Printing html file with pagebreaks

I am trying to create a program / service that can read an html file and print it.
I need to include page breaks; but don't know how to define them or make them print correctly.
The html files are mine, so I can add any elements to them to represent the page break position. I was thinking a hidden field, or using the page-break-before:always css style in the next element.
How should I approach this?
Css is the way to go. I'd recommend to create a class "page-break":
.page-break { page-break-before: always; }
Whereever you add this class to an HTML-element you get a page-break before this element (e.g. before every h1).
This tutorial covers almost every part of CSS and printing:
http://coding.smashingmagazine.com/2011/11/24/how-to-set-up-a-print-style-sheet/
hope this helps

How to remove wordwrap from a webbrowser and or set font size smaller

I am using a 2 web browsers to compare texts, and when the lines become to long it wraps my text, i would like to remove this or lower my font size to avoid this.
Can some one please advise me on how to remove the word warp or change font size on web Browsers?
The word wrap below totally miss alines my compare:
As far as I know, there is no property of the web browser control that can do this. The presentation of the web page is controlled entirely by the web page itself.
If you cannot change the web page itself, the best you can do is to possibly cache a local version and change its styling using WebBrowser.Document.ExecCommand(). WebBrowser.Document.InvokeScript() also works but requires already-defined JS, so we have to go ahead and add in the script manually.
HtmlElement head = webBrowser.Document.GetElementsByTagName("head")[0];
HtmlElement script = webBrowser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement;
element.text = "function adjust { document.getElementById('yourIdHere').style.whiteSpace='nowrap'; }";
head.AppendChild(script);
webBrowser.Document.InvokeScript("adjust");
Just find the div id of the text by looking at the web page's source code and you should be golden. If it doesn't have a div id, you can use other JS methods (such as getElementsByTagName) to find it.
You can not adjust font size or wrapper text from the web control its self. So you should adjust the styling of the elements inside the web browser.
I adjusted the styling at the same place i styled the green and red highlighting.
html.Append("<ins style=\"white-space:nowrap; display:inline; background:#e6ffe6;\">")
.Append(text)
.Append("</ins>");
"white-space:nowrap; display:inline;
The above code is what i added to remove word wrapping.
Inspired by Pomster's Answer, that's what I did to get the best result:
String.Format("<div style='white-space:nowrap; display:inline;'>{0}</div>",text);
c# 6.0 version:
$"<div style='white-space:nowrap; display:inline;'>{text}</div>";

Element-Enhancing Javascript in ASP.NET Master Pages

I have run in to a bit of a problem and I have done a bit of digging, but struggling to come up with a conclusive answer/fix.
Basically, I have some javascript (created by a 3rd party) that does some whizzbang stuff to page elements to make them look pretty. The code works great on single pages (i.e. no master), however, when I try and apply the effects to a content page within a master, it does not work.
In short I have a master page which contains the main script reference. All pages will use the script, but the parameters passed to it will differ for the content pages.
Master Page Script Reference
<script src="scripts.js" language="javascript" type="text/javascript" />
Single Page
<script>
MakePretty("elementID");
</script>
As you can see, I need the reference in each page (hence it being in the master) but the actual elements I want to "MakePretty" will change dependant on content.
Content Pages
Now, due to the content page not having a <head> element, I have been using the following code to add it to the master pages <head> element:
HtmlGenericControl ctl = new HtmlGenericControl("script");
ctl.Attributes.Add("language", "javascript");
ctl.InnerHtml = #"MakePretty(""elementID"")";
Master.Page.Header.Controls.Add(ctl);
Now, this fails to work. However, if I replace with something simple like alert("HI!"), all works fine. So the code is being added OK, it just doesn't seem to always execute depending on what it is doing..
Now, having done some digging, I have learned that th content page's Load event is raised before the master pages, which may be having an effect, however, I thought the javascript on the page was all loaded/run at once?
Forgive me if this is a stupid question, but I am still relatively new to using javascript, especially in the master pages scenario.
How can I get content pages to call javascript code which is referenced in the Master page?
Thanks for any/all help on this guys, you will really be helping me out with this work problem.
NOTES:
RegisterStartupScript and the like does not seem to work at any level..
The control ID's are being set fine, even in the MasterPage environment and are rendering as expected.
Apologies if any of this is unclear, I am real tired so if need be please comment if a re-word/clarification is required.
Put a ContentPlaceHolder in the head section of the master page, then add a asp:Content control on the content page referring to the placeholder and put your script in that control. You can customize it for each page this way.
Also, the reference by ID may not be working because when you use Master Pages, the control IDs on the page are automatically created based on the container structure. So instead of "elementID" as expected, it may be outputting "ctl00_MainContentPlaceHolder_elementID" View your source or use firebug to inspect your form elements to see what the IDs outputted are.
Isn't it possible to do with clean javascript ?-)
-- just add something similar to this inside the body-tag:
<script type="text/javascript">
window.onload = function(){
MakePretty("elementID");
}
</script>
By the way the script-tag has to have an end-tag:
<script type="text/javascript" src="myScript.js"></script>
Why not use jQuery to find all the controls? Something like this:
$(document).ready(function(){
$("input[type='text'], input[type='radio'], input[type='checkbox'], select, textarea").each(function(){
MakePretty(this);
});
});
This way you'll get all elements on the page, you can wait until the page is ready (so you don't modify the DOM illigally). The jQuery selector can get the elements in a bit more of a specific format if you need (ie, add a root element, like the ID of the body div).
It'd also be best to modify the MakePretty method so it takes the element not the ID as the parameter to reduce processing overhead.
Once you use Master Pages, the ids of controls on the client side aren't what you think they are. You should use Control.ClientID when you generate the script.
When using master pages, you need to be careful with the html attribute ID, since .NET will modify this value as it needs to keep ids unique.
I would assume your javascript is applying css styles via ID, and when you are using master pages the ID is different than what is in your aspx. If you verify your javascript is always being added, your answer needs to take into account the following:
ALWAYS set your master page id in page load (this.ID = "myPrefix";)
Any HTML element in your master page will be prefixed by the master page id (i.e.: on the rendered page will be "myPrefix_myDiv")
Any HTML element in your content place holder id will be prefixed with an additional prefix (i.e. myPrefix_ContentPlaceHolderId1_myDiv)
Please let me know if I can clarify anything. Hope this helps!

Categories