I'm using Selenium Webdriver and am working with IE11. I'd like to access the window performance resources from an HTML page. From chrome I can do that easily with
IJavaScriptExecutor js = _webDriver as IJavaScriptExecutor;
ReadOnlyCollection<object> rList = ReadOnlyCollection<object>)js.ExecuteScript("return window.performance.getEntriesByType(\"resource\")");
and then a simple String object dictionary cast lets me get the details.
BUT the same code doesn't work for IE. There I am forced to cast the contents of what js is returning to a ReadOnlyCollection<IWebElement> - which is obviously not containing any of the info I want it to. Does anyone know what I ought to do to get the real info back?
Edit: I'm gonna leave my other answer because of how dumb I am.
Here's what I'm using now.
var resourceJson = ieDriver.ExecuteScript("var resourceTimings = window.performance.getEntriesByType(\"resource\");return JSON.stringify(resourceTimings)");
var resourceTimings = JsonConvert.DeserializeObject<System.Collections.ObjectModel.ReadOnlyCollection<object>>(resourceJson.ToString());
I'm stuck in the same boat, this is the best I could do:
var resNames = ieDriver.ExecuteScript("var keys = [];for(var key in window.performance.getEntriesByType(\"resource\")){keys.push(key);} return keys;");
Dictionary<string, Dictionary<string, object>> resTimings = new Dictionary<string, Dictionary<string, object>>();
foreach (string name in (System.Collections.ObjectModel.ReadOnlyCollection<object>)resNames)
{
var resource = new Dictionary<string, object>();
var resProperties = ieDriver.ExecuteScript(string.Format("var keys = [];for(var key in window.performance.getEntriesByType(\"resource\")[{0}]){{keys.push(key);}} return keys;", name));
foreach (string property in (System.Collections.ObjectModel.ReadOnlyCollection<object>)resProperties)
{
resource.Add(property, ieDriver.ExecuteScript(string.Format("return window.performance.getEntriesByType(\"resource\")[{0}].{1};", name, property)));
}
resTimings.Add(name, resource);
}
This works, but seems to take way too long. I'm sure there are a lot of optimizations to make. Don't know much js, but it seems it might go faster to offload the work there.
Well I found an answer of sorts
Basically I can query with strings like this to find the array description and access individual items.
"return window.performance.getEntriesByType(\"resource\").length"
"return window.performance.getEntriesByType(\"resource\")[0].name"
Not really the solution I expected, but it works
Related
In a program that I've been working on, there are three steps to get the data into a Dictionary that's been created:
execute the SQL command
pull those results into a DataTable, then
pull the DataTable into the Dictionary
Code:
var myDr = myLookup.ExecuteReader();
dt.Load(myDr);
customerLookup = dt.AsEnumerable()
.ToDictionary(key => key.Field<string>("code"),
value => value.Field<string>("customerText"));
My question is, is it possible to “cut out the middleman,” so to speak, and pull the data from the SqlDataReater directly into the Dictionaries? Or is it necessary to pull it into a DataTable first? If what I'm looking to do is possible, can someone please post code for me to try?
Thanks very much!
You can just loop through the rows returned by the reader:
var customerLookup = new Dictionary<string, string>();
using (var reader = myLookup.ExecuteReader())
{
while (reader.Read())
{
customerLookup[(string)reader["code"]] = (string)reader["customerText"];
}
}
You should be aware that if there are any duplicate codes, subsequent code values will overwrite previous ones in the dictionary. You can use customerLookup.Add() instead if you'd rather an exception be thrown in such a case.
Not only can you, but you definitely should. The code, as you show it, shows a complete lack of knowledge of how .NET works.
Some of the code I am suggesting may be considered "overkill" for the question at hand, but it does demonstrate some best practices.
Dictionary<string, string> customerLookup = new Dictionary<string, string>();
using (var reader = myLookup.ExecuteReader())
{
int ordinalCode = reader.GetOrdinal("code");
int ordinalCustomerText = reader.GetOrdinal("customerText");
while (reader.Read())
{
//this code assumes the values returned by the reader cannot be null
customerLookup.Add(reader.GetString(ordinalCode), reader.GetString(ordinalCustomerText))
}
}
Yes, it's possible. You should use SqlDataReader.Read method.
BACKGROUND TO THE PROBLEM
Say I had the following two lists (prioSums and contentVals) compiled from a SQL Server CE query like this:
var queryResults = db.Query(searchQueryString, searchTermsArray);
Dictionary<string, double> prioSums = new Dictionary<string, double>();
Dictionary<string, string> contentVals = new Dictionary<string, string>();
double prioTemp = 0.0;
foreach(var row in queryResults)
{
string location = row.location;
double priority = row.priority;
if (!prioSums.ContainsKey(location))
{
prioSums[location] = 0.0;
}
if (!contentVals.ContainsKey(location))
{
contentVals[location] = row.value;
prioTemp = priority;
}
if (prioTemp < priority)
{
contentVals[location] = row.value;
}
prioSums[location] += priority;
}
The query itself is pretty large, very dynamically compiled, and really beyond the scope of this question, so I'll just say that it returns rows that include a priority, text value, and location.
With the above code I am able to get one list (prioSums) which sums up all of the priorities for each location (not allowing repeats on the location [key] itself, even though repeats for the location are in the query results), and another list (contentVals) to hold the value of the location with the highest priority, once again, using the location as key.
All of this I have accomplished and it works very well. I can iterate over the two lists and display the information I want HOWEVER...
THE PROBLEM
...Now I need to reorder these lists together with the highest priority (or sums of priorities which are stored as the values in prioSums) first.
I have wracked my brain trying to think about using an instantiated class with three properties as given advice by others, but I can't seem to wrap my brain on how that would work, given my WebMatrix C#.net-webpages environment. I know how to call a class from a .cs file from the current .cshtml file, no problem, but I have never done this by instantiating a class to make it an object before (sorry, still new to some of the more complex C# logic/methodology).
Can anyone suggest how to accomplish this, or perhaps show an easier (at least easier to understand) way of doing this? In short all I really need is these two lists ordered together by the value in prioSums from highest to lowest.
NOTE
Please forgive me if I have not provided quite enough information. If more should be provided don't hesitate to ask.
Also, for more information or background on this problem, you can look at my previous question on this here: Is there any way to loop through my sql results and store certain name/value pairs elsewhere in C#?
I dont know if its the outcome you want but you can give it a try:
var result = from p in prioSums
orderby p.Value descending
select new { location = p.Key, priority = p.Value, value = contentVals[p.Key] };
just messing around, trying to expand my bag o' tricks: I was just experimenting and want to do something like a Dictionary object with another inner Dictionary as the outside Dictionary's .Value
var dictionary = new Dictionary<ObjectType, Dictionary<string, string>>();
ObjectType is an enum
so...what then...either you're not suppose to do this or I just don't know how 'cause I started running into a wall when I was trying to figure out how to populate and retrieve data from it.
Purpose might help: I'm being passed an ObjectGUID and need to flip through a bunch of database tables to determine which table the object exists in. The method I've already written just queries each table and returns count (here are a couple examples)
// Domain Check
sql = string.Format(#"select count(domainguid) from domains where domainguid = ?ObjectGUID");
count = (int)MySQLHelper.ExecuteScalar(ConnectionStrings.ConnectionStrings.V4DB_READ, sql, pObjectGUID).ToString().Parse<int>();
if (count > 0)
return ObjectType.Domain;
// Group Check
sql = string.Format(#"select count(domaingroupguid) from domaingroups where domaingroupguid = ?ObjectGUID");
count = (int)MySQLHelper.ExecuteScalar(ConnectionStrings.ConnectionStrings.V4DB_READ, sql, pObjectGUID).ToString().Parse<int>();
if (count > 0)
return ObjectType.Group;
So, that's all done and works fine...but because the fieldname and table name are the only things that change for each check I started thinking about where I could re-use the repetitive code, I created a dictionary and a foreach loop that flips through and changes the sql line (shown below)...but, as you can see below, I need that ObjectType as kind of the key for each table/fieldname pair so I can return it without any further calculations
Dictionary<string, string> objects = new Dictionary<string,string>();
objects.Add("domains", "domainguid");
objects.Add("domaingroups", "domaingroupguid");
objects.Add("users", "userguid");
objects.Add("channels", "channelguid");
objects.Add("categorylists", "categorylistguid");
objects.Add("inboundschemas", "inboundschemaguid");
objects.Add("catalogs", "catalogguid");
foreach (var item in objects)
{
sql = string.Format(#"select count({0}) from {1} where {0} = ?ObjectGUID", item.Value, item.Key);
count = (int)MySQLHelper.ExecuteScalar(ConnectionStrings.ConnectionStrings.V4DB_READ, sql, pObjectGUID).ToString().Parse<int>();
if (count > 0)
return ?????
}
This isn't all that important since my original method works just fine but I thought you StackOverflow geeks might turn me on to some new clever ideas to research...I'm guessing someone is going to smack me in the head and tell me to use arrays... :)
EDIT # Jon Skeet ------------------------------------------
Heh, sweet, think I might have come upon the right way to do it...haven't run it yet but here's an example I wrote for you
var objectTypes = new Dictionary<string, string>();
objectTypes.Add("domainguid", "domains");
var dictionary = new Dictionary<ObjectType, Dictionary<string, string>>();
dictionary.Add(ObjectType.Domain, objectTypes);
foreach(var objectType in dictionary)
{
foreach(var item in objectType.Value)
{
sql = string.Format(#"select count({0}) from {1} where {0} = ?ObjectGUID", item.Key, item.Value);
count = (int)MySQLHelper.ExecuteScalar(ConnectionStrings.ConnectionStrings.V4DB_READ, sql, pObjectGUID).ToString().Parse<int>();
if (count > 0)
return objectType.Key;
}
}
This chunk should hit the domains table looking for domainguid and if count > 0 return ObjectType.Domain...look right? Only problem is, while it might seem somewhat clever, it's like 2 dictionary objects, a couple strings, some nested loops, harder to read and debug than my first version, and about 10 more lines per check hehe...fun to experiment though and if this looks like to you then I guess it's one more thing I can add to my brain :)
also found this how to fetch data from nested Dictionary in c#
You can definitely do it, although you're currently missing a closing angle bracket and parentheses. It should be:
var dictionary = new Dictionary<ObjectType, Dictionary<string, string>>().
To add a given value you probably want something like:
private void AddEntry(ObjectType type, string key, string value)
{
Dictionary<string, string> tmp;
// Assume "dictionary" is the field
if (!dictionary.TryGetValue(type, out tmp))
{
tmp = new Dictionary<string, string>();
dictionary[type] = tmp;
}
tmp.Add(key, value);
}
If that doesn't help, please show the code that you've tried and failed with - the database code in your question isn't really relevant as far as I can tell, as it doesn't try to use a nested dictionary.
I am getting a datatable with customer data from a MySql databaes and a customer object from a web service.
I want to compare every value in the datatable with the values in the object and if there is one field that differs I want to perfrom some tasks.
I know I can get the values from the datatable with:
string mCompanyName = row["Company Name"].ToString();
string mCreatedDate = row["Created Date"].Tostring();
//etc..
Then I get the values from the web service
string wsCompanyName = customer.companyName;
string wsCreatedDate = customer.createdDate;
There are about 50 fields and doing
if( mCompanyName != wsCompanyName & mCreatedDate != wsCreatedDate and so on..) (or similar)
{
//Do something
}
seems to be a bit tedious and not very nice so how should I perform this? Is there a much better way to chuck it into a list and use some fancy LINQ?
Thanks in advance.
For cases like this I sometimes put them ("the objects") in something IEnumerable (make sure to "line them up") and use the SequenceEqual extension method. It performs standard Equals()'ity and is "cheap enough for my usage".
For instance:
var equal = (new object[] { row["A"], row["B"] })
.SequenceEqual(new object[] { x.A, x.B });
This requires LINQ, of course.
I'd put them in a Dictionary and search that way:
Dictionary<string, string> mData = new Dictionary<string, string>();
mData.Add("Company Name", row["Company Name"].ToString());
Dictionary<string, string> wsData = new Dictionary<string, string>();
wsData.Add("Company Name", customer.CompanyName);
Then loop through:
foreach (KeyValuePair<string, string> pair in mData)
{
if (wsData[pair.Key] == pair.Value)
{
// Do something
}
}
This way, for every entry in mData (the data from your database), it will look for an entry in wsData with the same name.
I wouldn't create individual variables for each piece of data. It would be difficult to maintain, and would not scale well (lots of copy and pastes).
I think this might help you, but it needs to modify this to use in your scenerio stackoverflow link
i have a namespace string like "Company.Product.Sub1.Sub2.IService".
The Sub1/Sub2 can differ in their count, but normally their is one part which matches to
a Dictionary with AssemblyFullname as key and path to it as value.
Now ive written this code
string fullName = interfaceCodeElement.FullName;
var fullNameParts = interfaceCodeElement.FullName.Split('.').Reverse();
KeyValuePair<string, string> type = new KeyValuePair<string,string>();
foreach (var item in fullNameParts)
{
var match = references.Where(x => x.Key.Contains(item)).ToList();
if (match.Count > 0)
{
type = match[0];
break;
}
}
Works but doesnt look nice in my opinion.
I tried it with linq but i dont know how ive to write it.
var matches = from reference in refs
where reference.Key.Contains(fullNameParts.Reverse().
Thanks for help.
To first put it into English, you're trying to go through the parts (backwards) of the Fullname in interfaceCodeElement and find the first that matches (as a substring, case-sensitive) any of the keys in references (which is a Dictionary<string, string> from fullname to path). Your result, type, is a KeyValuePair<string, string> although it's not clear if you actually need that (both the key and value) or just one or the other.
One, it seems a little odd to have a Dictionary in such a case, since you're not able to lookup as a key, but I guess it still works for the purpose :) Switching to something like List<Tuple<string, string>> or List<KeyValuePair<string, string>> might make sense, as the order of the pairs that comes from iteration over references will potentially affect which pair is selected into type.
In order to try to make it easier to understand, I'll add a let here:
var bestMatchPerPart = from part in fullNameParts
let firstMatchPair = references.FirstOrDefault(pair => pair.Key.Contains(part))
where firstMatchPair != null // ignore parts that have no match
// since we want the pair, not the part, select that
select firstMatchPair;
var type = bestMatchPerPart.FirstOrDefault()
// to match original behavior, empty pair in result instead of null if no match
?? new KeyValuePair<string, string>();
This should give you a list of the matches:
var listOfMatches = fullNameParts.Where(fp => references.Where(r => r.Key.Contains(fp))).ToList();
Edit: So based on your comments I think I kind of understand. Assuming you have some list of these fullNames somewhere:
// Making this up because I am nor sure what you have to start with
List<string> yourListOfAllYourFullNames = GetThisList();
var listOfMatches = yourListOfAllYourFullNames.Where(
fnl => fnl.Split('.').Reverse().Where(
fnp => references.Where(r => r.Key.Contains(fnp))).Count() > 0).ToList();