Execute Javascript using Selenium or HtmlUnit - selenium

I need small help.
I want to open some page using Java and Selenium or HtmlUnit, and after opening this page execute url like Ajax and get to String the response.
Let say, a want to open http://www.somepage.com , when driver is still on this page, execute GET http://www.somepage.com/myAjax/xyz , which should return JSON.
Then i want to get the JSON response and do something with it.
Could you help me, how to do it ?
Best regards

To inject your own javascript, you can do something like:
new WebConnectionWrapper(webClient) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if (request.getUrl().toExternalForm().contains("my_url")) {
String content = response.getContentAsString("UTF-8");
// inject the below to the 'content'
String tobeInjected = ""
+ "<script>\n"
+ "var myOwnVariable;\n"
+ "var xmlhttp;\n"
+ "if (window.XMLHttpRequest) {\n"
+ " xmlhttp=new XMLHttpRequest();\n"
+ "}\n"
+ "else {\n"
+ " xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');\n"
+ "}\n"
+ "\n"
+ "xmlhttp.onreadystatechange=function() {\n"
+ " if (xmlhttp.readyState==4 && xmlhttp.status==200) {\n"
+ " myOwnVariable = xmlhttp.responseText;\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "xmlhttp.open('GET', 'http://www.somepage.com/myAjax/xyz', true);\n"
+ "xmlhttp.send();\n"
+ "</script>";
WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
response = new WebResponse(data, request, response.getLoadTime());
}
return response;
}
};
To retrieve the value of the javascript variable:
webClient.waitForBackgroundJavaScript(5_000);
String value = htmlPage.executeJavaScript("myOwnVariable").toString();

Related

YouTube iFrame API Not Working Properly In JavaFX WebView?

So recently I've been working on making an audioplayer that can play playlists made by the user (mp3 files, wav files etc.) but that can also play YouTube playlists. In order to play YouTube videos I use JavaFX's WebView in combination with Google's YouTube iFrame API.
In order to do so, I use the following code;
#Override
public void loadList(String list)
{
html = "<!DOCTYPE html>\n" +
"<html>\n" +
" <body>\n" +
"<iframe id=\"player\" width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/videoseries?list=PL7aXwAD1wk5kdkuQOFBHY63R9Bhki7rCg&enablejsapi=1\" frameborder=\"0\" gesture=\"media\" allowfullscreen></iframe>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" var tag = document.createElement('script');\n" +
" tag.id = 'iframe-demo';\n" +
" tag.src = 'https://www.youtube.com/iframe_api';\n" +
" var firstScriptTag = document.getElementsByTagName('script')[0];\n" +
" var volume = 100;\n" +
" firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\n" +
"\n" +
" var player;\n" +
" function onYouTubeIframeAPIReady() {\n" +
" player = new YT.Player('player', {\n" +
" events: {\n" +
" 'onReady': onPlayerReady,\n" +
" 'onError' : handleError,\n" +
" 'onStateChange' : stateChange,\n" +
" 'onApiChange' : stateChange\n" +
" }\n" +
" });\n" +
" }\n" +
" function onPlayerReady(event) {\n" +
" event.target.playVideo();\n" +
" //event.target.nextVideo();\n" +
" }\n" +
" \n" +
" function handleError(event)\n" +
" {\n" +
" console.log(event);\n" +
" player.nextVideo();\n" +
" }\n" +
" \n" +
" function setVolume(vol)\n" +
" {\n" +
" volume = vol;\n" +
" player.setVolume(vol);\n" +
" }\n" +
" \n" +
" function stateChange(event)\n" +
" {\n" +
" // player.setVolume(volume + 1);\n" +
" // player.setVolume(volume - 1);\n" +
" // player.setVolume(volume);\n" +
" }\n" +
"</script>\n" +
" </body>\n" +
"</html>";
jfxPanel = new JFXPanel();
Platform.runLater ( new Runnable () {
#Override
public void run () {
player = new WebView();
player.getEngine().setJavaScriptEnabled(true);
player.getEngine().loadContent(html);
jfxPanel.setScene(new Scene(player));
JFrame f = new JFrame();
f.add(jfxPanel);
f.setSize(1280,720);
f.setVisible(true);
}
} );
GraphicalInterface.uptodate = false;
}
The issue I am having is this:
Once I use the API's 'player.setVolume(vol)' functionality, it correctly changes the volume for the video it is currently playing. When a new video loads, the videoplayer still shows the volume is the same as it had previously been set to, but it outputs too high of a volume;
first video, lowered volume;
second video, volumeslider is lowered, volume itself isn't;
I only have this issue when using JavaFX's WebView. When I paste the HTML code in a .html file and run it that way, the audio is correctly lowered (and not just the audio slider).
Does anyone know why this could be happening and how I can fix this? Does it have to do with the WebView's settings?
Note:
In the JavaScript I have commented out a small piece of code. This code is a small temporary workaround that "re-setd" the audio to where it should be when a new video is loaded. This solution is not ideal though.

How do I call Pay U Money Server through WCF?

i am creating a wcf service for Pay u Money I wrote same code like asp.net c# for Pay u Money, but using HttpWebRequest I'm facing this error:
SORRY! We were unable to process your payment
Same code I tried in simple asp.net c# and there working fine. Here I don't know what goes wrong, how could I solve this?
enter code here
public PayUMoneyModel PayUMoney(PayUMoneyModel Data)
{
PayUMoneyModel objPayUMoneyModel = new PayUMoneyModel();
action1 = ConfigurationManager.AppSettings["PAYU_BASE_URL"] +
"/_payment";
try
{
string[] hashVarsSeq;
string hash_string = string.Empty;
if (string.IsNullOrEmpty(Data.txnid)) // generating txnid
{
Random rnd = new Random();
string strHash = Generatehash512(rnd.ToString() +
DateTime.Now);
txnid1 = strHash.ToString().Substring(0, 20);
}
else if(Data.txnid!=null)
{
txnid1 = Data.txnid;
}
Data.txnid = txnid1;
Data.key= ConfigurationManager.AppSettings["MERCHANT_KEY"];
string salt= ConfigurationManager.AppSettings["SALT"];
System.Collections.Hashtable data = new System.Collections.Hashtable();
data.Add("key", Data.key);
data.Add("txnid", Data.txnid);
string AmountForm = Convert.ToDecimal(Data.amount).ToString("g29");// eliminating trailing zeros
//amount.Text = AmountForm;
data.Add("amount", 1.00);
data.Add("firstname", Data.firstname);
data.Add("email", Data.email);
data.Add("phone", Data.phone);
data.Add("productinfo", Data.productinfo);
data.Add("surl", Data.surl);
data.Add("furl", Data.furl);
data.Add("lastname", Data.lastname);
data.Add("curl", Data.curl);
data.Add("address1", Data.address1);
data.Add("address2", Data.address2);
data.Add("city", Data.city);
data.Add("state", Data.state);
data.Add("country",Data.country);
data.Add("zipcode", Data.zipcode);
data.Add("udf1", Data.udf1);
data.Add("udf2", Data.udf2);
data.Add("udf3", Data.udf3);
data.Add("udf4", Data.udf4);
data.Add("udf5", Data.udf5);
data.Add("pg", Data.pg);
data.Add("service_provider", "payu_paisa");
hash_string = Data.key + "|" + Data.txnid + "|" + AmountForm + "|" + Data.productinfo+ "|" + Data.firstname + "|" + Data.email + "|||||||||||" + salt;
string hash = Generatehash512(hash_string);
data.Add("hash", hash);
data.Add("abc", hash_string);
string strForm = PreparePOSTForm(action1, data);
if (strForm != "")
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(action1);
// httpWebRequest.ContentType = "text/html";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = strForm.Length;
string Json = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(strForm,0,strForm.Length);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
Json = streamReader.ReadToEnd().Replace(";", "");
}
}
HttpContext.Current.Response.Write(Json);
}
}
catch(Exception ex)
{
throw ex;
}
return objPayUMoneyModel;
}
this is my Post Form Method
private string PreparePOSTForm(string url, System.Collections.Hashtable data) // post form
{
//Set a name for the form
string formID = "PostForm";
//Build the form using the specified data to be posted.
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");
foreach (System.Collections.DictionaryEntry key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key.Key +
"\" value=\"" + key.Value + "\">");
}
strForm.Append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formID + " = document." +
formID + ";");
strScript.Append("v" + formID + ".submit();");
strScript.Append("</script>");
//Return the form and the script concatenated.
//(The order is important, Form then JavaScript)
return strForm.ToString() + strScript.ToString();
}
this is my key and salt provided by Payumoney website:-
Key:-rjQUPktU
Salt:-e5iIg1jwi8

Saved Docusign Document PDF's come out corrupted

I created a listener page that receives the Docusign webhooks. Everything is working as far as pulling data from the webhook, but when I cycle through the DocumentPDF's, it creates the PDF files but they are corrupted and cannot be opened (when I try to open it in Acrobat, I receive the following message: Acrobat could not open ... because it is either not a supported file type or because the file has been damaged.")
Can anybody help me figure out why the created pdf files are corrupted?
My code for the page is as follows:
protected void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(Request.InputStream);
string xml = sr.ReadToEnd();
string fileName = HttpContext.Current.Server.MapPath("") + "\\Results\\" + DateTime.Now.Ticks + ".xml";
File.WriteAllText(fileName, xml);
try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
var mgr = new XmlNamespaceManager(xmldoc.NameTable);
mgr.AddNamespace("a", "http://www.docusign.net/API/3.0");
XmlNode envelopeStatus = xmldoc.SelectSingleNode("//a:EnvelopeStatus", mgr);
XmlNode envelopeId = envelopeStatus.SelectSingleNode("//a:EnvelopeID", mgr);
XmlNode status = envelopeStatus.SelectSingleNode("//a:Status", mgr);
if (status.InnerText == "Completed")
{
LogException("Looking for DocPDF's_" + DateTime.Now.Ticks + ";");
// Loop through the DocumentPDFs element, storing each document.
XmlNode docs = xmldoc.SelectSingleNode("//a:DocumentPDFs", mgr);
foreach (XmlNode doc in docs.ChildNodes)
{
string documentName = doc.ChildNodes[0].InnerText; // pdf.SelectSingleNode("//a:Name", mgr).InnerText;
string documentId = doc.ChildNodes[2].InnerText; // pdf.SelectSingleNode("//a:DocumentID", mgr).InnerText;
string byteStr = doc.ChildNodes[1].InnerText; // pdf.SelectSingleNode("//a:PDFBytes", mgr).InnerText;
LogException("Writing Out PDF_" + HttpContext.Current.Server.MapPath("") + "\\Documents\\" + envelopeId.InnerText + "_" + documentId + "_" + documentName + "_" + DateTime.Now.Ticks + ";");
File.WriteAllText(HttpContext.Current.Server.MapPath("") + "\\Documents\\" + envelopeId.InnerText + "_" + documentId + "_" + documentName, byteStr);
LogException("Successfully wrote out PDF_" + DateTime.Now.Ticks + ";");
}
}
}
catch (Exception ex)
{
LogException("Exception: " + ex.Message + "; InnerException: " + ex.InnerException.ToString() + "_" + DateTime.Now.Ticks + ";");
}
}
#mkl is correct. The Webhook (Connect) notification message's PDF content is base64 encoded. Decode it to obtain the PDF file.
An example: see line 402 of the recipe example webhook listener --
pdf_file.write(base64.b64decode(pdf.PDFBytes.string))
I am using an Azure Function and using a Blob storage to save it.
This worked for me:
var byteStr = doc.ChildNodes[1].InnerText;
outputBlob.Write(System.Convert.FromBase64String(byteStr));

Paypal IPN cannot send to my MVC 4 controller action

I try to get IPN message from my MVC Controller action but IPN cannot send to my action controller
The following is my controller action :
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] Param = Request.BinaryRead(HttpContext.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(Param);
strRequest = strRequest + "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//Dim proxy As New WebProxy(New System.Uri("http://url:port#"))
//req.Proxy = proxy
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED") {
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
} else if (strResponse == "INVALID") {
//log for manual investigation
} else {
//Response wasn't VERIFIED or INVALID, log for manual investigation
}
The following is paypal information I used :
<add key="paypalAccount" value="abc#abc.com" />
<add key="PayPalSubmitUrl" value="https://www.paypal.com/cgi-bin/webscr"/>
<add key="PDTToken" value="asdfwlfti2Rc_Kskwsdfc7uK26FmT1pdAkhSdLb8FvS2kQ-ZQp6VoF2SqYem"/>
<add key="FromMail" value="myat#abc.com"/>
<add key="return_Url" value="http://testing/Purchase/PayPalResult"/>
<add key="cancel_return" value="http://testing/Purchase/Purchase"/>
<add key="notify_url" value="http://testing/Purchase/PayPalPaymentNotification"/>
<add key="Test_Live" value="live"/>
<add key="BCC" value="myat#abc.com"/>
But in paypal IPN message is still retrying and I didn't receive anything
I notice that HttpContext.Request.ContentLength is always 0 and response status for paypal is always is INVALID
So please advice me what should I do?
Thank you
This is my full action to get IPN message
public ActionResult PayPalPaymentNotification()
{
string strLog = "";
string currentTime = "";
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Start IPN request','" + currentTime + "')";
InsertData(strLog);
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] Param = Request.BinaryRead(HttpContext.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(Param);
strRequest = strRequest + "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//Dim proxy As New WebProxy(New System.Uri("http://url:port#"))
//req.Proxy = proxy
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Status - Verified','" + currentTime + "')";
InsertData(strLog);
}
else if (strResponse == "INVALID")
{
//log for manual investigation
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Status - Invalid','" + currentTime + "')";
InsertData(strLog);
}
else
{
//Response wasn't VERIFIED or INVALID, log for manual investigation
}
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Finish IPN Request','" + currentTime + "')";
InsertData(strLog);
return View();
}
Your return URL isn't right - the message can never be returned.
Add [AllowAnonymous] above the controller action.
Paypal needs to know the URL of your listener service that indicates where the IPNs need to go. You must review the IPN Notification section on your Paypal account and set the URL.
For this you can review the following section: Paypal developer and set the notifications URL.
After that you must have a payment notification to recieve.
My recomendation is first use the Paypal developer section with Sandbox whis is king of fake account that you can use for testing this application.

Rename File Using SharePoint Client Object Model?

This may seem like a stupid question but I can't seem to find any answers on Google.
I have written a method to query SharePoint and rename a document based on the document name parameter I specify. I have used a similar method to rename folders and this has worked fine however when I try to rename a file I get an ArgumentOutOfRangeException
Here is my code:
public bool RenameFileInDocumentLibrary(string documentName, string newDocumentName, ClientContext clientContext)
{
{
bool isDocumentRenamed = false;
string url = "MySharePointSite";
List list = clientContext.Web.Lists.GetByTitle("MyDocLib");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
"<Query>" +
"<Where>" +
"<And>" +
"<Eq>" +
"<FieldRef Name=\"FSObjType\" />" +
"<Value Type=\"Integer\">2</Value>" +
"</Eq>" +
"<Eq>" +
"<FieldRef Name=\"Title\"/>" +
"<Value Type=\"Text\">" + documentName + "</Value>" +
"</Eq>" +
"</And>" +
"</Where>" +
"</Query>" +
"</View>";
var files = list.GetItems(query);
clientContext.Load(list);
clientContext.Load(list.Fields);
clientContext.Load(files, fs => fs.Include(fi => fi["Title"],
fi => fi["DisplayName"],
fi => fi["FileLeafRef"]));
clientContext.ExecuteQuery();
if (files.Count == 0)
{
files[0]["Title"] = newDocumentName;
files[0]["FileLeafRef"] = newDocumentName;
files[0].Update();
clientContext.ExecuteQuery();
isDocumentRenamed = true;
}
return isDocumentRenamed;
}
}
}
Any help with this would be appreciated. Thanks!
You need to use the ListItems File member:
string newPath = files[0]["FileDirRef"] + "/" + "MyNewFileName" + ".extension";
files[0].File.MoveTo(newPath, MoveOperations.Overwrite);
files[0].Update();
clientContext.ExecuteQuery();