Get the value of an attribute from webbrowser1 - c#

I have the following code which extracts all URLS within Google's search results:
private void button1_Click(object sender, EventArgs e)
{
HtmlElementCollection a = webBrowser1.Document.GetElementsByTagName("a");
foreach (HtmlElement b in a)
{
string item = b.GetAttribute("href");
if (item.Contains("url?q="))
{
listBox1.Items.Add(item);
}
}
}
However I need this to be more specific.
Google's Chrome element inspector has this and I need to access the URL in this element:
<cite class="_Rm">www.dicksmith.com.au/apple-<b>ipad</b></cite>
The class is "_Rm", its in a 'cite' tag, and I need that URL ONLY.

Find html element with specified 'class' and 'tag' values. Then retrieve an url from InnerHtml.
HtmlElement FindHtmlElement(string tag, Predicate<HtmlElement> predicate)
{
try
{
var elements = webBrowser1.Document.GetElementsByTagName(tag);
foreach (HtmlElement element in elements)
{
if (predicate(element))
{
return element;
}
}
}
catch (Exception ex)
{
//Log.Error("Error on finding html element on {0}. Exception: {1}", _webBrowserBot.Url.ToString(), ex.Message);
}
return null;
}
private void button1_Click(object sender, EventArgs e)
{
// search for <cite class="_Rm">www.dicksmith.com.au/apple-<b>ipad</b></cite>
var element = FindHtmlElement("cite", (h) =>
{
return h.GetAttribute("class") == "_Rm";
});
string url = "";
if (element != null)
{
// retrieve url only
int ix = element.InnerHtml.IndexOf("-<b>");
if (ix > 0)
url = element.InnerHtml.Remove(ix);
// url obtained
//...
}
}

Related

C# get folderpath from TreeListNode in treeList devexpress

I use XtratreeList with fileExplorerAssistant. I have a problem when I want to get the path of the selected folder from treelist. Or I have a problem in getting the folder path from TreeListNode. Please help me.
My code is :
private void frmMovieAddAuto_Load(object sender, EventArgs e)
{
// Scan for all partitions
System.IO.DriveInfo[] driveList = System.IO.DriveInfo.GetDrives();
foreach (var drive in driveList)
{
// Select only logical fixed partitions
if (drive.DriveType == System.IO.DriveType.Fixed && drive.IsReady)
{
// Add each drive as a root node
treeListExtension1.RootNodes.Add(new PathNode(drive.RootDirectory.ToString()));
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
TreeListColumn columnname;
columnname = treeList1.Columns[0];
columnname.Caption = "Folder Name";
List<TreeListNode> nodes = treeList1.GetNodeList();
foreach (TreeListNode node in nodes)
{
if (node.Checked == true)
{
DirectoryInfo di = new DirectoryInfo(node.GetValue(columnname).ToString());
foreach (FileInfo fi in di.GetFiles("*.avi;*.mpg;*.mpeg;*.mp4;*.mkv;*.divx;*.AVI;*.MPG;*.MPEG;*.MP4;*.MKV;*.DIVX", SearchOption.AllDirectories))
{
//do something
}
}
}
}
In this code:
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
// Get the node that is currently focused (selected) in the TreeList
TreeListNode focusedNode = treeList1.FocusedNode;
// Get the column that contains the folder path
TreeListColumn folderPathColumn = treeList1.Columns[0];
// Get the value of the folder path column from the focused node
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
if(focusedNode.Checked == true)
{
pathfolderList.Add(folderPath);
}
}
In this line code:
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
It gives this error:
'Object reference not set to an instance of an object.'
Your question is how to get the full path of a DevExpress.XtraTreeList.Nodes.TreeListNode. This requires traversing the DisplayText from the selected node up to its root, When this collection is reversed and combined, the result is the full path.
foreach (var node in treeList1.GetNodeList())
{
List<string> builder = new List<string>();
TreeListNode traverse = node;
// This adds the display text from the leaf to the root.
while(traverse != null)
{
builder.Add(traverse.GetDisplayText(0));
traverse = traverse.ParentNode;
}
// What we want is the root to the leaf, so reverse the list.
builder.Reverse();
// Now combine into a path.
var path = Path.Combine(builder.ToArray());
Debug.WriteLine(path);
}
You might also find the DevExpress documentation helpful (their approach is slightly different).

Web Browser Control Not working properly

I will post my code below. I have a form with a web browser component. It is named webBrowser1. For some crazy reason when I run this in debug mode, and put a break point at System.Threading.Thread.Sleep(2000); The code before it appears not to have ran at all. The basic idea of this program is to login to a website , search for a part number, then return that part numbers description. Why is that happening? There are two buttons, the login button and the signout button. Signout is button 2, and login is button 1.
public partial class Form1 : Form
{
HtmlElementCollection firstPage;
HtmlElementCollection secondPage;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// First Do login page if that comes up
try
{
// Insert userName
HtmlElementCollection firstPage = webBrowser1.Document.All;
foreach (HtmlElement element in firstPage)
{
if (element.GetAttribute("className") == "logininput" && element.Name== "username" )
{
element.SetAttribute("value","userName");
}
}
// Insert password
foreach (HtmlElement element in firstPage)
{
if (element.GetAttribute("className") == "logininput" && element.Name == "password")
{
element.SetAttribute("value", "Password");
}
}
// Submit
webBrowser1.Document.GetElementById("loginsubmit").InvokeMember("click");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
try
{
System.Threading.Thread.Sleep(2000);
//Search For Part
var mfgPartNumber = "CRCW12061R00FKEA";
webBrowser1.Document.GetElementById("txtsearch").SetAttribute("value", mfgPartNumber);
webBrowser1.Document.GetElementById("btnsearch").InvokeMember("click");
System.Threading.Thread.Sleep(50);
//Get Part
secondPage = webBrowser1.Document.All;
foreach (HtmlElement element in secondPage)
{
if (element.GetAttribute("className") == "SE-Content-PartSearch-Grid-Row-Description")
{
MessageBox.Show("got here");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
firstPage = webBrowser1.Document.All;
foreach (HtmlElement element in firstPage)
{
if (element.GetAttribute("className") == "SE-BannerLogoutLable")
{
element.InvokeMember("click");
}
}
}
}

Find PlaceHolder another PlaceHolder

I've strange problem... :/
I have on my page PlaceHolder, where I generate dynamically more PlaceHolders.
I've stored names of this dynamicaly created PlaceHolders.
When I try to find any of this PlaceHolders - I've got error null reference to an Object.
Please help! :)
private void btnMoreInfo_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string[] componentName = button.ID.Split('_');
String controlName = null;
foreach (String singlePlaceHolder in placeHolderNames)
{
if (singlePlaceHolder.Contains(componentName[0]))
controlName = singlePlaceHolder;
}
Control cph = this.Master.FindControl(controlName);
Label helperlabel = new Label();
helperlabel.Text = "That one!";
cph.Controls.Add(helperlabel);
cph.Visible = true;
}
I changed code to this, and it's working now:
var cph = FindControlRecursive(this.Master, controlName);
plus I added new method:
private Control FindControlRecursive(Control root, string id)
{
if(root.Id==id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t= FindControlRecursaive(c, id);
if (t !=null)
{
return t;
}
}
return null;
}

How to make my method to wait for button click event in winforms

I have winForms project , my button_click 1 is add in elements of my one of documents chapters and sections. I want to save my configurations in configurations file test.json (it is written by JSON format) . I am saving everything what is chosen by checking check boxes. And later I want to load what check boxes are checked. But how to wait till button_click1 event will be clicked and my check boxes will appear. My load files looks like:
private void SaveConfig(string path)
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
foreach (TreeNode node in treeView1.Nodes)
{
{
config.Parts.Add(new DocPart { NodeTitle = node.Text, NodeChecked = node.Checked });
}
{
foreach (TreeNode child in node.Nodes)
{
config.Parts.Add(new DocPart { ChildTitle = child.Text, ChildChecked = child.Checked });
}
}
var configString = config.SaveToString();
File.WriteAllText(path, configString);
}
}
private void LoadConfig(string path)
{
var cfgString = File.ReadAllText(path);
var cfg = DocConfig.LoadFromString(cfgString);
foreach (var part in cfg.Parts)
{
foreach (TreeNode node in treeView1.Nodes)
{
if (part.NodeTitle == "chap1")
{
node.Checked = part.NodeChecked;
}
if (part.NodeTitle == "chap2")
{
node.Checked = part.NodeChecked;
}
if (part.NodeTitle == "chap3")
{
node.Checked = part.NodeChecked;
}
}
}
}
}
}
Removed button1_click() and added this class
private void Initializetreeview();
treeView1.Nodes.Add(new TreeNode("chapter1") { Tag = #"\include {chapter1}" }); ;
treeView1.Nodes.Add(new TreeNode("chapter2") { Tag = #"\include {chapter2}" });
treeView1.Nodes.Add(new TreeNode("chapter3") { Tag = #"\include {chapter3}" });
treeView1.Nodes[0].Nodes.Add(new TreeNode("section1") { Tag = #"\input {sec1}" });
treeView1.Nodes[1].Nodes.Add(new TreeNode("section2") { Tag = #"\input {sec2}" });
treeView1.Nodes[2].Nodes.Add(new TreeNode("section3") { Tag = #"\input {sec3}" });
Removing from added list button2_Click:
private void button2_Click(object sender, EventArgs e)
{
RemoveChecked(treeView1.Nodes);
}
void RemoveChecked(TreeNodeCollection nodes)
{
foreach (TreeNode checkedNode in FindCheckedNodes(nodes))
{
nodes.Remove(checkedNode);
}
}
private List<TreeNode> FindCheckedNodes(TreeNodeCollection nodes)
{
List<TreeNode> checkedNodes = new List<TreeNode>();
foreach (TreeNode node in nodes)
{
if (node.Checked)
{
checkedNodes.Add(node);
}
else
{
// find checked childs
checkedNodes.AddRange(FindCheckedNodes(node.Nodes));
}
}
return checkedNodes;
}
Here is my load event handler, where I call my LoadConfig:
private void Form1_Load(object sender, EventArgs e)
{
Initializetreeview();
var cmdArgs = Environment.GetCommandLineArgs();
if (cmdArgs.Length == 1)
{
//MessageBox.Show("None file loaded as parameter");
}
if (cmdArgs.Length == 2)
{
//MessageBox.Show("JSON file is not loaded as parameter");
var dconfFilename = cmdArgs[1];
LoadConfig(dconfFilename);
}
}
Because LoadConfig method assume that TreeView control already has nodes with names, you need initialize TreeView before executing LoadConfig method
//Create method which initialize treeview control with your nodes
private void InitializeTreeView()
{
this.treeView1.Nodes.Add(new TreeNode("chapter1") { Tag = #"\include {chapter1}" });
this.treeView1.Nodes.Add(new TreeNode("chapter2") { Tag = #"\include {chapter2}" });
this.treeView1.Nodes.Add(new TreeNode("chapter3") { Tag = #"\include {chapter3}" });
this.treeView1.Nodes[0].Nodes.Add(new TreeNode("section1") { Tag = #"\input {sec1}" });
this.treeView1.Nodes[1].Nodes.Add(new TreeNode("section2") { Tag = #"\input {sec2}" });
this.treeView1.Nodes[2].Nodes.Add(new TreeNode("section3") { Tag = #"\input {sec3}" });
}
private void Form_Load(Object sender, EventArgs e)
{
this.InitializeTreeView();
//Now you can load your config
var cmdArgs = Environment.GetCommandLineArgs();
if (cmdArgs.Length == 1)
{
//MessageBox.Show("None file loaded as parameter");
}
if (cmdArgs.Length == 2)
{
//MessageBox.Show("JSON file is not loaded as parameter");
var dconfFilename = cmdArgs[1];
LoadConfig(dconfFilename);
}
}

How to find a specific word in WebBrowser control C#

I use this code to find CDE in the HTML. How can I find my request data in tag page with different ids, for example if page id is 1 my result is CDE and when page id is 2 my result is IJK, How can I set id-value in my search?
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = #"<html><head><title></title></head><body>"
+ "<page id=\"1\">"
+ #"ABCDEF</page>"
+ "<page id=\"2\">"
+ #"GHIJKLMN</page></body></html>";
webBrowser1.DocumentCompleted += HtmlEditorDocumentCompleted;
}
void HtmlEditorDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var document = (IHTMLDocument2)((WebBrowser)sender).Document.DomDocument;
if (document != null)
{
IHTMLBodyElement bodyElement = document.body as IHTMLBodyElement;
if (bodyElement != null)
{
IHTMLTxtRange trg = bodyElement.createTextRange();
if (trg != null)
{
trg.move("character", 2);
trg.moveEnd("character", 3);
trg.select();
trg.pasteHTML("<font color=#FF0000><strike>" + trg.text + "</strike></font>");
}
}
}
}
I have no idea, what do you need to do, you may have to rephrase the question...
But you might want to have a look at webBrowser1.Document.GetElementDyId() to get a specific element by "id"

Categories