C# Foreach goes too quickly for the webbrowser control - c#

I am coding in C# using WindowsForms.
I am trying to iterate through a list of ID's that changes the url of a webbrowser control.
ClientID is an List<int> ClientID = new List<int>();
And filled with around 10-15 different numbers.
The foreach goes too quickly for the webbrowser control, and because of that the ErrorDiv is always null. The site isn't able to load, thus I am not able to check for the div with the specified class. If this class does exist, the foreach has to contiue with the next Client.
foreach (int Client in ClientID)
{
if(webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
webBrowser1.Navigate(URLconsult + "/" + Client);
}
var ErrorDiv = webBrowser1.Document
.GetElementsByTagName("div")
.Cast<HtmlElement>()
.FirstOrDefault(m => m.GetAttribute("className") == "incompleteConsultNotification");
Console.WriteLine(webBrowser1.Document.GetElementsByTagName("div").Cast<HtmlElement>().FirstOrDefault(m => m.GetAttribute("className") == "incompleteConsultNotification"));
//if (ErrorDiv == null)
//{
// Console.WriteLine("Normal");
//}
//else
//{
// Error.Add(Client);
// continue;
//}
}
The HTML div I try to target:
<div class="incompleteConsultNotification">
This form is incomplete. Please add the following:
<ul>
<li> option 1</li>
<li> option 2</li>
</ul>
</div>

Related

In ASP.net, what kind of IF statement could I use to hide a div if the image inside it matches the current page URL?

This is within Sitefinity if that matters, and I am really new at ASP.NET and C#.
I have an image-based navigation element at the bottom of a page that links to different articles using the same template. There are 5 articles, and I would like the link to the active page/article to be hidden so there is a grid of 4 image links.
Here's a screenshot:
https://i.imgur.com/PG2Sfpo.png
Here is the code behind it:
#{
string navTitle = string.Empty;
string url = string.Empty;
if (Model.CurrentSiteMapNode != null && Model.CurrentSiteMapNode.ParentNode != null)
{
if (Model.CurrentSiteMapNode.Title == "Home")
{
navTitle = Model.CurrentSiteMapNode.ParentNode.Title;
}
else
{
navTitle = Model.CurrentSiteMapNode.Title;
}
url = Model.CurrentSiteMapNode.ParentNode.Url;
}
}
<div class="foundation-stories-container">
#foreach (var node in Model.Nodes)
{
#RenderRootLevelNode(node);
}
</div>
#*Here is specified the rendering for the root level*#
#helper RenderRootLevelNode(NodeViewModel node)
{
string[] thisPage = (node.Url).Split('/');
string thisImage = thisPage[4] + ".jpg";
<a href="#node.Url" target="#node.LinkTarget">
<div class="foundation-story-block">
<div class="hovereffect">
<img src="[OUR WEBSITE URL]/stories/#thisImage" class="img-fluid">
<div class="overlay">
<h2>#node.Title</h2>
</div>
</div>
</div>
</a>
}
So we're already getting the page URL and image file name
string[] thisPage = (node.Url).Split('/');
string thisImage = thisPage[4] + ".jpg";
Is this as easy as doing the following?
if (thisImage = thisPage)
{
foundation-story-block.AddClassToHtmlControl("hide")
}
Seems easy enough, but I don't know where to start.
I'm better at Javascript, so I do have a JS solution in place for this already, but I'd really like to find a cleaner way to do it.
<script type="text/javascript">
$(document).ready(function() {
var active = window.location.pathname.split("/").pop()
var name = active;
name = name.replace(/-/g, ' ');
jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
return function( elem ) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >=
0;
};
});
$("h2:Contains('" + name + "')").closest(".foundation-story-block").addClass("hide");
});
</script>
This exists on the main template page.
Gets the last part of the URL
Sets that as a variable called "name"
Changes the dash to a space if there is one (most of the pages are associated with names so it's like /first-last)
Then it goes and looks at the which is where the title of the page lives, and if it equals the "name" variable, the ".hide" class is added to the block.
Thanks for any help anyone can provide.
You could bind a click event to your elements with the foundation-story-block class. The reason I use .on instead of .click is because when using UpdatePanels the click event won't fire after an UpdatePanel has it's update event triggered - you might encounter a similar problem with your dynamic binding so I used .on to avoid this.
$(".foundation-story-block").on("click", function() {
// Remove the "hide" class from any elements that have it applied
$.each($(".foundation-story-block.hide"), function(index, value) {
// Remove the class using the "this" context from the anonymous function
$(this).removeClass("hide");
});
// Add the "hide" class to the element that was clicked
$(this).addClass("hide");
});
I haven't run this though an IDE so it might not be 100% correct but it will put you on the correct path.
It is possible, yes. Here is how:
...
#{
var hiddenClass = thisImage == thisPage ? "hide" : string.Empty;
}
<div class="foundation-story-block #hiddenClass">
<div class="hovereffect">
<img src="[OUR WEBSITE URL]/stories/#thisImage" class="img-fluid">
<div class="overlay">
<h2>#node.Title</h2>
</div>
</div>
</div>

Get element by class name via browser C#

I have:
<h2 class="entry-title" itemprop="headline">
<a href="http://www.printesaurbana.ro/2015/10/idei-despre-un-start-bun-in-blogging.html" Idei despre un start bun în blogging </a>
</h2>
I want get href using class name, I try:
if (webBrowser1.Document != null)
{
var links = webBrowser1.Document.GetElementsByTagName("a");
foreach (HtmlElement link in links)
{
if (link.GetAttribute("class") == "entry-title")
{
MessageBox.Show("Here");
}
}
}
But didn't work. How solve this?
You should use link.GetAtribute("className"). Besides, it is the h2 tag in your html document that has the entry-title class. Corrected code:
if (webBrowser1.Document != null)
{
var links = webBrowser1.Document.GetElementsByTagName("h2");
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className") == "entry-title")
{
MessageBox.Show("Here");
}
}
}

Error "Object reference not set to an instance of an object"

This code can work with one of the web, but with some sites it back error messages like this, I do not know how to edit (Error in stars)
var document = webBrowser1.Document;
var documentAsIHtmlDocument3 = (mshtml.IHTMLDocument3)document.DomDocument;
var htmlString = documentAsIHtmlDocument3.documentElement.innerHTML;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlString);
// Sử dụng node để lấy tin
HtmlNodeCollection texts = doc.DocumentNode.SelectNodes("//div[#id='footer']/p");
string kq = "";
// cho vòng lặp để lấy kết quả
foreach (var item in texts)
{
kq += item.InnerText + Environment.NewLine;
}
richTextBox1.Text = kq;
HTML code:
<div id="divTop" >
<div id="text-conent" style="width: 500px; float: right;"></div>
<div id="grid" style="margin-removed 505px; height: 700px;"></div>
</div>
It seems that on the pages where this is successful there exists a div with the id of footer
But on other pages where this fails no such div exists.
So it seems like your logic may need to change to make the search expression that doc.DocumentNode.SelectNodes more forgiving.
Alternatively create a few more search strings that would work if your original fails:
if(texts == null){
texts = doc.DocumentNode.SelectNodes("some other search string");
}
etc.

Updating ContentBlock pulled from pageManager.LoadControl(). Sitefinity 5

Asked this on the forums as well, but no luck as of yet. What I need to do is set the HTML content of each content block on a given page. It seems that I can set the html value okay, but saving it does not update the actual page.
I'm wondering if it's because there needs to be some sort of save call on the control. There doesn't seem to be any methods available for such an action.
foreach (var c in duplicated.Page.Controls)
{
// go through the properties, se the ID to grab the right text
foreach (var p in c.Properties)
{
if (p.Name == "ID")
{
var content = pageContent.Where(content_pair => content_pair.Key == p.Value).SingleOrDefault();
var control = pageManager.LoadControl(c);
if (control is ContentBlock)
{
var contentBlock = pageManager.LoadControl(c) as ContentBlock;
contentBlock.Html = content.Value;
}
}
}
}
pageManager.SaveChanges(); */
WorkflowManager.MessageWorkflow(duplicated.Id, typeof(PageNode), null, "Publish", false, bag);
The following code may help you achieve what you need.
It will first get the page by its title (I am looking for a page by the title "duplicated" as it's implied by your code).
It generates a new draft of the current page, then go over its controls.
Controls which are detected as content blocks are then iterated in a foreach loop.
As written in the comment inside the foreach loop, you may detect controls by their explicit ID (by the property named "ID") or by their related shared content block (by the property named "SharedContentID") or any other condition (or ignore this condition altogether, which would result in updating all the controls n the page.
Once we have a control to update at hand, you can set its new value depending on the localization settings of your project.
After that the draft is saved and published and optionally a new version is created for it.
PageManager pageManager = PageManager.GetManager();
VersionManager vmanager = VersionManager.GetManager();
PageNode duplicated = pageManager.GetPageNodes().FirstOrDefault(p => p.Title == "duplicate");
if (duplicated != null)
{
var draft = pageManager.EditPage(duplicated.Page.Id, true);
string contentBlockTypeName = typeof(ContentBlock).FullName;
PageDraftControl[] contentBlocks = draft.Controls.Where(contentBlock => contentBlock.ObjectType == contentBlockTypeName).ToArray();
foreach (PageDraftControl contentBlock in contentBlocks)
{
Guid contentBlockId = contentBlock.Id;
//User "SharedContentID" if you are looking up controls which are linked to a shared content block of a specific ID.
//If you you are trying to locate a specific control by its own ID, use the explicit "ID" property instead of "SharedCotentID"
if (contentBlock.Properties.Where(prop => prop.Name == "SharedContentID" && prop.Value.ToString() == contentItemIdstr).FirstOrDefault() != null)
{
ControlProperty htmlProperty = contentBlock.Properties.Where(prop => prop.Control.Id == contentBlockId && prop.Name == "Html").FirstOrDefault();
if (htmlProperty != null)
{
if (AppSettings.CurrentSettings.Multilingual)
{
htmlProperty.GetString("MultilingualValue").SetString(CultureInfo.CurrentUICulture, "New Value");
}
else
{
htmlProperty.Value = "New Value";
}
}
}
}
draft = pageManager.SavePageDraft(draft);
draft.ParentPage.LockedBy = Guid.Empty;
pageManager.PublishPageDraft(draft);
pageManager.DeletePageTempDrafts(draft.ParentPage);
//Use the 2 next lines to create a new version of your page, if you wish.
//Otherwise the content will be updated on the current page version.
vmanager.CreateVersion(draft, draft.ParentPage.Id, true);
vmanager.SaveChanges();
pageManager.SaveChanges();
}
I hope this code helps.
Alon.

How to create menu bar in ASP.NET

I have to create a menu bar for my web application. I don't know how to create it. I came across few sites and downloaded some sample code. I have created a master page for this and pasted the code below for creating the menu which I have used.
[MethodImpl(MethodImplOptions.Synchronized)]
public override SiteMapNode BuildSiteMap()
{
// Return immediately if this method has been called before
if (_root != null)
return _root;
// Create a dictionary for temporary node storage and lookup
Dictionary<int, SiteMapNode> nodes = new Dictionary<int, SiteMapNode> (16);
// Query the database for site map nodes
using (SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["SQLConnectionString"]))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT ID, Title, Description, Url, Roles, Parent FROM ven_sitemap ORDER BY ID", connection);
SqlDataReader reader = command.ExecuteReader ();
int id = reader.GetOrdinal("ID");
int url = reader.GetOrdinal ("Url");
int title = reader.GetOrdinal ("Title");
int desc = reader.GetOrdinal("Description");
int roles = reader.GetOrdinal ("Roles");
int parent = reader.GetOrdinal("Parent");
while (reader.Read())
{
// Create the root SiteMapNode
// Build a tree of SiteMapNodes underneath the root node
//while (reader.Read())
//{
if (reader["parent"].ToString() == "0")
{
_root = new SiteMapNode(this, reader.GetInt32(id).ToString(), reader.IsDBNull(url) ? null : reader.GetString(url),
reader.GetString(title), reader.IsDBNull(desc) ? null : reader.GetString(desc));
if (!reader.IsDBNull(roles))
{
string rolenames = reader.GetString(roles).Trim();
if (!String.IsNullOrEmpty(rolenames))
{
string[] rolelist = rolenames.Split(new char[] { ',', ';' }, 512);
_root.Roles = rolelist;
}
}
// Add "*" to the roles list if no roles are specified
if (_root.Roles == null)
_root.Roles = new string[] { "*" };
// Record the root node in the dictionary
if (nodes.ContainsKey(reader.GetInt32(id)))
throw new ConfigurationErrorsException(_errmsg2); // ConfigurationException pre-Beta 2
nodes.Add(reader.GetInt32(id), _root);
// Add the node to the site map
AddNode(_root, null);
}
else
{
SiteMapNode node = new SiteMapNode(this, reader.GetInt32(id).ToString(), reader.IsDBNull(url) ? null : reader.GetString(url),
reader.GetString(title), reader.IsDBNull(desc) ? null : reader.GetString(desc));
if (!reader.IsDBNull(roles))
{
string rolenames = reader.GetString(roles).Trim();
if (!String.IsNullOrEmpty(rolenames))
{
string[] rolelist = rolenames.Split(new char[] { ',', ';' }, 512);
node.Roles = rolelist;
}
}
// If the node lacks roles information, "inherit" that
// information from its parent
SiteMapNode parentnode = nodes[reader.GetInt32(parent)];
if (node.Roles == null)
node.Roles = parentnode.Roles;
// Record the node in the dictionary
if (nodes.ContainsKey(reader.GetInt32(id)))
throw new ConfigurationErrorsException(_errmsg2);
nodes.Add(reader.GetInt32(id), node);
// Add the node to the site map
AddNode(node, parentnode);
}
//}
}
}
// Return the root SiteMapNode
return _root;
}
protected override SiteMapNode GetRootNodeCore ()
{
BuildSiteMap ();
return _root;
}
My table :
ID Title Description Url Roles Parent
1 HOME NULL ~/Reports/Production_data_report.aspx 2 0
2 Machinename NULL ~/Reports/machine_name.aspx 3 1
3 Business Quote NULL ~/Reports/business_quote.aspx 2 1
6 Machine Counter NULL ~/Reports/machine_counter.aspx 1 0
7 Data Query NULL ~/Reports/data_query_page.aspx 2 6
8 Production Report NULL ~/Reports/yoneda_report.aspx 2 6
Output from the code:
Machine counter
Data query
Production Report
But I need to have output like this,
Home Machine counter
machinename Data query
businessquote Production Report
Where home and machine counter are root nodes. When I execute the above code my first root node is replaced by the second one.
Please help me solve this issue.
Unless you specifically need to extract the site structure from a database, I would suggest using ASP.NET Site Maps with a Web.sitemap file and then connecting it with an ASP.NET Menu Control. Your question is a little unclear so apologies if this is not what you are after.
i have used css and html to meet my requirement.. i have removed all my server side coding..
coding :
<ul id="topnav" style="left: 24px; width: 95%; position: absolute; top: 86px">
<li class ="admin" style="background-color:#FF9900; left: 0px; top: 0px;">
<h4>
ADMIN
</h4>
<div class="sub">
<ul>
<li><h2>ADD MACHINE</h2></li>
<li><h2>ADD JOB</h2></li>
</ul>
</div>
</li>
<li class ="report" style="background-color:#ff9933; left: 154px; top: 0px;">
<h4 style="background-color: #ff9933">
REPORT
</h4>
<div class="sub">
<ul>
<li style ="color:Red;"><h2>MACHINE REPORT</h2></li>
<li style="visibility:hidden;">PRODUCTION REPORT</li>
</ul>
<ul>
<li style ="color:Red;"><h2>TIME SHEET</h2></li>
<li >ASSEMBLY</li>
<li>MAINTENANCE</li>
<li>CNC</li>
<li>DESIGN</li>
</ul>
<ul>
<li style ="color:Red;"><h2>MACHINE COUNTER</h2></li>
<li>MACHINE COUNTER</li>
</ul>
</div>
</li>
<li class ="business" style="left: -100px; top: 0px; height: 38px; background-color: #ff9933" >
<h4>
BUSINESS
</h4>
<div class="sub">
<ul>
<li><h2>BUSINESS QOUTE</h2></li>
<li><h2>BUSINESS AWARD </h2></li>
</ul>
</div>
<!--
<li>
Store Locator
</li>

Categories