I want to know if my gridView is empty-doesn't have any items in it.
I have tried to do the following :
public sealed partial class Profile : Page
{
Boolean isGridViewEmpty = true;
}
This is the function that shows the grid view, and I have tried to make it also determine whether or not the gridview is empty
//gets the animals of the specific chosen user's data tabe
public async void getAnimalsData(int ownerId)
{
int count = 0;
regitration.getAnimalsOfUserTableResponseGetAnimalsOfUserTableResult r = await cal.getAnimalsOfUserTableAsync(ownerId);
List<Animal> theAnimalList = new List<Animal>();
Animal a = null;
XmlReader xr = r.Any1.CreateReader();
XmlDocument document = new XmlDocument();
document.Load(xr);
XmlNodeList theXmlList = document.GetElementsByTagName("Table");
foreach (XmlElement item in theXmlList)
{
a = new Animal();
foreach (XmlNode node in item.ChildNodes)
{
switch (node.Name)
{
case "animalId": a.AnimalId = int.Parse(node.InnerText); count++; break;
case "ownerId": a.OwnerId = int.Parse(node.InnerText); count++; break;
case "animalName": a.Animalname = node.InnerText; count++; break;
case "fur": a.Fur = node.InnerText; count++; break;
case "level": a.Level = int.Parse(node.InnerText); count++; break;
case "money": a.Money = int.Parse(node.InnerText); count++; break;
}
}
theAnimalList.Add(a);
}
grid2.ItemsSource = theAnimalList;
if (count == 0)
{
isGridViewEmpty = true;
}
else
{
isGridViewEmpty = false;
}
}
Upon debugging, I could see that it doesn't really exit the function, although, it also doesn't display an error message. It just appears stuck after the last curly bracket.
I have no idea what I'm doing wrong, the count appears to work fine , upon debugging it also shows me that isGridViewEmpty is really set to true, but whenever I come to implement the function and I check if isGridViewEmptyis true, it doesn't work. Also, as I mentioned before, the debugger gets stuck in the function getAnimalsData
The function getAnimalsData was async. So it actually works, just because it happens in the background instead of the order I pressed it, so whenever I have conditional related functionality, it looks useless. So I made it a Task instead of void and put await before the function.
For more detail you could refer Asynchronous programming with async and await (C#).
Related
I asked this question yesterday.
Essentially, I'm trying to parse an XML from a URL but my code hangs forever if the connection is lost when attempting to read the XML.
I am still having the same problem, however I changed the code in a way I thought would prevent the program from freezing if the connection to the URL was interrupted. Could someone please explain why my solution didn't work and how I can fix it? Thanks!
Here are the two functions I am using. CanReach just checks the connection to make sure the URL is there, and GetTags gets all the parent tags of the XML file. I want it to break if the connection is interrupted. I tried to do this by loading the xml file instead of parsing it right from the URL and using try and catch to catch the error. xmlLocation is the URL.
public static bool CanReach(string xmlLocation)
{
WebRequest request = WebRequest.Create(xmlLocation);
request.Timeout = 1000;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Dispose();
request.Abort();
return true;
}
catch (System.Net.WebException)
{
request.Abort();
return false;
}
}
public static List<string> GetTopTags(string xmlLocation)
{
bool canBeReached = CanReach(xmlLocation);
if (canBeReached)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlLocation);
XmlReader reader = new XmlNodeReader(xmlDoc);
List<string> dataList = new List<string>();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
dataList.Add(reader.Name);
break;
}
}
reader.Dispose();
return topTags;
}
catch
{
return null;
}
}
else
{
return null;
}
}
We can start of another thread that is reading the XML file and the current method can continuously check whether connection is alive or not. If the we can not reach the URL anymore, we can cancel the operation and return null. If the read operation is finished, isFinished flag is set and we can return returnValue.
Try this:
public static List<string> GetTopTags(string xmlLocation)
{
bool canBeReached = CanReach(xmlLocation);
if (!canBeReached)
return null;
List<string> returnValue = null;
CancellationTokenSource cts = new CancellationTokenSource();
bool isFinished = false;
Task.Factory.StartNew(() =>
{
try
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(xmlLocation);
using var reader = new XmlNodeReader(xmlDoc);
List<string> dataList = new List<string>();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
dataList.Add(reader.Name);
break;
}
}
if (reader.ReadState == ReadState.Error)
returnValue = null;
else
returnValue = topTags;
}
catch
{
returnValue = null;
}
isFinished = true;
}, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
while (!isFinished)
if (!CanReach(xmlLocation))
cts.Cancel();
return returnValue;
}
I'm not wild about that XmlDocument.Load() and passing it a URL. You're handing over too much control and it's making it hard for you to debug. I would separate out the networking and the XML reading. With the networking separated out, you eliminate the need for your CanReach() function. Anything network related needs to be ran in a separate thread. Based on your source, something like the following is what I might start with.
public static async Task<List<string>> GetTopTags(string xmlLocation)
{
string xmlText = null;
try
{
// You are free to use WebRequest here, I've used WebClient for simplicity.
using (var webClient = new WebClient())
{
xmlText = await webClient.DownloadStringTaskAsync(xmlLocation);
}
}
catch (Exception)
{
// Handle network related issues.
}
if (string.IsNullOrWhiteSpace(xmlText))
{
// We weren't able to download the XML, or the downloaded XML is not valid,
// "CanReach()" is false.
return null;
}
// We downloaded the XML successfully if you get here, now just read it.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new StringReader(xmlText));
using (XmlReader reader = new XmlNodeReader(xmlDoc))
{
List<string> dataList = new List<string>();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
dataList.Add(reader.Name);
break;
}
}
return dataList;
}
}
Here is the code for my work.
public void InsertValue(WordprocessingDocument doc, string bookMark, string txt)
{
try
{
RemoveBookMarkContent(doc, bookMark);
var bmStart = FindBookMarkStart(doc, bookMark);
if (bmStart == null)
return;
var run = new Run();
run.Append(GetRunProperties());
run.Append(new Text(txt));
bmStart.Parent.InsertAfter(run, bmStart);
}
catch (Exception c)
{
//not Exception
}
}
private void RemoveBookMarkContent(WordprocessingDocument doc, string bmName)
{
BookmarkStart bmStart = FindBookMarkStart(doc, bmName);
if (bmStart == null)
return;
BookmarkEnd bmEnd = FindBookMarkEnd(doc, bmStart.Id);
while (true)
{
var run = bmStart.NextSibling();
if (run == null)
{
break;
}
if (run is BookmarkEnd && (BookmarkEnd)run == bmEnd)
{
break;
}
run.Remove();
}
}
There are still several auxiliary classes not written.Work process, first find the bookmark location, delete the content of the bookmark location, and then add it.I've also tried to add one Paragraph to the bookmark location.But that doesn't work.
Document to insert in bookmark eg:露点:U=0.15℃(k=2);相对湿度:U=1.0%RH(k=2).Both u and K must be italics.Any help will be appreciated.Thanks.
I tried a new component.[Spire.Office.][1]
At the beginning, I didn't think of a solution, but I used the global search and replacement to determine whether the search location has bookmarks, which perfectly solved the problem.
Here is the code for my work.
var selection = document.FindAllString("U", false, true);
foreach (var sec in selection)
{
var t = sec.GetAsOneRange();
if (sec.GetAsOneRange()?.Owner?.LastChild?.DocumentObjectType == DocumentObjectType.BookmarkEnd)
{
sec.GetAsOneRange().CharacterFormat.Italic = true;
}
}
I didn't try to do this with openxml, but I think the principle should be consistent.
[1]: https://www.e-iceblue.cn/Buy/Spire-PDF-NET.html
The program for ordering statements on the registry, I can not go to their pop-up window, selenium does not see that any new is being created.
Is it possible to do it through Xpath without using the transition to the Popup window, a browser function, or in another way in Selenium (Chrome)?
New window detection function:
public static string ClickAndSwitchWindow(IWebElement elementToBeClicked,
IWebDriver driver, int timer = 2000)
{
System.Collections.Generic.List<string> previousHandles = new
System.Collections.Generic.List<string>();
System.Collections.Generic.List<string> currentHandles = new
System.Collections.Generic.List<string>();
previousHandles.AddRange(driver.WindowHandles);
elementToBeClicked.Click();
Thread.Sleep(timer);
for (int i = 0; i < 20; i++)
{
currentHandles.Clear();
currentHandles.AddRange(driver.WindowHandles);
foreach (string s in previousHandles)
{
currentHandles.RemoveAll(p => p == s);
}
if (currentHandles.Count == 1)
{
driver.SwitchTo().Window(currentHandles[0]);
Thread.Sleep(100);
return currentHandles[0];
}
else
{
Thread.Sleep(500);
}
}
return null;
}
The piece of code itself:
//After this click of this element, a window opens:
//"Send request"
IWebElement PopWindowsstart = ww.Until(ExpectedConditions.ElementIsVisible(By.XPath("/html/body/div[1]/div[6]/div[4]/div/div/section/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div/div/div[1]/div/div/div/div[1]/div/div/div/div[4]/div/div/div/div[1]/div/div/div/div[1]/div/div/span/span")));
//Search for a new window
string newWin = ClickAndSwitchWindow(PopWindowsstart, Browser, 2500);
PopupWindowFinder finder = new PopupWindowFinder(Browser);
//Switch to a new window
Browser.SwitchTo().Window(newWin);
//Statement Number:
IWebElement NumExctract = ww.Until(ExpectedConditions.ElementIsVisible(By.XPath("div[class='v-label v-label-tipFont tipFont v-label-undef-w'] b")));
//Read check
MessageBox.Show(NumExctract.Text);
//"Continue work"
ww.Until(ExpectedConditions.ElementIsVisible(By.XPath("/html/body/div[7]/div/div/div/div[3]/div/div/div/div[1]/div/div/div/div[2]/div/div/div/div[1]/div/div/div/div[1]/div/div/span/span"))).Click();
//"Change"
ww.Until(ExpectedConditions.ElementIsVisible(By.XPath("/html/body/div[1]/div[6]/div[4]/div/div/section/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div/div/div[1]/div/div/div/div[2]/div/div/div/div[1]/div/div/div/div[2]/div/div/span/span"))).Click();
Thread.Sleep(300000);
Type window:
Let's make this a bit easier.
If you need to switch to a popup, try the below.
public static string SwitchToPopup()
{
var mainHandle = Driver.CurrentWindowHandle;
var handles = Driver.WindowHandles;
foreach (var handle in handles)
{
if (mainHandle == handle)
{
continue;
}
Driver.SwitchTo().Window(handle);
break;
}
var result = Url;
return result;
}
When you need to switch back, use:
public static void GoToMainHandle()
{
var handles = Driver.WindowHandles;
foreach (var handle in handles)
{
Driver.SwitchTo().Window(handle);
break;
}
}
That being said, your xpath is not something that should ever be used. Please look at https://www.w3schools.com/xml/xpath_intro.asp and rewrite it. When you use chrome to give you your xpath like:
ww.Until(ExpectedConditions.ElementIsVisible(By.XPath("/html/body/div[1]/div[6]/div[4]/div/div/section/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div/div/div[1]/div/div/div/div[2]/div/div/div/div[1]/div/div/div/div[2]/div/div/span/span"))).Click();
If your dev adds a div in here somewhere, all of your tests will now fail. If your devs are not providing unique identifiers, work with them to resolve that. You should have id's, class names etc.
Try:
public static void PopUp()
{
_webDriver.SwitchTo().Alert().Accept();
}
I would like to ask about shopify pagination version 2020-01
First request query:
URL: https://klevarange.myshopify.com/admin/api/2020-01/orders.json?fulfillment_status=unfulfilled&limit=250&financial_status=paid&created_at_min=2019-08-27T16:15:47-04:00
Return Header:
"<https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzIxNzM2NTIsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjA5OjUyIiwiZGlyZWN0aW9uIjoibmV4dCJ9>; rel=\"next\""
2nd Request Query:
"https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9>; rel=\"next\""
Result: Bad Request
What should I put in page_info? Do I need to include the rel=\"next\"" in the page_info?
Thank you.
Remove > from your page_info variable
var page_info = "eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9"
and Make your request URL like below.
https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info={page_info}
Digging Deeper
You need to iterate your while loop until there is no Link Parameter in the response header and this parameter is not a static value it is the address of last object you get and saying next will give you next 250 objects.
you need to update your pageInfo parameter in every request with newly generated next reference ( pageInfo )
When you do not get this parameter that means there is no next or previous page .
Have a look in this below code...( written in php )
How to create pagination in shopify rest api using php
You should use only this part: https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9 i.e. without rel="next"
In the 2nd and all next requests, you can only pass up to 3 query parameters:
page_info
limit
fields
So if you want to get results from the next page you need to extract page_info value from the first response headers.
The idea is that you can move only forward or backwards while requesting the results and you can get the link (page_info token) to the next (or previous) page only after retrieving the current page results.
Maybe in the last 2 years, Shopify has made some modifications to their API, then I use GetNextPageFilter method. This is my approach.
public async Task<IEnumerable<Product>> ProductsGetList(string shopUrl, string accessToken)
{
var products = new List<Product>();
var service = new ProductService(shopUrl, accessToken);
var filter = GetFilters(shopUrl);
var productList = await service.ListAsync(filter);
if (productList != null && productList.Items.Any())
{
products.AddRange(productList.Items);
bool hasMorePages = productList.HasNextPage;
if (hasMorePages)
{
do
{
var filterList = productList.GetNextPageFilter(filter.Limit, filter.Fields);
productList = await service.ListAsync(filterList);
if (productList != null && productList.Items.Any())
{
products.AddRange(productList.Items);
hasMorePages = productList.HasNextPage;
}
} while (hasMorePages);
}
}
return products;
}
private ProductListFilter GetFilters(string url)
{
ProductListFilter filters = new ProductListFilter();
string queryString = new System.Uri(url).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
foreach (var parameter in queryDictionary)
{
var key = (string)parameter;
var value = queryDictionary.Get(key);
switch (key)
{
case "published_status":
filters.PublishedStatus = value;
break;
case "published_at_max":
filters.PublishedAtMax = DateTimeOffset.Parse(value);
break;
case "published_at_min":
filters.PublishedAtMin = DateTimeOffset.Parse(value);
break;
case "updated_at_max":
filters.UpdatedAtMax = DateTimeOffset.Parse(value);
break;
case "updated_at_min":
filters.UpdatedAtMin = DateTimeOffset.Parse(value);
break;
case "created_at_max":
filters.CreatedAtMax = DateTimeOffset.Parse(value);
break;
case "presentment_currencies":
filters.PresentmentCurrencies = value.Split(',').AsEnumerable();
break;
case "created_at_min":
filters.CreatedAtMin = DateTimeOffset.Parse(value);
break;
case "status":
filters.Status = value;
break;
case "product_type":
filters.ProductType = value;
break;
case "handle":
filters.Handle = value;
break;
case "vendor":
filters.Vendor = value;
break;
case "title":
filters.Title = value;
break;
case "since_id":
filters.SinceId = long.Parse(value);
break;
case "collection_id":
filters.CollectionId = long.Parse(value);
break;
case "ids":
filters.Ids = value.Split(',').AsEnumerable().Cast<long>();
break;
case "limit":
filters.Limit = int.Parse(value);
break;
}
}
return filters;
}
Where shopUrl is the entire URL (https://{apiKey}:{password}#{hostname}/admin/api/{version}/{resource}.json) and accessToken is the URL {password} atribute
I'm not a developer so maybe the answer is out there for a different solution but I can't really translate it from python or something else.
I'm trying to use the AWS .NET SDK to find an instance and then get the instance's tags. I've gotten as far as being able to determine if an instance is up and running or not. I also see how I can create and delete tags (not in code example below). But I don't see an easy way to actually check if a tag exists and get the value of the tag if it does exist.
Sorry if I'm missing the obvious but this is all new to me. Here's an example of the code I'm using to check if an instance is running.
instanceID = "i-myInstanceID";
do {
var myrequest = new DescribeInstanceStatusRequest();
DescribeInstanceStatusResponse myresponse = ec2.DescribeInstanceStatus(myrequest);
int isCount = myresponse.DescribeInstanceStatusResult.InstanceStatuses.Count;
for (int isc=0; isc < isCount; isc++) {
InstanceStatus instanceStatus = myresponse.DescribeInstanceStatusResult.InstanceStatuses[isc];
if (instanceStatus.InstanceId.Contains(instanceID)) {
Console.WriteLine("It looks like instance "+instanceID+" is running.");
idIdx = isc;
foundID = true;
break;
}
}
if ((foundID==false) && (secondCounter==1)) {
Console.Write("Looking for instance "+instanceID);
} else {
Console.Write(".");
}
Thread.Sleep(1000);
secondCounter++;
if (secondCounter > 5) {
break;
}
} while (foundID == false) ;
First send a DescribeInstancesRequest to get the list of Instances:
public DescribeInstancesResult GetInstances(Ec2Key ec2Key)
{
_logger.Debug("GetInstances Start.");
AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);
var ec2Request = new DescribeInstancesRequest();
DescribeInstancesResponse describeInstancesResponse = ec2.DescribeInstances(ec2Request);
DescribeInstancesResult result = describeInstancesResponse.DescribeInstancesResult;
_logger.Debug("GetInstances End.");
return result;
}
Then loop through the instances until you find the one you want, and then use the Tag.GetTagValueByKey method:
// This just calls the above code
DescribeInstancesResult ec2Instances = _ec2ResourceAccess.GetInstances(ec2Key);
var returnInstances = new List<Ec2UtilityInstance>();
foreach (var reservation in ec2Instances.Reservation)
{
foreach (var runningInstance in reservation.RunningInstance)
{
var returnInstance = new Ec2UtilityInstance();
returnInstance.InstanceId = runningInstance.InstanceId;
returnInstance.InstanceName = runningInstance.Tag.GetTagValueByKey("Name");
returnInstance.Status = (Ec2UtilityInstanceStatus)Enum.Parse(typeof(Ec2UtilityInstanceStatus), runningInstance.InstanceState.Name, true);
returnInstance.DefaultIp = runningInstance.Tag.GetTagValueByKey("DefaultIp");
returnInstance.InstanceType = runningInstance.InstanceType;
returnInstance.ImageId = runningInstance.ImageId;
returnInstances.Add(returnInstance);
}
}
Here is the link for full source that this was taken from:
https://github.com/escherrer/EC2Utilities
Common\Manager
and
Common\ResourceAccess