Identifying Facebook Status Update using C# Selenium - c#

I have made an automated test to login to Facebook and make a status update.
I am however stuck with two problems:
The entire status text doesn't get typed with sendkeys() function.
Identifying the appearance of the status right after it appears in the home feed
Here is the code sample I used:
IWebElement query5 = driver.FindElement(By.Id("u_0_1d"));//this is to find the status field
query5.Click();
WebDriverWait wait5 = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
query5.SendKeys("Status Update made by test automation using Selenium");
WebDriverWait wait6 = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IWebElement query6 = driver.FindElement(By.CssSelector("div.clearfix button.selected"));
query6.Click();
/*I tried to check whether or not the status appears in the homefeed by executing the following code, but it doesn't work. */
IWebElement query7 = driver.FindElement(By.CssSelector("div.fcg a.nazarah div.userContent"));
/*i used my partial href text of my profile url which has a term nazarah*/
Problem 1: only the following sub text is typed in the status box:
"date made by test automation using Selenium"
Problem 2: usually when you post a status, it appears just below the status update field. How can I identify and confirm it using selenium c#?

Looks like some elements’ html ids you rely on is pointing on wrong elements or not persistent.
Facebook dynamically generates Html Ids for some elements, so it would be much better to identify web-elements with different attributes.
I’ve posted long source code below, and here are some highlights:
Problem 1:
txtMessage.SendKeys("Hello! This is an update\n");
txtMessage.SendKeys("From automated script " + messageGuid);
You can use a character \n inside string to put a new line.
Problem 2:
You can count the number of current user posts and wait until it is increased.
while (currentMessagesCount <= previousMessagesCount)
{
userMessagesList = driver.FindElementsByCssSelector(PostLocators.userPostsList_CssSelector);
currentMessagesCount = userMessagesList.Count();
System.Threading.Thread.Sleep(100);
}
Also, I would like to recommend a tool which aims to debug locators for Selenium Webdriver – SWD Page Recorder; here is a short overview.
Full Source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace ConsoleApplication4
{
class Program
{
//Locators: Generated with SWD Page Recorder; Template=[CSharp] Locator constants in the static class
public static class LoginLocators
{
public const string txtEmail_XPath = #"id(""email"")";
public const string txtPassword_XPath = #"id(""pass"")";
public const string btnLogin_XPath = #"id(""loginbutton"")";
}
public static class PostLocators
{
public const string txtWhatsOnYourMind_XPath = #"//textarea[contains(#title,""What's on your mind?"")]";
public const string btnPost_XPath = #"//button[contains(text(), 'Post')]";
public const string userPostsList_CssSelector = #"div.userContentWrapper";
}
// ====
#region Login and Password
static string userLogin = "googleplus#gmail.com";
static string userPassword = "pAAASSSSWWWrd";
#endregion
static void Main(string[] args)
{
var driver = new FirefoxDriver();
driver.Url = "https://www.facebook.com";
// Log-in to Facebook
var txtLogin = driver.FindElementByXPath(LoginLocators.txtEmail_XPath);
var txtPassword = driver.FindElementByXPath(LoginLocators.txtPassword_XPath);
var btnLogIn = driver.FindElementByXPath(LoginLocators.btnLogin_XPath);
txtLogin.SendKeys(userLogin);
txtPassword.SendKeys(userPassword);
btnLogIn.Click();
// Go to F.b. Updates
driver.Url = "https://www.facebook.com/?sk=nf";
// Find Elements on Fb. Updates Page
var txtMessage = driver.FindElementByXPath(PostLocators.txtWhatsOnYourMind_XPath);
var btnPost = driver.FindElementByXPath(PostLocators.btnPost_XPath);
var userMessagesList = driver.FindElementsByCssSelector(PostLocators.userPostsList_CssSelector);
int previousMessagesCount = userMessagesList.Count();
Console.WriteLine("User messages before: {0}", previousMessagesCount);
string messageGuid = Guid.NewGuid().ToString();
// Perform Post Update
/* Problem 1: only the following sub text is typed in the status box:
* "date made by test automation using Selenium" */
txtMessage.SendKeys("Hello! This is an update\n");
txtMessage.SendKeys("From automated script " + messageGuid);
btnPost.Click();
int currentMessagesCount = previousMessagesCount;
/* Problem 2: usually when you post a status, it appears just below
* the status update field.
* How can I identify and confirm it using selenium c#? */
// Wait untill new message is added
while (currentMessagesCount <= previousMessagesCount)
{
userMessagesList = driver.FindElementsByCssSelector(PostLocators.userPostsList_CssSelector);
currentMessagesCount = userMessagesList.Count();
System.Threading.Thread.Sleep(100);
}
Console.WriteLine("User messages after: {0}", currentMessagesCount);
// Just for demo purpose :D
System.Threading.Thread.Sleep(5000);
driver.Quit();
}
}
}
Demo Video:
http://www.youtube.com/embed/_VVcc4zZiwE?vq=hd720

Related

Download/Read Google Ad Manager Reports using Google Ad Manager Api in C# console Application

I am trying to read/download some of the reports i created in Google Ad Manager account using Google Ad Manager Api https://developers.google.com/ad-manager/api/reporting
But couldn't get the results
Also tried NetworkService and InventoryService services of the api to grab some of the data from my google ad manager account which is working correctly as follows:
using Google.Api.Ads.AdManager.Lib;
using Google.Api.Ads.AdManager.Util.v201911;
using Google.Api.Ads.AdManager.v201911;
using Google.Api.Ads.Common.Util.Reports;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Google.Api.Ads.AdManager.Examples.CSharp.v201911
{
/// This example gets all ad units.
public class GetAllAdUnits : SampleBase
{
public string orderId;
/// Returns a description about the code example.
public string Description => "This example gets all ad units.";
/// Main method, to run this code example as a standalone application.
public static void Main()
{
GetAllAdUnits codeExample = new GetAllAdUnits();
Console.WriteLine(codeExample.Description);
try
{
codeExample.Run(new AdManagerUser());
}
catch (Exception e)
{
Console.WriteLine("Failed to get ad units. Exception says \"{0}\"", e.Message);
}
}
private string filePath = "/Users/fazeem/";
/// Run the code example.
public void Run(AdManagerUser user)
{
using (NetworkService networkService = user.GetService<NetworkService>())
{
var network = networkService.getCurrentNetwork();
Console.WriteLine(
$"Current network has the network code {network.networkCode} and " +
$"display name \"{network.displayName}\" and Currency {network.currencyCode}."
);
}
using (InventoryService inventoryService = user.GetService<InventoryService>())
{
// Create a statement to select ad units.
int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
StatementBuilder statementBuilder1 =
new StatementBuilder().OrderBy("id ASC").Limit(pageSize);
// Retrieve a small amount of ad units at a time, paging through until all
// ad units have been retrieved.
int totalResultSetSize = 0;
do
{
AdUnitPage page =
inventoryService.getAdUnitsByStatement(statementBuilder1.ToStatement());
// Print out some information for each ad unit.
if (page.results != null)
{
totalResultSetSize = page.totalResultSetSize;
int i = page.startIndex;
foreach (AdUnit adUnit in page.results)
{
Console.WriteLine(
"{0}) Ad unit with ID \"{1}\" and name \"{2}\" was found.", i++,
adUnit.id, adUnit.name);
}
}
statementBuilder1.IncreaseOffsetBy(pageSize);
} while (statementBuilder1.GetOffset() < totalResultSetSize);
Console.WriteLine("Number of results found: {0}", totalResultSetSize);
}
/////////////////////////////////////////////////////////////////////
// Create report job.
/////////////////////////////////////////////////////////////////////
using (ReportService reportService = user.GetService<ReportService>())
{
ReportJob reportJob = new ReportJob();
reportJob.reportQuery = new ReportQuery();
reportJob.reportQuery.dimensions = new Dimension[]
{
Dimension.ORDER_ID,
Dimension.ORDER_NAME
};
reportJob.reportQuery.dimensionAttributes = new DimensionAttribute[]
{
DimensionAttribute.ORDER_TRAFFICKER,
DimensionAttribute.ORDER_START_DATE_TIME,
DimensionAttribute.ORDER_END_DATE_TIME
};
reportJob.reportQuery.columns = new Column[]
{
Column.AD_SERVER_IMPRESSIONS,
Column.AD_SERVER_CLICKS,
//Column.TOTAL_ACTIVE_VIEW_MEASURABLE_IMPRESSIONS,
//Column.AD_SERVER_CPM_AND_CPC_REVENUE,
//Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM
};
// Set a custom date range for the last 8 days
reportJob.reportQuery.dateRangeType = DateRangeType.CUSTOM_DATE;
System.DateTime endDateTime = System.DateTime.Now;
reportJob.reportQuery.startDate = DateTimeUtilities
.FromDateTime(endDateTime.AddDays(-8), "Australia/Sydney").date;
reportJob.reportQuery.endDate = DateTimeUtilities
.FromDateTime(endDateTime, "Australia/Sydney").date;
// Create statement object to filter for an order.
StatementBuilder statementBuilder = new StatementBuilder().Where("ORDER_ID = :id")
.AddValue("id", orderId);
reportJob.reportQuery.statement = statementBuilder.ToStatement();
// Run report job.
reportJob = reportService.runReportJob(reportJob);
// Download the report
ReportUtilities reportUtilities =
new ReportUtilities(new ReportService(), reportJob.id);
// Set download options.
ReportDownloadOptions options = new ReportDownloadOptions();
options.exportFormat = ExportFormat.CSV_DUMP;
options.useGzipCompression = true;
reportUtilities.reportDownloadOptions = options;
// Download the report.
using (ReportResponse reportResponse = reportUtilities.GetResponse())
{
reportResponse.Save(filePath);
}
Console.WriteLine("Report saved to \"{0}\".", filePath);
}
}
}
}
But the reportService section of the code(which is for downloading/reading reports) is throwing this exception: "Faied to get ad units. Exception says "AdManagerApiException: Exception of type 'Google.api.ads.adManager.lib.adManagerApiException' was thrown"
Any help/Suggestion will be highly appreciated. TIA
P.S I was initially looking for directly reading some of the reports from Ad Manager account but couldn't find any detailed documentation about it so end up downloadig then reading it..So If any one have correct way of directly reading reports from ad manager account, Please share that as well.

C# Google API throws exception

I am using Google API for the first time and I want to use Natural Language API.
But I don't know how.
So I search the internet and found an example code.
But when it uses APIs, the program throws an exception.
problem source code and thrown exception:
using Google.Cloud.Language.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// The text to analyze.
string text = "Hello World!";
try
{
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
Console.WriteLine($"Score: {sentiment.Score}");
Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
The console output:
The Application Default Credentials are not available.
They are available if running on Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
See https://developers.google.com/accounts/docs/application-default-credentials for more information.
What should I do?
I had used NLP a year ago for entity analysis. I had used Google.Apis.CloudNaturalLanguage.v1. I put together my code with what you have written for sentiment analysis. You will need the API key for this:
var service = new CloudNaturalLanguageService(new CloudNaturalLanguageService.Initializer { ApiKey = ApiKey });
var req = new AnalyzeSentimentRequest {
Document = new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
},
EncodingType = "UTF8"
};
var output = service.Documents.AnalyzeSentiment(req);
var exe = output.Execute();
Hope this works.

How do I search google from within my game

I am trying to use google search in my game. I'd like to find out the number of results a specific search query returns.
Currently I am opening a URL with a search query. However the way google works is by loading the page and then streaming in the search results. Unity believes the page has fully loaded and then returns the results too soon.
Below is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
public class SearchWeb: MonoBehaviour {
// I call this method to start the search from an input field
public void Search(InputField _inputField) {
StartCoroutine(GetHtml(_inputField.text.ToString(), ShowResults));
}
// This is my callBack that will post results in the console
public void ShowResults(int _results, string _searchQuery) {
Debug.Log("searching for " + _searchQuery + " results in " + _results + " results.");
}
// This method is responsible for recieving the HTML from a search query
//
IEnumerator GetHtml(string _searchQuery, Action < int, string > _callback) {
// White space in the a google search will return an error from google
_searchQuery = _searchQuery.Replace(" ", "+");
// The URL to send
string url = "https://www.google.com/search?sclient=psy-ab&btnG=Search&q=" + _searchQuery.ToString();
WWW wwwHTML = new WWW(url);
Debug.Log("Attempting to search " + url);
yield
return wwwHTML;
// Process the returned HTML, get useful information out of it
int _results = GetResults(wwwHTML.text.ToString());
// Send it back
_callback(_results, _searchQuery);
yield
return null;
}
// This method is incomplete but would eventually return the number of results my search query found
private int GetResults(string _html) {
Debug.Log(_html);
// Here I can tell by looking in the console if the returned html includes the search results
// At the moment it doesn't
int _startIndex = 0;
int _results = 0;
// looking for this <div id="resultStats"> where the search results are placed
if (_html.IndexOf("<div id=\"resultStats\">", System.StringComparison.Ordinal) > 0) {
_startIndex = _html.IndexOf("<div id=\"resultStats\">", System.StringComparison.Ordinal);
// TODO - Finish this stuff
}
// TODO - For now I'm just debugging to see if I've found where the result stats may be
_results = _startIndex;
return _results;
}
}
It currently returns html which doesnt contain any search results
I don't think google like you using their services in this way - they'd really like you to sign up and access these kind of things via their Custom Search API. This is a nice JSON based api, so you avoid having to do any HTML processing. Getting the answers out of the JSON response in Unity should then be pretty straight forward.
Original tutorials here. Just use GoogleSearch.Search() function. Source code project at Github can be found here.
string query = "The University of Hong Kong";
var results = GoogleSearch.Search(query);
foreach (Result result in results)
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Title: {0}", result.Title);
Console.WriteLine("Link: {0}", result.Link);
}
Console.ReadKey();

C# NameSpace Error With Producing Output [duplicate]

This question already has answers here:
A namespace cannot directly contain members such as fields or methods?
(4 answers)
Closed 8 years ago.
I am running this code in C# in VS2013 which I got from here: http://tda.codeplex.com/. The code is supposed to gather data from my TD Ameritrade 401k account. The code is running fine but when I look in the output folder no file is saved. I keep getting this two errors that I am unable to fix. What am I doing wrong?
namespace TDAmeritrade.Samples
{
using System;
using TDAmeritrade;
class Program
{
static void Main()
{
// Initialize TD Ameritrade client, provide additional config info if needed
var client = new TDAClient();
// Log in to the TD Ameritrade website with your user ID and password
client.LogIn("jessicasusername", "jessicaspassword");
// Now 'client.User' property contains all the information about currently logged in user
var accountName = client.User.Account.DisplayName;
// Get stock quotes snapshot.
var quotes = client.GetQuotes("GOOG, AAPL, $SPX.X, DUMMY");
// 'quotes.Error' contains a list of symbols which have not been found
var errors = quotes.Errors;
// Find symbols matching the search string
var symbols = client.FindSymbols("GOO");
// Get historical prices
var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1));
}
}
}
const string SaveFileToLocation = #"C:\Users\jessica\Desktop\json_data";
string json = JsonConvert.SerializeObject(prices, Formatting.Indented);
using (StreamWriter writer = new StreamWriter(SaveFileToLocation))
{
writer.Write(json);
}
Error 1 A namespace cannot directly contain members such as fields or
methods
Error 2 Expected class, delegate, enum, interface, or struct
this is because you declare some variable outside of a class. just put theme in class Program.
namespace TDAmeritrade.Samples
{
using System;
using TDAmeritrade;
class Program
{
const string SaveFileToLocation = #"C:\Users\jessica\Desktop\json_data";
static void Main()
{
// find best place for these codes.
string json = JsonConvert.SerializeObject(prices, Formatting.Indented);
using (StreamWriter writer = new StreamWriter(SaveFileToLocation))
{
writer.Write(json);
}
// Initialize TD Ameritrade client, provide additional config info if needed
var client = new TDAClient();
// Log in to the TD Ameritrade website with your user ID and password
client.LogIn("jessicasusername", "jessicaspassword");
// Now 'client.User' property contains all the information about currently logged in user
var accountName = client.User.Account.DisplayName;
// Get stock quotes snapshot.
var quotes = client.GetQuotes("GOOG, AAPL, $SPX.X, DUMMY");
// 'quotes.Error' contains a list of symbols which have not been found
var errors = quotes.Errors;
// Find symbols matching the search string
var symbols = client.FindSymbols("GOO");
// Get historical prices
var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1));
}
}
}
The way your code should be arranged is thus:
using System;
using TDAmeritrade;
namespace TDAmeritrade.Samples
{
class Program
{
const string SaveFileToLocation = #"C:\Users\jessica\Desktop\json_data";
static void Main()
{
// Initialize TD Ameritrade client, provide additional config info if needed
var client = new TDAClient();
// Log in to the TD Ameritrade website with your user ID and password
client.LogIn("jessicasusername", "jessicaspassword")
// Get historical prices
var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1));
//You cannot create json until the prices variable has been declared!
string json = JsonConvert.SerializeObject(prices, Formatting.Indented);
using (StreamWriter writer = new StreamWriter(SaveFileToLocation))
{
writer.Write(json);
}
}
}
}

Set class property at runtime

I have a problem with my code, I cannot get it the 'test' to get the values im trying to assign to it.
rec = new Record(perosn, actually, com, Centre, CCentre);
webservicename.singleSummary test = new webservicename.singleSummary();
test.person = rec.person;
test.actually = recc.Actually;
test.com = rec.Com;
test.Centre = rec.Centre;
test.CCentre = rec.CCentre;
webservicename.Feed CallWebService = new webservicename.Feed();
I am trying to get this to pop up in a dialog box to show that it is working, with something like test.account getting showed in the message box, not sure quite what the problem is.
My overall problem is I am trying to set the class porpert at runtime.
Any help is appreciated.
Is "Record" an existing class?
Is this a compile time error and what does the error say?
One simple solution might be to debug into this using visual studio and check the values there, (if your using Visual Studio).
If you're trying check these values at run time (not development time) then you could use javascript to display a message.
Thanks to a WebProNew.com article...http://www.webpronews.com/expertarticles/2006/11/29/javascript-alertshowmessage-from-aspnet-codebehind
using System.Web;
using System.Text;
using System.Web.UI;
///
/// A JavaScript alert
///
public static class Alert
{
///
/// Shows a client-side JavaScript alert in the browser.
///
/// The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "\\'");
string script = "alert('" + cleanMessage + "');";
// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;
// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}
Usage...
void btnSave_Click(object sender, EventArgs e)
{
try
{
SaveSomething();
Alert.Show("You document has been saved");
}
catch (ReadOnlyException)
{
Alert.Show("You do not have write permission to this file");
}
}

Categories

Resources