Selenium File upload on chrome from android phone - selenium

I am trying to upload file in a selenium test that is run on chrome browser on an android phone. The usual element.sendkeys(path) is not working.
Are there any known alternatives for android ?

It may help to upload the file:
public CorePage UploadHack(string fileInputId, string contentType, string fileContent, string fileName, string angularScopeVar)
{
UploadFile(_filePath);
var uploadHack =
"(function(){" +
"function convert(base64){" +
"var raw = atob(base64);" +
"var arr = new Uint8Array(new ArrayBuffer(raw.length));" +
"for (var i = 0; i < raw.length; i++){" +
"arr[i] = raw.charCodeAt(i);" +
"}" +
"return arr; " +
"}" +
$"var file = new Blob([convert('{fileContent}')], {{'type':'{contentType}'}}); " +
$"file.name = '{fileName}'; " +
$"angular.element('#{fileInputId}').scope().{angularScopeVar} = file;" +
"})()";
Driver.ExecuteJavaScript(uploadHack);
return this;
}

Related

RDLC report Index was outside the bounds of the array asp net core

I got Index was outside the bounds of the array error when use debug mode in asp net core mvc, but its ok when run in non-debug mode (Shift+F5).
Here details of error description :
An unhandled exception occurred while processing the request.
IndexOutOfRangeException: Index was outside the bounds of the array.
AspNetCore.ReportingServices.RdlExpressions.ExpressionHostObjectModel.RemoteArrayWrapper.get_Item(int
index)
ReportProcessingException: An unexpected error occurred in Report
Processing. Index was outside the bounds of the array.
AspNetCore.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension
newRenderer)
LocalProcessingException: An error occurred during local report
processing.;An unexpected error occurred in Report Processing. Index
was outside the bounds of the array.
AspNetCore.Reporting.InternalLocalReport.InternalRender(string format,
bool allowInternalRenderers, string deviceInfo, PageCountMode
pageCountMode, CreateAndRegisterStream createStreamCallback, out
Warning[] warnings)
Here my export to pdf code :
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Report\\RptDO2.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
parameters.Add("txtto", inv.Quotation.CustomerContact.Customer.CompanyName);
parameters.Add("txtaddress_detail", inv.Quotation.CustomerContact.Customer.Address1 + "\r\n"
+ inv.Quotation.CustomerContact.Customer.Address2 + "- "
+ inv.Quotation.CustomerContact.Customer.City + "- "
+ inv.Quotation.CustomerContact.Customer.State + " ("
+ inv.Quotation.CustomerContact.Customer.Zip + ")\r\n"
+ "Phone : " + inv.Quotation.CustomerContact.Customer.PhoneNumber
+ ", Email : " + inv.Quotation.CustomerContact.Customer.Email);
parameters.Add("txtdo_no", inv.Id.Replace("INV", "DO"));
parameters.Add("txtdate", inv.Quotation.CreatedAt.ToShortDateString());
parameters.Add("txtrefnum", inv.QuotationId);
parameters.Add("txtfrom", us.FirstName + " " + us.LastName);
parameters.Add("txtUP", TextUp);
parameters.Add("kop_nama", c.CpName);
parameters.Add("kop_alamat", c.CpStreetAddress);
parameters.Add("kop_alamat2", c.CpCity + " " + c.CpState + " (" + c.CpZip + ")");
parameters.Add("kop_contact", c.CpPhone);
parameters.Add("kop_email", c.CpEmail);
parameters.Add("kop_logo", Convert.ToBase64String(c.CpFoto));
parameters.Add("txtjabatan", us.Designation);
parameters.Add("txtPrintedBy", lgnuser.FirstName + " " + lgnuser.LastName);
List<vwQuotationDetail> vwQuotationDetails = new List<vwQuotationDetail>();
foreach (TblquotationDetail quos in inv.Quotation.TblquotationDetail.OrderBy(o => o.Id))
{
vwQuotationDetail quotationDetail = new vwQuotationDetail
{
id = quos.Id,
quotation_id = quos.QuotationId,
order_number = quos.OrderNumber,
product_name = quos.Product.ProductName,
product_id = quos.ProductId,
product_comments = string.IsNullOrEmpty(quos.ProductComments) ? "" : quos.ProductComments,
quantity = quos.Quantity,
unit_price = quos.UnitPrice,
unit_name = quos.Product.Unit.UnitName,
sub_total = quos.SubTotal,
product_desc = quos.Product.ProductDesc,
category_name = quos.Product.Category.CategoryName
};
vwQuotationDetails.Add(quotationDetail);
}
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("dsDO", vwQuotationDetails.ToArray());
//var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
var result = localReport.Execute(RenderType.Pdf, extension, parameters);
return File(result.MainStream, "application/pdf");
Any suggestion will appreciated, thanks in advance.
Just Dont Pass extension as 1 in:
var result = localReport.Execute(RenderType.Pdf, extension, parameters);
The Solution is:
int ext = (int)(DateTime.Now.Ticks >> 10);
var result = localReport.Execute(RenderType.Pdf, ext, param);
In other words, Extension should not be same for every report.

Is that the right way to add digest header in QNetworkAccessManager

Could you help me about QNetworkAccessManager. I am trying to make an digest authentication in C++ QNetworkAccessManager, I couldn't a way to send the request without calculating the digest data. So I am doing the request with calculating the md5 . Does anybody know? Is that the right way to add the header of digest response in QNetworkAccessManager.
Thanks,
QString G_username = QString::fromUtf8(_userName.c_str());
QString G_realm = QString::fromUtf8(_realm.c_str());
QString G_nonce = QString::fromUtf8(_nonce.c_str());
QString G_uri = QString::fromUtf8(urlAfterIp.c_str());
QString G_response = QString::fromUtf8(ha3.c_str());
QString G_qop = QString::fromUtf8(_qop.c_str());
QString G_nc = QString::fromUtf8((_ncString).c_str());
QString G_cnonce = QString::fromUtf8(_cnonce.c_str());
QEventLoop loop;
QNetworkAccessManager* manager = new QNetworkAccessManager();
QNetworkRequest networkRequest;
networkRequest.setUrl(QUrl("http://172.16.101.68/reset"));
//networkRequest.setRawHeader(QByteArray("Authorization"), digestValueToAdd.toUtf8());
networkRequest.setRawHeader(QByteArray("Digest username"), G_username.toUtf8());
networkRequest.setRawHeader(QByteArray("realm"), G_realm.toUtf8());
networkRequest.setRawHeader(QByteArray("nonce"), G_nonce.toUtf8());
networkRequest.setRawHeader(QByteArray("uri"), G_uri.toUtf8());
networkRequest.setRawHeader(QByteArray("algorithm"), "MD5");
networkRequest.setRawHeader(QByteArray("response"), G_response.toUtf8());
networkRequest.setRawHeader(QByteArray("qop"), G_qop.toUtf8());
networkRequest.setRawHeader(QByteArray("nc"), G_nc.toUtf8());
networkRequest.setRawHeader(QByteArray("cnonce"), G_cnonce.toUtf8());
QLabel *label = new QLabel();
QNetworkReply *reply = manager->get(networkRequest);
QObject::connect(reply, SIGNAL(readyRead()),
label, SLOT(slotReadyRead()));
QObject::connect(reply, SIGNAL(finished()),
label, SLOT(slotOnRequestCompleted()));
QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
label, SLOT(slotOnRequestError(QNetworkReply::NetworkError)));
QObject::connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
label, SLOT(slotSslErrors(QList<QSslError>)));
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QByteArray dataReceived = reply->readAll();
QString dataReply(dataReceived);
I solved the problem, right way of adding the digest header is:
digestResponse = "Digest username=\"" + _userName + "\"" + ", realm=\"" + _realm
+
"\"" + ", nonce=\"" + _nonce + "\""
+ ", uri=\"" + urlAfterIp +"\"" + ", algorithm=MD5" + ", response="
+
"\"" + ha3 +"\"" + ", qop=" + _qop + ", nc="
+ _ncString + ", cnonce=\"" +_cnonce + "\"";
QEventLoop loop;
QNetworkAccessManager* manager = new QNetworkAccessManager();
QNetworkRequest networkRequest;
networkRequest.setUrl(QUrl("http://172.16.101.68/reset"));
networkRequest.setRawHeader("Authorization", digestResponse.c_str());

LiveCycle dynamic PDF - how to enforce Acrobat version?

I have a dynamic PDF that doesn't display correctly in Firefox, Chrome, or lower versions of Adobe. Is there a way to show blank page with error message when the user opens it with anything less than Acrobat version X?
I tried searching on this site and Googling but couldn't find anything..
Help much appreciated!!
This can be achieved with a PDF cover page but can also be achieved with your own subform combo and a bit of script. Creating a cover page that is hidden only to reveal your form content if a script executes correctly and is inside a full feature XFA form viewer is one way to tackle this.
function detect(){
//Sample platform detection
var viewerType = xfa.host.appType;
var versionNo = xfa.host.version;
var variation = xfa.host.variation;
var plugIns = app.plugIns;
var nplugIns = plugIns.length;
var msg = "";
if((viewerType == "Reader") && (nplugIns > 0)){
msg = "This PDF was opened in Reader " + versionNo + ", " + variation + ", and loaded " + nplugIns + " plug-ins.";
form1.Top.Cover.presence = "hidden";
form1.Top.Content.presence = "visible";
}
else if((viewerType == "Exchange") && (nplugIns > 0)){
msg = "This PDF was opened in Acrobat " + versionNo + ", " + variation + ", and loaded " + nplugIns + " plug-ins.";
form1.Top.Cover.presence = "hidden";
form1.Top.Content.presence = "visible";
}
else if((viewerType == "Exchange-Pro") && (nplugIns > 0)){
msg = "This PDF was opened in Acrobat Pro " + versionNo + ", " + variation + ", and loaded " + nplugIns + " plug-ins.";
form1.Top.Cover.presence = "hidden";
form1.Top.Content.presence = "visible";
}
else{
msg = "This PDF was opened in an unrecognized platform";
}
xfa.host.messageBox(msg); //Throw prompt.
form1.Top.Content.TextField1.rawValue = msg; //Write message to form.
}
Most of the function above relies on xfa.host.appType but some PDF viewers developped using the Adobe Acrobat code base will return valid platform values but will not load any plug-ins which is a way to detect and unsupported platform.

Running PhantomJs in java

I'm trying to run phantomjs in my program, below is the command I'm running.
Process exec = Runtime.getRuntime().exec(new String[]{
"C:/Users/buddy/Desktop/phantomjs-1.9.7-windows",
"-c",
"phantomjs "
+ pipedCommand + " "
+ size + " "
+ conversion.getConversionTarget().extension() + " "
+ this.local.getId()});
and I'm getting exception when I run: (But above code runs for Linux)
I have downloaded phantomjs windows version and its in the following path: C:/Users/buddy/Desktop/phantomjs-1.9.7-windows
java.io.IOException: Cannot run program "C:/Users/buddy/Desktop/phantomjs-1.9.7-windows": CreateProcess error=5, Access is denied.
I believe you need to run it from a cmd process... not sure if it helps but how I did it was to create a shellscript file with contents similar to below
echo "- Processing : Creating screenshot image from $1"
'C:\software\phantomjs' 'C:\software\rasterize.js' http://$1 $2
and then within the java code
// Create process command
String command = "cmd /c " + imageScriptLocation + " " + cleanUrl + " " + imgLocation
// Execute the process
Runtime rt = Runtime.getRuntime();
p = rt.exec(command);
// Retrieve any errors from the script
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
logger.debug("Image Script: " + line);
}
// Wait for the process to complete and the images to be generated
p.waitFor();
if you just want to use your approach above though, the below should work...
Process exec = Runtime.getRuntime().exec(new String[]{
"cmd",
"/c",
"phantomjs "
+ pipedCommand + " "
+ size + " "
+ conversion.getConversionTarget().extension() + " "
+ this.local.getId()});
You can run PhantomJS using Selenium.
DesiredCapabilities caps = new DesiredCapabilities();
String path = "Path to PhantomJS Binary";
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, path);
WebDriver driver = new PhantomJSDriver(caps);

Get web methods dynamically for an asmx service

We have number of asmx services. I want to give an user a page with a textbox to input service url like http://abc.win.com/myservice/customerdata.asmx. When user hit "Load" button, dynamically I add all the web methods to the dropdown. I need some pointers:
1. How to dynamically get all the methods?
2. How can I get the SOAP request for the method selected? So that, we can replace the parameter values with actual values?
Appreciate your help.
Kuul13 : You need to modify your webservice URL like http://abc.win.com/myservice/customerdata.asmx?wsdl when user clicks on load button. then you can use we "ServiceDescription" class to get wsdl description and then iterate that to get method names in 'WebMethodInfoCollection' class.
To get SOAP request you need to use SOAPExtension class.This will give you SOAP Request and Response XML.Refere this link for that : http://blog.encoresystems.net/articles/how-to-capture-soap-envelopes-when-consuming-a-web-service.aspx?www.microsoft.com
For dynamically calling webservice look a this V.Good article
http://www.codeproject.com/KB/webservices/webservice_.aspx
Please reply me for any comment.
System.Net.WebClient client = new System.Net.WebClient();
System.IO.Stream stream = client.OpenRead("http://www.webservicex.net/globalweather.asmx?wsdl");
ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(description, null, null);
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
if (warning == 0)
{
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
object[] args = new object[1];
args[0] = "India";
object wsvcClass = results.CompiledAssembly.CreateInstance("GlobalWeather");
MethodInfo mi = wsvcClass.GetType().GetMethod("GetCitiesByCountry");
RegExpForCountryCity(mi.Invoke(wsvcClass, args).ToString());
}
else
{
Console.WriteLine("Warning: " + warning);
}
void RegExpForCountryCity(string strHTML)
{
Regex qariRegex = new Regex(#"<Table>\s*<Country>(?<Country>[\s\S]*?)</Country>\s*<City>(?<City>[\s\S]*?)</City>\s*</Table>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
MatchCollection mc = qariRegex.Matches(strHTML);
string strCountryCity = "";
for (int i = 0; i < mc.Count; i++)
{
if (string.IsNullOrEmpty(strCountryCity))
strCountryCity = "Country: " + "<b>" + mc[i].Groups["Country"].Value + "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
else
strCountryCity += "</br>" + "Country: " + "<b>" + mc[i].Groups["Country"].Value + "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
}
Response.Write(strCountryCity);
}