I'm getting an error within the kendo.all.min.js when I try and click on one of the nodes in a TreeView - anyone know if I have to further configure it to avoid this?
The error I'm getting is:
JavaScript runtime error: Unable to get property 'set' of undefined or null reference
and the rough area that is highlighted on error by VS is:
return arguments.length?(n=e(n,r).closest(q),r.find(".k-state-selected").each(function(){var e=i.dataItem(this);e.set("selected",!1),delete e.selected}),n.length&&i.dataItem(n).set("selected",!0)...
What i'm after is basically a list of files within a parent folder, and if the file is active and has child files, then I'd like it to give it a URL so they can open the link, but if not, I'd like nothing to happen, but I don't want to completely disable the node as I'd like the user to be able to expand it or shrink it if required.
Here is the code I'm using for the treeview in MVC:
#(Html.Kendo().TreeView()
.Name("treeview")
.Items(level1 =>
{
level1.Add().Text(rootFolderName)
.SpriteCssClasses("folder")
.Expanded(true)
.Items(level2 =>
{
int count = 0;
foreach (var node in list)
{
string title = node.Title;
string url = "";
if (node.HasChildren)
{
title = node.Title + "(" + node.ChildrenCount + ")";
url = "/Secure/Areas/Compliance.aspx?id=" + node.ItemId;
}
level2.Add().Text(title).Url(url)
.Expanded(true);
}
});
})
)
Anyone used these before and know what else I'm needing to do to achieve my aim?
Ok, learning more as I go. Ended up using an event like so:
#(Html.Kendo().TreeView()
.Name("treeview")
.Events(events => events
.Select("onSelect")
)
.Items(level1 =>
and then added a preventDefault if the url is empty
function onSelect(e) {
var dataItem = $('#treeview').data('kendoTreeView').dataItem(e.node);
if (dataItem.href == 'undefined')
e.preventDefault();
else
location.href = dataItem.href;
}
There is maybe a better way, but this seems to work so I'm happy for now.
Related
I am trying to search through a folder with Event Logs in them, eventpath has the path of the specific Event Log I want to access. I want to use a specified RecordID to find it's correlated FormatDescription and display it in a MessageBox. I want to be able to use the eventpath to access each Event Log since I am using 6 separate .evtx files and need to use this method on all of them.
I found this solution, but I get an error when I'm trying to Query. I've tried to find a fix, but it seems as if it's just not going to work for what I need. I commented where exactly it is occurring in the code.
This is the exception: System.Diagnostics.Eventing.Reader.EventLogException: The specified path is invalid.
I can't find a fix for this code, but if anyone knows a fix or another way to approach searching through Event Logs by RecordID and giving the corresponding FormatDescription, it would be greatly appreciated.
I am using C# in Windows Presentation Foundation.
public void getDesc(string recordid)
{
string eventpath = getEventPath();
//takes off the .evtx of the path
string result = eventpath.Substring(0, eventpath.Length - 5);
//result1 is going to be similar to this:
//C:\Users\MyName\AppData\Local\Temp\randomTempDirectory\additional_files\DiagnosticInfo\WindowsEventLogs\Application
string sQuery = "*[System/EventRecordID=" + recordid + "]";
var elQuery = new EventLogQuery(result, PathType.LogName, sQuery);
//this is where it errors out
//error: Specified Channel Path is invalid
using (var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery))
{
List<EventRecord> eventList = new List<EventRecord>();
EventRecord eventInstance = elReader.ReadEvent();
try
{
while ((eventInstance = elReader.ReadEvent()) != null)
{
//Access event properties here:
string formatDescription = eventInstance.FormatDescription();
MessageBox.Show(formatDescription);
}
}
finally
{
if (eventInstance != null)
eventInstance.Dispose();
}
}
}
I'm using Selenium for retrieve data from this site, and I encountered a little problem when I try to click an element within a foreach.
What I'm trying to do
I'm trying to get the table associated to a specific category of odds, in the link above we have different categories:
As you can see from the image, I clicked on Asian handicap -1.75 and the site has generated a table through javascript, so inside my code I'm trying to get that table finding the corresponding element and clicking it.
Code
Actually I have two methods, the first called GetAsianHandicap which iterate over all categories of odds:
public List<T> GetAsianHandicap(Uri fixtureLink)
{
//Contains all the categories displayed on the page
string[] categories = new string[] { "-1.75", "-1.5", "-1.25", "-1", "-0.75", "-0.5", "-0.25", "0", "+0.25", "+0.5", "+0.75", "+1", "+1.25", "+1.5", "+1.75" };
foreach(string cat in categories)
{
//Get the html of the table for the current category
string html = GetSelector("Asian handicap " + asian);
if(html == string.Empty)
continue;
//other code
}
}
and then the method GetSelector which click on the searched element, this is the design:
public string GetSelector(string selector)
{
//Get the available table container (the category).
var containers = driver.FindElements(By.XPath("//div[#class='table-container']"));
//Store the html to return.
string html = string.Empty;
foreach (IWebElement container in containers)
{
//Container not available for click.
if (container.GetAttribute("style") == "display: none;")
continue;
//Get container header (contains the description).
IWebElement header = container.FindElement(By.XPath(".//div[starts-with(#class, 'table-header')]"));
//Store the table description.
string description = header.FindElement(By.TagName("a")).Text;
//The container contains the searched category
if (description.Trim() == selector)
{
//Get the available links.
var listItems = driver.FindElement(By.Id("odds-data-table")).FindElements(By.TagName("a"));
//Get the element to click.
IWebElement element = listItems.Where(li => li.Text == selector).FirstOrDefault();
//The element exist
if (element != null)
{
//Click on the container for load the table.
element.Click();
//Wait few seconds on ChromeDriver for table loading.
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
//Get the new html of the page
html = driver.PageSource;
}
return html;
}
return string.Empty;
}
Problem and exception details
When the foreach reach this line:
var listItems = driver.FindElement(By.Id("odds-data-table")).FindElements(By.TagName("a"));
I get this exception:
'OpenQA.Selenium.StaleElementReferenceException' in WebDriver.dll
stale element reference: element is not attached to the page document
Searching for the error means that the html page source was changed, but in this case I store the element to click in a variable and the html itself in another variable, so I can't get rid to patch this issue.
Someone could help me?
Thanks in advance.
I looked at your code and I think you're making it more complicated than it needs to be. I'm assuming you want to scrape the table that is exposed when you click one of the handicap links. Here's some simple code to do this. It dumps the text of the elements which ends up unformatted but you can use this as a starting point and add functionality if you want. I didn't run into any StaleElementExceptions when running this code and I never saw the page refresh so I'm not sure what other people were seeing.
string url = "http://www.oddsportal.com/soccer/europe/champions-league/paok-spartak-moscow-pIXFEt8o/#ah;2";
driver.Url = url;
// get all the (visible) handicap links and click them to open the page and display the table with odds
IReadOnlyCollection<IWebElement> links = driver.FindElements(By.XPath("//a[contains(.,'Asian handicap')]")).Where(e => e.Displayed).ToList();
foreach (var link in links)
{
link.Click();
}
// print all the odds tables
foreach (var item in driver.FindElements(By.XPath("//div[#class='table-container']")))
{
Console.WriteLine(item.Text);
Console.WriteLine("====================================");
}
I would suggest that you spend some more time learning locators. Locators are very powerful and can save you having to stack nested loops looking for one thing... and then children of that thing... and then children of that thing... and so on. The right locator can find all that in one scrape of the page which saves a lot of code and time.
As you mentioned in related Post, this issue is because site executes an auto refresh.
Solution 1:
I would suggest if there is an explicit way to do refresh, perform that refresh on a periodic basis, or (if you are sure, when you need to do refresh).
Solution 2:
Create a Extension method for FindElement and FindElements, so that it try to get element for a given timeout.
public static void FindElement(this IWebDriver driver, By by, int timeout)
{
if(timeout >0)
{
return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(ExpectedConditions.ElementToBeClickable(by));
}
return driver.FindElement(by);
}
public static IReadOnlyCollection<IWebElement> FindElements(this IWebDriver driver, By by, int timeout)
{
if(timeout >0)
{
return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(by));
}
return driver.FindElements(by);
}
so your code will use these like this:
var listItems = driver.FindElement(By.Id("odds-data-table"), 30).FindElements(By.TagName("a"),30);
Solution 3:
Handle StaleElementException using an Extension Method:
public static void FindElement(this IWebDriver driver, By by, int maxAttempt)
{
for(int attempt =0; attempt <maxAttempt; attempt++)
{
try
{
driver.FindElement(by);
break;
}
catch(StaleElementException)
{
}
}
}
public static IReadOnlyCollection<IWebElement> FindElements(this IWebDriver driver, By by, int maxAttempt)
{
for(int attempt =0; attempt <maxAttempt; attempt++)
{
try
{
driver.FindElements(by);
break;
}
catch(StaleElementException)
{
}
}
}
Your code will use these like this:
var listItems = driver.FindElement(By.Id("odds-data-table"), 2).FindElements(By.TagName("a"),2);
Use this:
string description = header.FindElement(By.XPath("strong/a")).Text;
instead of your:
string description = header.FindElement(By.TagName("a")).Text;
I am working with mvc in framework-4.5. In all other fields validation is working properly, but i am finding it difficult for selectize dropdownlist. Validation is working properly in simple dropdownlist also.
I tried to show message using field-validation-error and input-validation-error but not getting any success. Here are some changes i made in jquery.validate.unobtrusive.js.
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error-+-").appendTo(container);
}
else {
error.hide();
}
//For Validation Toggel Start
debugger;
if ($(inputElement).parent().hasClass("selectize-input")) {
$(inputElement).parent().parent().parent().addClass("md-input-danger");
var container = error.data("unobtrusiveContainer");
container.removeClass("field-validation-valid").addClass("field-validation-error");
}
}
I did lots of research for this but i didn't get any proper solution.
please help me to solve this issue.
Thanks
add below JQuery code in document ready to validate your selectize dropdown
$.validator.setDefaults({
ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input'
});
I am using the GeckoFX 22 c# web browser control but cannot manage to access tags within an iframe. When I check the gecko innerhtml it seems that although the iframe tag shows in the html, the contents of it do not.
This is the code I used to get the inner html of the browser control which just shows the iframe tag as empty (when it should have another doc inside of it):
GeckoHtmlElement element = null;
var geckoDomElement = webBrowser.Document.DocumentElement;
if (geckoDomElement is GeckoHtmlElement)
{
element = (GeckoHtmlElement)geckoDomElement;
var innerHtml = element.InnerHtml;
}
Previously I used code similar to the code below to access individual elements which works fine:
GeckoDocument checkDoc = (GeckoDocument)webBrowser.Window.Document;
var x = (checkDoc.GetElementsByTagName("a").Where(b => b.Id == "ipt-form-format-aside").First());
I am able to get individual elements and change their values/trigger events etc without problems with the main html document but anything in an iframe is impossible to get the elements of. I think perhaps the Iframe has not been loaded yet or something like that. Is there a way to force the control to wait for the I frame to load before attempting to access its elements?
string content = null;
var iframe = webBrowser.Document.GetElementsByTagName("iframe").FirstOrDefault() as Gecko.DOM.GeckoIFrameElement;
if(iframe != null)
{
var html = iframe.ContentDocument.DocumentElement as GeckoHtmlElement;
if (html != null)
content = html.OuterHtml;
}
I'm just posting this for anyone else that might get this problem
foreach (GeckoIFrameElement _E in geckoWebBrowser1.Document.GetElementsByTagName("iframe"))
{
if (_E.GetAttribute("class") == "testClass")
{
var innerHTML = _E.ContentDocument;
foreach (GeckoHtmlElement _A in innerHTML.GetElementsByTagName("input"))
{
_A.SetAttribute("value", "Test");
}
}
}
I got a similar problem so i did this
checkDoc.Window.Frames(1)
instead of
checkDoc.GetElementsByTagName("iframe")
value within the parenthesis (i.e. 1 here) depends of your index
Here's the deal. Have a functioning web app using ASP.NET WebForms with a C# backend. The thing works fine, but I'm always looking to improve, as a beginner at this stuff. Right now, to deal with a user's search coming back with no results, I utilize the following, and was wondering if there was any cleaner way to do it, for future reference:
DataClass data = new DataClass();
var searchresults = data.GetData(searchBox.Text);
int datanumber = searchresults.Count();
if (datanumber == 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "javascript:alert('There were no records found to match your search');", true);
}
else
{
DropDownList1.Visible = true;
DropDownList1.Items.Clear();
DropDownList1.DataSource = searchresults;
DropDownList1.DataBind();
}
I agree with the not using popups, so you could always do something as simple as having a Label object on your page:
<asp:Label runat="server" id="lblResultMsg" ForeColor="Red" Visible="False" />
And then set the text dynamically (or add it as a property to the code) and set the label to be visible on postback if no results are found:
if (datanumber == 0)
{
lblResultMsg.Text = "There were no records found to match your search.";
lblResultMsg.Visible = true;
}
else
{
lblResultMsg.Text = "";
lblResultMsg.Visible = false;
// do your data binding
}
But there are quite a vast number of ways you could achieve something like this. Regarding your question about using the .Count from the Enumerable collection - there's nothing stopping you doing this as it's perfectly valid. The question is which method do you find more readable?
if you include the jquery ui dialog (http://jqueryui.com/demos/dialog/), you can simply call this to create a nice dialog box:
$('<div>message</div>').dialog({autoOpen:true,title:'Error'});
Personally I prefer to create a helper function for inserting the relevant javascript into the page, and only pass parameters to the function so that I don't need to worry about the messy details every time.
Something like :
public static void GrowlMessage(System.Web.UI.Control pageControl, string header = "", string message = "", bool sticky = false, string position = "top-right", string theme = "", bool closer = true, int life = 8)
{
string _js = "$.jGrowl('" + HttpContext.Current.Server.HtmlEncode(message) + "', { header:'" + header + "', sticky:" + sticky.ToString().ToLower() + ", position: '" + position + "', theme: '" + theme + "', closer: " + closer.ToString().ToLower() + ", life:" + life * 1000 + "});";
ScriptManager.RegisterStartupScript(pageControl, pageControl.GetType(),"Growl",_js, true);
}
The sample I have used also requires jQuery and the jGrowl library available here. And IMHO the messages are pretty. They are unobtrusive, the user does not need to click a button to make them go away, and they fade away after your specified amount of time.
But I agree with Mike, that if you don't have any records, you should just use the built in properties of a GridView (EmptyDataRowStyle and EmptyDataRowText) to display a 'no data matching your query' style message. Assuming that you're using a GridView at all, that is..
When it comes to user feedback, Impromptu is my friend. There is a nice ASP.NET implementation of Impromptu on Aaron Goldenthal's website: http://www.aarongoldenthal.com/post/2009/11/11/Using-jQuery-Impromptu-With-ASPNET.aspx
If you have decided to alert user via alert then please go ahead with light box effect..
http://www.designyourway.net/blog/resources/30-efficient-jquery-lightbox-plugins/
if you are still would like to go ahead with traditional alert then obviously its easy for you to fire it up on page load rather than attaching script to it..
')" ....>
Because if you require any change then you just need to alter the javascript alone and you dont need to build project again to test it...
Hope its useful for you..
Note: I'm using my own DLLs to render content so above coding may requires alteration because i did forget traditional asp codings.. :)