Selenium File Upload iOS or Android using BrowserStack - android

Is there any possibility to upload a file on mobile browser (Safari on iOS, Chrome on Android)? Conventional methods doesn't seem to work. Maybe there are similar options to BrowserStack where file upload can actually work?

BrowserStack uses Appium to drive your Selenium tests on Android and iOS.
As given here, since Appium currently does not support uploads, BrowserStack too wouldn't be able to support File Upload on mobile devices.

This is a hacky file upload solution using base64 and JS, but it works, so hey, I hope you find this useful:
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

Invalid Request when debuging on Android devide, Xamarin

I'm writing a project in Xamarin Forms, and today we try our app on Android device. And our request to googleAPI stop working. Here's code :
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=" + position.Latitude + "," + position.Longitude + "&radius=1000&types=bar&sensor=false&key=APIKEY") as HttpWebRequest;
webRequest.Method = "GET";
webRequest.BeginGetResponse(new AsyncCallback(RequestCompleted), webRequest);
and then :
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
var r = new StreamReader(stream);
var resp = r.ReadToEnd();
}
We got response and change it to json. On computer it works OK, but on Android it is saying INVALID REQUEST. Someone worked with Xamarin and know how to solve it?
If I would have to guess, I'd guess, that the locale/ language on your phone is different to that one on your pc.
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=" + position.Latitude + "," + position.Longitude + "&radius=1000&types=bar&sensor=false&key=APIKEY") as HttpWebRequest;
There are implicit ToString() at ...n=" + position.Latitude + "," + position.Longitude + "&ra... that produce a localized output. But the google API needs the values with a . as decimal separator.
Append .ToString("G", CultureInfo.InvariantCulture)
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=" +
position.Latitude.ToString("G", CultureInfo.InvariantCulture) +
"," + position.Longitude.ToString("G", CultureInfo.InvariantCulture) +
"&radius=1000&types=bar&sensor=false&key=APIKEY") as HttpWebRequest;

java.io.filenotfound android exception on web service call

I am getting exception java.io.filenotfound android exception on web service call in android.But when I run the same url in my browser it works fine.I am communication with the project running on local host in visual studio. My url is like this:
http://10.0.2.2:7378/HighriseeSite/appservices.svc/savewc?WcID=3646&WODetailID=480982&PSID=2084&wcdate=07/14/2015 &wcompleted=1&remarks=&rabill=0&connectivityID=0&length=0&breadth=0&height=0&execby=0
When I use the same url in my browser by replacing 10.0.2.2 with the localhost it works fine webservice gets called.But when the same url is called from the android studio project I get the exception:
java.io.filenotfound
and in the visual studio where project is running and from where the webservice is being called I get the exception as:
Object reference not set to an instance of an object.
But the same url works fine in the browser.I am not able to detect what is wrong with this.Any kind of help will be appreciated.
My code for accessing webservice is like this:
for( WCompletionData Itm:lstWC)
{
if(Float.parseFloat (Itm.getCompQty())>0.0)
{
ur = "http://" + ServerDetails.hostServer + "/appservices.svc/savewc?WcID=" + Itm.getWO_No().trim() + "&WODetailID=" + Itm.getWODetail_Id().trim() + "&PSID=" + Itm.getPS_Id().trim() + "&wcdate=" + currentDateTimeString.trim().trim() + " &wcompleted=" + Itm.getCompQty().trim() + "&remarks=&rabill=" + Itm.getRABill_Id().trim() + "&connectivityID=0&length=0&breadth=0&height=0&execby=0";
//String ur = "http://"+ServerDetails.hostServer+"/appservices.svc/TaskQuanityList?MaterialID="+MatrID+"&ProjectNo="+ProID+"&TaskNo="+TaskID;
Log.d("URLgggrn", ur);
// Replace it with your own WCF service path
URL json = new URL(ur);
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
line = reader.readLine().toString();
Log.d("Line", line);
WCNo = WCNo + line + ",";
}
I am using same code on another activity and it works fine on that activity.
To get rid of File Not Found Exception while requesting to a URL
from android we should avoid white space from URL. If you need to pass
parameter data which contain space you have to use below code
String param1 = "happy coding";
String url = "http://example.com/query?q=" + URLEncoder.encode(param1 , "UTF-8");

AJAX not being called on load in PhoneGap 2.9.1

I am trying to load and parse an XML file onto a page in my PhoneGap application. My XML file is in the correct directory.
When I run page in Google Chrome using a Local Apache Web Server, the file is loaded and Parsed, but when I run the application on my Device. (Samsung Galaxy SII GT-i9100p) The script doesn't run. I have tried everything I can think of. The thing that has stumped is that it was working a few days ago, up until I changed the script to parse the data into a jQuery Mobile Collapsible.
Any help would be much appreciated.
Here is my code:
$(function loadXml() {
load();
});
$(document).on('pagebeforecreate orientationchange', Application.updateIcons);
function load() {
$.ajax({
type: "GET",
url: "schooldata.xml",
dataType: "xml",
success: function (xml) {
var regionName;
var schoolName;
var schoolDescription;
var liHtml;
$(xml).find("REGION").each(function (index, Region) {
liHtml = "";
$(Region).find("SCHOOL").each(function (index, School) {
regionName = $(Region).find("REGIONNAME").text();
schoolName = $(School).find("NAME").text();
schoolDescription = $(School).find("DESCRIPTION").text();
liHtml +=
"<li>" +
schoolName +
"<br>" +
schoolDescription +
"</li>"
})
$('#schoolcontainer').append
(
"<div data-role='collapsible' data-theme='b'>" +
"<h3>" + regionName + "</h3>" +
"<ul data-role='listview' data-inset='false'>" +
liHtml +
"</ul>" +
"</div>"
)
});
$('#schoolcontainer').collapsibleset("refresh");
}
});
}
$(document).one('deviceready', Application.initApplication);

Problems with asp HttpResponse on a download from Android

I have the following problem:
I develop a .zip file download with .pdf selected inside a function on c#.
The function creates the .zip file on a temp folder on the server and the HTTP Response return this file.
This function works great when is called from windows, and IOS. But when I call this function on Android it never downloads the file.
On the server I see that the function create the .zip file again and again when it's called from android browser (chrome, dolphin...) and it's never returned.
The strange thing is that I could run it well when I selected 90 .pdf files (although the function is called twice for no reason), but when I select 140 (or more) the issue happens again.
Here is the code:
**string dirName = Utiles.GetNewName();
zipName += ".ZIP\"";
string urlRet = _mSTempPath + #"\" + dirName + ".ZIP";
string urlDelete = _mSTempPath + #"\" + dirName;
System.IO.Stream iStream = null;
// Total bytes to read:
long dataToRead;
//HttpResponse resp = _page.Response;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
using (ZipFile zip = new ZipFile())
{
foreach (string url in filesURLs)
{
zip.AddFile(url,"");
}
zip.Save(_mSTempPath + #"\" + dirName + ".ZIP");
}
// Open the file.
iStream = new System.IO.FileStream(urlRet, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + zipName);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("content-length", dataToRead.ToString());
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.TransmitFile(urlRet);
HttpContext.Current.Response.Flush();**
Please, I will be very grateful if anyone can help.
Thanks again!

How to access share folder in windows through android and read files

I need to connect from my Android phone to a Windows PC share and access files. I saw some sample apps in Android market that access share folders using smb/samba. But I have no idea about how to create an app like that. Thanks a lot.
You need to get JCIFS and use SmbFile class to interact with files over the network,
http://lists.samba.org/archive/jcifs/2007-September/007465.html
that is a quick example of how to list files, of coarse you need internet permission on. So Far though everytime I try to call SmbFile.listFiles(); I get an UnknownHostException, However others seam to be able to do it with no problem, this might work for you, try it!
Google has released a simple, free Samba client. It is on github so you can have a look and use whatever you need out of that: https://github.com/google/samba-documents-provider
The other option is JCIFS: https://jcifs.samba.org/. There you can find the library and examples on how to use it.
I used JCIFS. Here is an example from my code which reads files from a folder in a windows share:
TreeMap<Date, String> filesInfo = new TreeMap<Date, String>();
NtlmPasswordAuthentication auth = null;
UniAddress dc = UniAddress.getByName(m_dataHostIp);
if(m_userName.length() > 0 && m_password.length() > 0)
auth = new NtlmPasswordAuthentication(m_domain + ";" + m_userName + ":" + m_password);
else
auth = new NtlmPasswordAuthentication(m_domain, null, null);
SmbSession.logon(dc, auth);
SmbFile file = new SmbFile(m_foldername, auth);
SmbFile[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
{
String fileName = files[i].getName();
String extension=fileName.substring(fileName.lastIndexOf(".") + 1);
logInfo(TAG + " " + fileName + "\n");
Date fileTime = new Date(files[i].getDate());
if(m_fileExtension.contains(extension))
filesInfo.put(fileTime, fileName);
}
The code posted above works. It allows you to connect to the share, authenticate (username and password that you know) and get the list of the files. At the root of jcif file access is the SmbFile which has all the info you need to access files in the share. All you need is in your build.gradle for the app add:
dependencies {
implementation files('libs/jcifs-1.3.19.jar')
}
and in your implementation file:
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import static jcifs.smb.SmbFile.FILE_SHARE_DELETE;
import static jcifs.smb.SmbFile.FILE_SHARE_READ;
import static jcifs.smb.SmbFile.FILE_SHARE_WRITE;

Categories

Resources