Eval Function in C# - c#

How Can I Evaluate a String in C# Windows Application because I need to Dynamically select object in a form based on the Combination of 2 String that give me the name of the needed object

You can tryControlCollection.Find method to find control by name.
For example:
MyForm.Controls.Find("FooButton", true);
Method returns an array of Control element with the Name property set to "FooButton".
There is no C# eval equivalent. But by the link you can find some useful answers. Ofc, if you want to find or evaluate something than winform controls
UPDATE: I think sometimes it is better get control by key directly. For example:
Control control = this.Controls["FooTxtBox"];
if(control==null)
{
MessageBox.Show("Control not found");
}
control.Text = "something";

This is a feature (compiler as a service) that should be available in the next version of the .NET Framework, version 5.
Perhaps reflection could be your solution for this?

Just use the string as the lookup for the Form.Controls collection. Then when you've got the instance of the control, just call whatever method you need on it to select it.

Have a look at this:
http://www.logiclabz.com/c/evaluate-function-in-c-net-as-eval-function-in-javascript.aspx (Link is dead, please provide an updated source)

Related

How to get actual JavaScript value in onclick from webbrowser control?

I'm looking for a way to get the JavaScript code defined inside of onclick.
I'm using .NET 2.0 C# Visual Studio 2005.
Example:
<span id="foo" onclick+"window.location.href='someURL'>click here</span>
My goal is to get the string "window.location.href='someURL'".
Scenario:
A user clicks on web page element, the tag shown above for instance, inside of WebBrowser control. Then the clicked tag is refereed to HtmlElement object.
In WebBrowser control I then call HtmlElement object's getAttribute("onclick"), it just gives me "System.__ComObject".
I've searched how to deal with it then found that it can be casted then get the value.
if (tag.GetAttribute("onclick").Equals("System.__ComObject"))
{
Console.WriteLine("dom elem >>>>>>>>>>> " + tag.DomElement.ToString());
mshtml.HTMLSpanElementClass span = (mshtml.HTMLSpanElementClass)tag.DomElement;
Console.WriteLine("js value ===>" + span.onclick);
}
Output:
dom elem >>>>>>>>>>> mshtml.HTMLSpanElementClass
js value ===> System.__ComObject
As it shown, span.onclick still give me System.__ComObject, what am I doing wrong?
In Why does HtmlElement's GetAttribute() method return “mshtml.HTMLInputElementClass” instead of the attribute's value? this guy said it worked in his case, and I've followed it, but mine is somewhat not working...
UPDATE
Research, research.....
I can add reference VisualBasic.dll to my C# project then call the method to find out who is this System.__ComObject really is.
Console.WriteLine(Microsoft.VisualBasic.Information.TypeName(span.onclick));
Output:
JScriptTypeInfo
It looks like this is a JScript type... how can I access this object?
More detail
The above description is based on my current project. The project is to create something like Selenium IDE. It uses WebBrowser control instead.
Selenium IDE creates 3 different things to record an element in the web document.
1. actionType
2. xpath
3. value
For instance,
type, //input[#id=foo], "hello world"
clickAndWait, //link=login, ""
Selenium IDE recognize page load so it changes actionType between "click" and "clickAndWait". My case, I want to make it simple.
If I click on the element and if it is anchor tag or has page load kind of javascript
such as onclick=window.location.href='blah' then I want to set the actionType to "clickAndWait".
There are number of ways you can do it.
There is an Event object in DOM, which will give you information about which element generated this event.
You can look at here, http://msdn.microsoft.com/en-us/library/ff975965%28v=VS.85%29.aspx
This one is good, you can use this easily, you will get the event object as method parameter which you can investigate parameters to find out the source of the event. http://support.microsoft.com/kb/312777
Another alternative is to use a custom navigation url and act upon it
Override BeforeNavigate event
Check for Navigation url if it contains "mycommand:click" or "mycommand:clickandwait" 3. If it contains any of this, then set cancel as true. (this will stop navigation by browser).
Then you can navigate your webbrowser code from your C# code and pass cancel as true.
Another Alternative method is to use External object, WebBrowser allows you to set an ObjectForScripting which you can access within Javascript of HTML.
ObjectForScripting in .NET 2.0
[ComVisible(true)]
public class MyClass
{
// can be called from JavaScript
public void ShowMessageBox(string msg){
MessageBox.Show(msg);
}
}
myBrowser.ObjectForScripting = new MyClass();
// or you can reuse instance of MyClass
And you can call,
window.external.ShowMessageBox("This was called from JavaScript");
Cast the element object to mshtml.IHTMLDOMNode, then read the attributes via IHTMLDOMNode.attributes. HtmlElement.GetAttribute is getting the IDispatch interface of the jscript function generated from the embedded attribute.
As per Sheng Jiang's response, here is some working sample:
IHTMLElement element = YourCodeToGetElement();
string onclick = string.Empty;
IHTMLDOMNode domNode = element as IHTMLDOMNode;
IHTMLAttributeCollection attrs = domNode.attributes;
foreach (IHTMLDOMAttribute attr in attrs)
{
if (attr.nodeName.Equals("onclick"))
{
string attrValue = attr.nodeValue as string;
if (!string.IsNullOrEmpty(attrValue))
{
onclick = attr.nodeValue;
break;
}
}
}
You can try to parse webBrowser1.DocumentText property using HtmlAgilityPack and then get desired result using XPath.
If you don't HAVE to do it with C# (you can do it with JS and create a Postback) you should take a look at THIS question.
You can parse it yourself easily, by first reading obj.outerHtml. That should give you the entire html for that obj, then search it for the value onclick="????" and extract the ???? part.

Find open Windows in XAML

I need a functionality to get all existing (open) instances of some conrete WPF window. I create those windows programatically in few places in code.
Is there a XAML/WPF solution for that? Something like GetInstancesByType(type)?
You can use the Application.Windows property:
foreach( var window in Application.Current.Windows.OfType<MyType>() )
{
// do stuff
}
As H.B. pointed out, you would need to include System.Linq to get the OfType<T> extension method, but it's not necessary.

Using user controls having his name on a string

i have a problem, the functionality I'm looking for exactly is:
I have a grid and datagrid, according to the line to select the datagrid there will be to introduce a user control or other user controls are different pictures I've made polylinesegments, bezier cuadratic ... to introduce the call will name, which build on a string, but I have no way to call it correctly.
This is what I do and it works by putting the full name:
d48.Children.Add(new tratsPintados.end148());
But put the string, tells me not find the path in the project, what I want is to find the path inside the string.
d48.Children.Add(new thestring());
Any ideas?
If you need to instantiate some class based on its name (without real reference), you will need to use Reflection.
Maybe you can do some lookup by name for the class you need, and then use Activator.CreateInstance to call its default constructor.
I hope this is what you want, the question text is quite confusing to me.
using System.Reflection;
public object GetObjectFromString()
{
string objectName = "WpfApplication1.uc1";
Type newType = Type.GetType(objectName, true, true);
object o = Activator.CreateInstance(newType);
// do what you want with the 'o' variable, maybe cast it to the type you want.
}

Passing dropdowncontrol name as parameter to method in c#

I have asp.net application. where on 2 web pages i have dropdown on each page. i want to populate the User list in drop down. so as usual i wrote the method FillUserDropDown() in common helper class.
and accessing this method on both page loads. but I am passing the Drop down control as parameter to this method so that method appears generic for all type of fill drop downs. Is this standard way? my seniors are avoiding me to passing the control as parameters.
So what is the best practice for this scenario? Please guide me.
To databind is better. But this is also acceptable just that you can let ASP.NET 'fill' it in automatically if you databind (it will generate the code for you). Return a datatable or list and and specify declarivly the binding.
Also tell your seniors that it's ok to do that too. If you've written the code already leave it.
Call Method By this way
FillDropDown(DropDownID, selectListItemText)
Set Below Code In your commonfile
DropDownID.DataTextField =
"TextFieldName";
DropDownID.DataValueField =
"ValueFieldName";
DropDownID.DataSource =
DatasourceName; DropDownID.DataBind();
if (includeSelectItem) {
DropDownID.Items.Insert(0, new
ListItem(selectListItemText,
selectListItemValue)); }
This way you can bind as you said above

C# dynamic control names in .NET CF

I'm working with .NET CF framework in c#, and I want to know if I can access the controls somehow like this:
string field="txtName";
this.Controls[field];
or is this impossibile?
I think the method you're after is FindControl - you'll find that method on anything with a Controls collection.
What about using Linq?
var myControl = this.Controls.Cast<Control>().OfType<WhateverControlType>().FirstOrDefault(cont => cont.ID == "myControlId");
Something like that?
I don't see why it would be wrong, the indexer expects a string, and you're passing a string, so for me it's correct.
It is possible to reference a control in the control collection by name (stirng) or index (int). The only thing you will need to do additionally is cast the control into the type of object it is. Something like the following.
MyControl c (MyControl)this.Controls["ControlName"];
Enjoy!

Categories