How can I read CSS properties in ASP.NET? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a CSS parser for C#?
I'd like to access some CSS properties of my website defined in an external .css file at runtime. I've found that there is a way to programmatically set css properties in the codebehind, but I haven't come across any way to read the ones that are already defined. (I'm using C#)

You can read them "at run time" only using client side script.
With jQuery it's really simple, plus you can then send the value to the server using AJAX then handle it or store it for later use.
If it's valid option let me know and I can post basic example of what I mean.
Basic example
First, the HTML used:
<div class="mydiv" id="testDiv">I'm red</div>
<button type="button" id="testButton">Test</button>
CSS:
<style type="text/css">
.mydiv { background-color: red; }
</style>
Now you have to include jQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
And finally have this JS code:
<script type="text/javascript">
$(document).ready(function() {
$("#testButton").click(function() {
var oDiv = $("#testDiv");
var sColor = oDiv.css("background-color");
$.get("TestZone.aspx?cssvalue=" + sColor);
alert("value has been sent");
});
});
</script>
This will send the runtime background color of the test div to the server when the button is clicked, and in the code behind of TestZone.aspx you can handle the value. The example send it over the querystring you can same way send it as POST data if you prefer.

This is the way to get the display value for aWebControl in the code behind:
aWebControl.Style["display"]

ASP.NET only deals with the markup of the page itself.
You can programmatically get or set inline styles (CSS declared inline with an element using the style attribute) using the WebControl.Style property. This gives you a collection of name/value pairs that represents the inline style for that element.
control.Style["font-family"] = "Verdana";
Inline styles are considered pretty unpleasant, so don't use them unless you have a really good reason.
Anything outside of the page, you cannot access with ASP.NET natively. Essentially, the external stylesheets are only loaded by the browser rendering the page and aren't handled by the ASP.NET runtime, so you don't get a chance to inspect them.
If you want to interpret those files, you will need to load them manually and parse them with a CSS parser. Have a look at this question for possible solutions:
Is there a CSS parser for C#?

Related

Redirect if JavaScript is not enabled [duplicate]

This question already has answers here:
How to detect if JavaScript is disabled?
(39 answers)
Closed 5 years ago.
I am working on a logic where I want user to be redirected to a particular page if JavaScript is not enabled. I have put a meta-tag which will refresh every few seconds and if JavaScript is enabled and I want to use JavaScript to remove that element.
I have tried many things but I have been unsuccessful in removing the tag. Also I tried to empty the content of the tag but it still redirects.
Is there any other way to deal with this issue?
I am posting some code for you to take a look, I just grabbed it from the web but seems to be emptying the contents when I debug through the code:
var m = $('meta');
for (var c = 0; c < m.length; c++) {
m[c].parentNode.removeChild(m[c]);
m[c].content = '';
}
I am also open to a server side solution but the client does not send much information such as if javaScript is enabled or not.......
Try this:
// THIS DOES NOT WORK
$( 'meta[http-equiv="refresh"]' ).remove();
It certainly depends on how soon your jQuery code executes and how soon your refresh triggers...
Update: The above method does not work. Even though the meta element is removed from the DOM, the browser still executes the refresh.
Live demo: http://www.ecmazing.com/misc/test-removing-meta-element/
I believe you should also be able to do this:
<noscript>
<meta http-equiv="refresh" content="...">
</noscript>
So, if you wrap your meta element in a NOSCRIPT element, it should only be parsed if JavaScript is disabled.
Read about the NOSCRIPT element here: https://developer.mozilla.org/en/HTML/Element/noscript

C# - Get JavaScript variable value using HTMLAgilityPack

I currently have 2 JavaScript variables in which I need to retrieve values from. The HTML consists of a series of nested DIVs with no id/name attributes. Is it possible to retrieve the data from these variables using HTMLAgilityPack? If so how would I go about doing so, if not what would be required, regular expressions? If the latter, please help me in creating a regular expression that would allow me to do this. Thank you.
<div style="margin: 12px 0px;" align="left">
<script type="text/javascript">
variable1 = "var1";
variable2 = "var2";
</script>
</div>
I'm assuming you are trying to scrape this information from a website? Most likely one you don't have direct control over? There are several ways to do this, I'll go easy to hard( at least as I see em):
Ask the owner (of the site). Most of the time they can give you direct access to the information and if you ask nicely, they might just let you have it for free
You can use the webBrowser control, run the javascript and then parse values from the DOM afterwards. As opposed to HttpWebRequest, this allows for all the proper values to be loaded on the page and scraped. Helpful Link Here.
Steal the source with Firebug. Inspect the website with Firebug to see which URLs are called from the background. Most likely, its using an asynchronous request to retrieving the updated information from a webservice. Using Firebug, you can view this under the NET -> XHR. Look at the request and the values returned, you can then retrieve the values your self and parse the contents from the source rather than scrape the page.
I think this might be the information you were looking for, but if not let me know and I can clarify/fix answer

Why does it make a difference where I include the jQuery script file?

On my master page (for all pages in my site) I have a ToolkitScriptManager.
On my content page, there are a series of hyperlinks and divs for collapsible functionality.
The code to show/hide the panels work like the following:
$(document).ready(function() {
// Hookup event handlers and execute HTML DOM-related code
$('#nameHyperLink').click(function() {
var div = $('#nameDiv');
var link = $('#nameHyperLink');
if (div.css('display') == 'none') {
link.text('Hide Data');
div.show('100');
}
else {
link.text('Show Data');
div.hide('100');
}
});
});
If I include a ScriptReference to the jQuery 1.4.2 file in the toolkitscriptmanager, the javascript code is executed incorrectly on the page (only the text for the hyperlink is changed, the div is not actually shown.) However, if I don't include the jQuery file in the ToolkitScriptManager and instead include it in the content page, it works correctly.
I'm a Javascript/jQuery newbie, and this makes no sense at all. What's going on here?
Positioning of the script include is important for the jQuery ref. If you look at your generated source I would bet the tag is below the script function(). You should make sure that the jQuery reference comes as early as you can get it in the page source.
Try moving the jQuery library reference into the head of your master page, that should work. Otherwise post up some source!
Like Tj says... should probably be in the head section of your master page. Also, it's nice to link to Google's version of this library, because chances are your users will already have it cached. For instance, look at the source for this very page.
The two most probable causes here are $ not being defined yet (see Tj's answer) and $ getting defined by another library, such as prototype.
I would highly suggest you look into using Firebug's javascript debugger, or at least take a look at Firefox's built in error console (Tools -> Error console). That will give you a much better clue what is going on other than "it's not working."

Trying to set/get a JavaScript variable in an ActiveX WebBrowser from C#

We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser.
We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object.
However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT type="text/javascript">
var field = 'hello world';
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="See field" onclick="javascript:alert(field);"/>
</BODY>
</HTML>
We want to access the field variable and assign a value to it. In VB6 the code for this was pretty straightforward:
doc.Script.field = 'newValue'
However, in C# we've had to resort to other tricks, like this:
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null);
The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".
That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable field.
Has anyone had any experience doing this type of operation before?
I think what you are looking for is the eval() method in Javascript. You can call it from C# like this:
webBrowser1.Document.InvokeScript("eval", new String[] {"1 + 2"});
This code will evaluate "1 + 2" and return "3". I would imagine that if you were to put in
InvokeScript("eval", new String[] {"varName = 3"})
you would get that variable assigned to 3 if it is globally visible in the file.
If you use the webBrowser control, you can assign a c# object to the
objectForScripting property
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx
after that you can use window.external in your javascript to interact with your c# object from javascript
if you use an activeX version for some reason, you can pass javascript: urls to programmatically sets your variable, or you can syncronize your script using a webservice/ database/file or simply using the method you suggested.
These two articles helped us find a solution to our problem. They outline the basics of what one needs to know:
Microsoft Web Browser Automation using C#
Using MSHTML Advanced Hosting Interfaces
So we implemented a DocHostUIHandler interface and that allowed us to set a UIHandler, allowing us to reference the method from Javascript.
The usual method we use is to add a hidden text input box (the ASP.Net control version) on the page. That way you can easily set its value in the C# codebehind and read the value in client side JavaScript (and vice-versa, of course).

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