Whatsapp Web Selenium with C# send message without reloads the web - whatsapp

I have created one project for automating Whatsapp message using web Whatsapp with selenium in C# code. It works perfectly fine but every time the URL is loaded for new message, how can I stop reloading the page and send message?
Below is my code and I have one for loop for all my numbers and I am calling SendMessage method for every numbers
private void SendMessage(string number, string message)
{
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
driver.Navigate().GoToUrl("https://api.whatsapp.com/send?phone=" + number + "&text=" + Uri.EscapeDataString(message));
driver.FindElement(By.Id("action-button")).Click();
driver.FindElement(By.CssSelector("button._2lkdt>span")).Click();
}
I need like this video: https://youtu.be/vzxyhPPEp9w?t=100
Thanks

Related

Open verification code sent in mail box then copy this code and paste it into verification code field in selenium testing

I am new to selenium web testing i have automated a Sign-In process for a web base application. now making it for Sign Up process i am stuck at a point where a verification code is sent to a mail address and then i have to copy that into my verification code field and proceed further
As i have searched so far i came to know about the mailosaur server but unable to copy that email verification code into my automated web browser. i also searched for the tutorials but unable to find any useful resource. also i want to generate random emails that part is also not getting in my mind.
As i am new to selenium so it is requested to please provide detail answer so i can understand it better, Thanks in advance, working on Intellij, Mavaen (Java)
You can use mailinator.com. No need to register or create a mail box. In your app just enter email with made up name #mailinator.com (asad1#mailinator.com, asadXY#mailinator.com, whatever).
To collect confirmation link (double opt in) I'm using this:
public class Mailinator {
public WebDriver driver;
public Mailinator(WebDriver driver) {this.driver = driver;}
public String urlMailinator = "https://www.mailinator.com/";
public WebDriverWait waitSec(WebDriver driver, int sec) {return new WebDriverWait(driver, sec);}
public static String doubleOptInLink = null;
public String getDoubleOptInLink() {return doubleOptInLink;}
public void setDoubleOptInLink (String doubleOptInLink) {Mailinator.doubleOptInLink = doubleOptInLink;}
public void collectDoubleOptInLink(String userEmail, int expectedNumberOfDeliveredEmails) throws InterruptedException {
driver.get(urlMailinator);
WebElement fldInbox = waitSec(driver, 5).until(ExpectedConditions.elementToBeClickable(By.id("inboxfield")));
fldInbox.sendKeys(userEmail);
WebElement btnGo = driver.findElement(By.xpath("/html/body/section[1]/div/div[3]/div[2]/div[2]/div[1]/span/button"));
btnGo.click();
waitSec(driver, 600).until(ExpectedConditions.numberOfElementsToBe((By.xpath("//*[#id=\"inboxpane\"]/div/div/div/table/tbody/tr")), expectedNumberOfDeliveredEmails));
WebElement lastMailLink = driver.findElement(By.xpath("//*[#id=\"inboxpane\"]/div/div/div/table/tbody/tr"));
lastMailLink.click();
Thread.sleep(3000);
driver.switchTo().frame(driver.findElement(By.id("msg_body")));
setDoubleOptInLink(driver.findElement(By.xpath("//*[#id=\"intro\"]/tbody/tr/td/a")).getAttribute("href"));
}
}
In my scenario:
register to webapp with new made up email, confirmation email is send
using collectDoubleOptInLink(email, 1); is the confirmation link set as doubleOptInLink
calling another method to go to the confirmation link with getDoubleOptInLink();
Sure you will need change what string comes to setDoubleOptInLink();
In specific cases don't forget to setDoubleOptInLink(null);.

How to Handle Authentication alert of browser in selenium webdriver?

Can anyone know that how can we handle Authenticate alert box of browser in selenium Webdriver ?
I user following code but its not working.
driver.switchTo().alert().authenticateUsing(new UserAndPassword("uname", "Password"));
Here is a screenshot of what I am trying to fill in:
Does anyone know how can I enter those credentials?
You can handle this in two ways:
You can pass the username and password directly through the URL like this:
driver..get("https://MyUserName:password#staging.www.abc.com")
You can also use AutoIT Tool for handling any kind of window popups.
For this you first have to download and install AutoIt
Then download SciTE4AutoIt3
You can do scripting in it, or you can use Au3Recorder. It is not available in new versions of SciTE, but you can download it from old versions separately. Unzip it and copy:
autoit-v3.3.14.0.zip\install\Extras\Au3Record
to
[#Install Dir of AutoIt in Program files]\Extras\Au3Record
Now you can start the recorder directly by clicking Au3Record.exe or you can find it in the Script Editor window Tools >AU3Recorder.
For it you have to create a blank .au3 file in the Script Editor. Now start recording. Perform action on Window Popup. Stop when Done. Save it with .au3 format.
Now GO to Saved File location >> Right Click on the File and compile it (Compile Script(x64) or else). It will create an .exe file in the same folder.Now run that script in your Project using:
Runtime.getRuntime().exec("File Loaction/MyAutoItScript.exe");
It will work.
Try below code:
String username = "myUsername";
String password = "myPassword";
String URL = "http://" + username + ":" + password + "#" + sso.mywebsite.com/usdf/ls/dia?kkkk;
driver.get(URL); // Basically operation done here itself still if not work use further Alert code as well
Alert alert = driver.switchTo().alert();
alert.accept();
Full code will be like:
driver.get("https://sso.mywebsite.com/usdf/ls/dia?kkkk");
String url = driver.getCurrentUrl().replaceAll("https://", "");
String username = "myUsername";
String password = "myPassword";
String URL = "https://" + username + ":" + password + "#" + url;
driver.get(URL); // Basically operation done here itself still if not work use further Alert code as well
Alert alert = driver.switchTo().alert();
alert.accept();
Note : Even alert code do not required .. use it as it works for you and this code works on chrome better
Something like this?
driver.Navigate().to("http://UserName:Password#url.‌​com")
or
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(*username*, *password*));
I use Java for my test automation. I have searched for a decent way to deal with these sign in pop ups and cannot find one. The most common answers are either to include in a URL as prefix prior to the real url (eg https:\username:password#www.website.com) or to use a wait for alert. These have not worked for me as: on a form submit there is no simple url to use and I am not sure as to the security including the password in the start of the url; with the wait for alert the webdriver hangs until there is a response - which only comes from submitting the login response via the pop up.
The workaround I have found is poor - I've not got it to work in a headless environment and so limits this answers usefulness. Would be great to get a real answer here. Note that I am running this in a Windows environment and if I was using Linux I have read that I could use xvfb to provide a 'screen' for sikuli and then this would work - if anyone can comment on how to do this on a Windows server that would be MUCH appreciated.
I use Sikuli for the automation of things I cannot automate via Selenium. Sikuli does many things, including letting you basically feed it images that it performs actions on.
For this purpose I run Sikuli on a thread started prior to clickin the submit that leads to the sign in pop-up. As it is running on a different thread it doesn't block the main thread, so it can still execute the log in. Once it logs in it shuts down and logging in closes the pop up and reactivates the main thread.
Specifically:
Sikuli MAVEN entry for POM:
<dependency>
<groupId>com.sikulix</groupId>
<artifactId>sikulixapi</artifactId>
<version>1.1.4-20191010.160947-268</version>
</dependency>
In the main code use a runnable executed via an executor:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
private final AtomicInteger expectedResultCount;
private final AtomicInteger publishedResultCount;
private final ExecutorService executor;
ExecutorService executor = Executors.newFixedThreadPool(5);
String processName = "asic-login";
LoginPopUp login = new LoginPopUp(this, processName);
addResultExpectation(processName);
executor.execute(login);
The runnable here implements an interface I use to keep things tidy:
The main class implements the interface to manage the threads:
public class TestRunner implements ResultPublisher{
These are functions inside the main class for thread management:
private void addResultExpectation(String process){
resultMap.put(process, new JSONObject());
expectedResultCount.addAndGet(1);
}
public void publishResult(JSONObject result){
String process = result.getString("process-name");
String strResult = result.getString("result");
resultMap.put(process, result);
publishedResultCount.addAndGet(1);
if(publishedResultCount.get() == expectedResultCount.get()){
executor.shutdown();
System.out.println("shutting down executor for run " + runId);
}
}
This is the interface
import org.json.JSONObject;
public interface ResultPublisher {
void publishResult(JSONObject result);
}
This is the runnable Runnable - an inner class in the TestRunner main class:
private class LoginPopUp implements Runnable{
private ResultPublisher publisher;
private String filePath;
private String processName;
private LoginPopUp(){
}
public LoginPopUp(ResultPublisher publisher, String processName){
this.publisher = publisher;
this.processName = processName;
}
private void publish(JSONObject result){
publisher.publishResult(result);
}
public void run(){
JSONObject result = new JSONObject();
result.put("path", filePath);
try{
Screen sd = new Screen();
ScreenUtility s = new ScreenUtility(imagesDirectory);
s.clickImage("LoginTitle.PNG", 10, 2500);
s.typeImageWithOffset("UserName.PNG", userName, 30,0);
s.typeImageWithOffset("Password.PNG",String.valueOf(password), 50,0);
s.clickImage("AsicSignIn.PNG", 10, 250);
}catch(Exception ex){
result.put("result", ex.getMessage());
result.put("process-name", processName);
publish(result);
Logger.getLogger(BCSRobot.class.getName()).log(Level.SEVERE, null, ex);
return;
}
result.put("result", "logged in successfully");
result.put("process-name", processName);
publish(result);
return;
}
}

Twillio , connect between 2 numbers

I am trying to achieve following functionality with twillio.js on client side and ASP.NET Mvc website at the backend.
I need to connect a call between real phone number of sales person and phone number of a potential client.
For example on button click , I need to call potential client , and in a case the client answered , i need to add to the call sales person (that is not using twillio number , using regular landline)
Is it possible to achieve with twillio ?
Karen, hello!
Were you able to achieve what you were looking for with Alex's suggestion of the Click to Call tutorial?
https://www.twilio.com/docs/tutorials/walkthrough/click-to-call/csharp/mvc
The above uses a web form and ajax to send the form asynchronously. Then we handle the POST from our web form and connect the call via the REST API.
/// <summary>
/// Handle a POST from our web form and connect a call via REST API
/// </summary>
[HttpPost]
public ActionResult Call(Contact contact)
{
if (!ModelState.IsValid)
{
return Json(new { success = false, message = (ModelState.Values.First()).Errors.First().ErrorMessage, });
}
var twilioNumber = ConfigurationManager.AppSettings["TwilioNumber"];
// The following line is how you should get the absolute Uri in an internet faced
// server or a production environment
// var handlerUri = Url.Action("Connect", "Call", null, Request.Url.Scheme);
// this line allow us to get the absolute Uri in a local computer using a secure instrospectable
// service like ngrok ;)
var handlerUri = GetTestUri();
_twilioService.CallToNumber(twilioNumber, contact.Phone.Replace(" ", ""), handlerUri);
return Json(new { success = true, message = "Phone call incoming!"});
}
Please let me know if this is helpful for your use case.

twilio nuget package not sending SMS message in vb.net

Does the twilio asp.net helper library package NOT work in vb.net? I can get it to work in c# web app but not vb.net web app.
In a vb.net web application project the following code doesnt send an sms message and when stepping through with the debugger, errs on the send message line and brings up a file dialog asking for access to core.cs. The twilio library's were installed via nuget.
Public Shared Sub SendAuthCodeViaSms(ByVal number As String)
Dim twilioAccountInfo As Dictionary(Of String, String) = XmlParse.GetAccountInfoFromXmlFile("twilio")
Dim accountSid As String = twilioAccountInfo("username")
Dim authToken As String = twilioAccountInfo("password")
If (Not String.IsNullOrEmpty(accountSid) AndAlso Not String.IsNullOrEmpty(authToken)) Then
Dim client = New TwilioRestClient(accountSid, authToken)
client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
Else
'log error and alert developer
End If
End Sub
But in a C# web API project the same code sends the message as expected.
protected void Page_Load(object sender, EventArgs e)
{
const string AccountSid = "mysid";
const string AuthToken = "mytoken";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage(TwilioSendNumber,ToNumber,"text message from twilio");
}
and all the sid's and tokens and phone number formats are correct, otherwise the c# one wouldnt send and I wouldnt get to the client.SendMessage part of vb.net version (client.SendSMSMessage produces the same result)
Twilio evangelist here.
I tried our your code by creating a simple VB console app and it worked for me.
The only thing I can think of is that either you are not getting your Twilio credentials correctly when parsing the XML, or the phone number you are passing into the function is not formatted correctly.
I'd suggest putting the result of call to SendMessage() into a variable and checking to see if RestException property is null:
Dim result = client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
If (Not IsNothing(result.RestException)) Then
' Something bad happened
Endif
If Twilio returns a status code greater than 400, then that will show up as an exception in the RestException property and will give you a clue as to whats going on.
If that does not work, you can always break out a tool like Fiddler to watch and see if the library is making the property HTTP request and Twilio is returning the proper result.
Hope that helps.

HttpWebRequest for ShoutCast on Windows Phone7

I tring to stream shoutcast stream in my window phone 7 app
I start an async HttpWebRequest like this
//Init Request
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://ACommonoShoutCastUrl:8000");
myHttpWebRequest.Headers["Icy-MetaData"] = "1";
myHttpWebRequest.UserAgent = "WinampMPEG/5.09";
myHttpWebRequest.AllowReadStreamBuffering = true;
//Call
// Create an instance of the RequestState and assign the previous myHttpWebRequest object to its request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myHttpWebRequest;
// Start the asynchronous request.
IAsyncResult result = (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallBack), myRequestState);
The problem is that the CallBack->RespCallBack is never called...
This code worked for me normally in other environments but not on the phone...
I tired also to use WebClient that seems to stream data,
the problem in this case is that it never call the end OpenReadCompleted because of endelss shoutcast stream
Thanks for support
any help would be appreciated
SHOUTcast implements its own protocol so you can't directly access and play it. You can use DownloadStringAsync (you will need a WebClient instance for this) to download the PLS file and read the URL with the help of RegEx.
When you get the URL, you can read the raw audio data by implementing MediaStreamSource and then use a MediaElement to play the contents.
You can find a sample implementation of MediaStreamSource here.
I just put the following on a page and the callback was called in repsonse to the button click. (I set a break point on the throw statement and it was hit.)
private HttpWebRequest myHttpWebRequest;
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//Init Request
//The following URI was chosen at random
myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://yp.shoutcast.com/sbin/tunein-station.pls?id=1377200");
myHttpWebRequest.Headers["Icy-MetaData"] = "1";
myHttpWebRequest.UserAgent = "WinampMPEG/5.09";
myHttpWebRequest.AllowReadStreamBuffering = true;
// Start the asynchronous request.
myHttpWebRequest.BeginGetResponse(RespCallBack, myHttpWebRequest);
}
private void RespCallBack(IAsyncResult ar)
{
throw new NotImplementedException();
}
I am trying to implement the Shoutcast streaming to my MediaElement via my own MediaStreamSource class. I have a loop in which I am downloading data from Shoutcast server and then set the data to the MediaStreamSource class - this works not perfectly for yet, but I discovered another more important issue. I made a test. I have downloaded a stream to a mp3 (stream is in mp3) file, then put this file to my application and set it to my MediaStreamSource. Here's the code for this:
private void Button_Click(object sender, RoutedEventArgs e)
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
var res = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Demo1.sample.mp3");
byte[] data = new byte[res.Length];
res.Read(data, 0, data.Length);
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
ShoutcastMediaStreamSource ss = new ShoutcastMediaStreamSource(ms);
player.SetSource(ss);
}
my ShoutcastMediaStreamSource based on MenagedMediaHelpers. So when I put this stream to my ShoutcastMediaStreamSource in debbuger I can see that the method OpenMediaAsync() is called properly, then the GetSampleAsync() is called in a loop by MediaElement, here also everything is fine, but when I run this app there is no sound ! Neither on the emulator nor on the device, and there are no errors. I think, the GetSampleAsync() method is running too fast, bacause for the file (and also stream) duration is about 30 sec., and this app ends after ca. 10 sec. But nevertheless, there should be a sound (scratch).
BUT whats suprising - this app works in Silverlight as Web Page ! The music is playing. I am confused.
Here is allso an app
http://timheuer.com/blog/archive/2010/08/16/download-and-store-media-for-playback-in-windows-phone-7-using-mediastreamsource.aspx
and there is a comment:
If Mp3MediaStreamSource is set as a
source for MediaElement then
MediaElement doesn't play that file
and donesn't show any error in Windows
phone 7 sdk RTM version. In previsios
version it was working but it's not
working with Windows phone 7 sdk final
release.
The callback gets called if you disable read stream buffering:
webRequest.AllowReadStreamBuffering = false;