Available Wifi connections list by using list view in Xmamrin - xamarin.android

i just want to know that if it is possible to make listview for the available wifi connections by using xamarin.....And if it is possible then please help me out here...... step by step.

Yes, It is. took it from xamarin forum: https://forums.xamarin.com/discussion/27364/how-to-get-list-of-wifi-networks
using Android.Content;
using Android.Net.Wifi;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace NetworkLocation.Utility
{
public class Wifi
{
private Context context = null;
private static WifiManager wifi;
private WifiReceiver wifiReceiver;
public static List<string> WiFiNetworks;
public Wifi(Context ctx)
{
this.context = ctx;
}
public void GetWifiNetworks()
{
WiFiNetworks = new List<string>();
// Get a handle to the Wifi
wifi = (WifiManager)context.GetSystemService(Context.WifiService);
// Start a scan and register the Broadcast receiver to get the list of Wifi Networks
wifiReceiver = new WifiReceiver();
context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
wifi.StartScan();
}
class WifiReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IList<ScanResult> scanwifinetworks = wifi.ScanResults;
foreach(ScanResult wifinetwork in scanwifinetworks)
{
WiFiNetworks.Add(wifinetwork.Ssid);
}
}
}
}
}

Related

QAF: Implementation of Self healing(Healenium) in QAF

Am new to QAF and I need to implement self-healing in our test method using healenium. I have implemented it without QAF it's working fine. Please refer to the below code.
import com.epam.healenium.SelfHealingDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;
public class BaseTest {
static protected SelfHealingDriver driver;
#BeforeAll
static public void setUp() {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.setHeadless(false);
//declare delegate
WebDriver delegate = new ChromeDriver(options);
driver = SelfHealingDriver.create(delegate);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1200, 800));
}
#AfterAll
static public void afterAll() {
if (driver != null) {
driver.quit();
}
}
}
I just want to wrap this self-healing driver with a QAF web driver like above.
QAF discourage to use static class variable for driver. The code provided in question will not work for parallel execution. Driver management is taken care by qaf with thread safety and with different behavior that can be set using property selenium.singletone.
You can try following way when you want SelfHealingDriver:
public class SampleTest extends WebDriverTestCase {
#Test
public void yourTestCase(){
SelfHealingDriver driver = SelfHealingDriver.create(getDriver());
//your code goes below
}
}
SelfHealingDriver proxies actual driver. You can achieve the self heal functionality without driver proxy with listener for findelement/findChildelement. Driver listener should work without proxing driver. For example:
public class WDListener extends QAFWebDriverCommandAdapter {
private static final Map<String, Object> byToString = JSONUtil.toMap(
"{'ByCssSelector':'css selector','ByClassName':'class name','ByXPath':'xpath','ByPartialLinkText':'partial link text','ById':'id','ByLinkText':'link text','ByName':'name'}");
//this method will called when new driver object created
public void onInitialize(QAFExtendedWebDriver driver){
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1200, 800));
}
#Override
public void afterCommand(QAFExtendedWebDriver driver, CommandTracker commandTracker) {
if (DriverCommand.FIND_ELEMENT.equalsIgnoreCase(commandTracker.getCommand())
|| DriverCommand.FIND_ELEMENTS.equalsIgnoreCase(commandTracker.getCommand())
|| DriverCommand.FIND_CHILD_ELEMENT.equalsIgnoreCase(commandTracker.getCommand())
|| DriverCommand.FIND_CHILD_ELEMENTS.equalsIgnoreCase(commandTracker.getCommand())) {
Map<String, Object> parameters = commandTracker.getParameters();
if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {
By by = LocatorUtil
.getBy(String.format("%s=%s", parameters.get("using"), parameters.get("value")));
HealingServiceImpl healingServiceImpl = new HealingServiceImpl(new SelfHealingEngine(driver));
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
Object result = commandTracker.getResponce().getValue();
List<WebElement> webElements = List.class.isAssignableFrom(result.getClass())?(List<WebElement>) result:Collections.singletonList((WebElement)result)
healingServiceImpl.savePath(new PageAwareBy(driver.getTitle(),by),webElements);
}
}
}
#Override
public void onFailure(QAFExtendedWebDriver driver, CommandTracker commandTracker) {
// StackTraceElement[] stackTrace =
// commandTracker.getException().getStackTrace();
Map<String, Object> parameters = commandTracker.getParameters();
if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {
By by = LocatorUtil
.getBy(String.format("%s=%s", parameters.get("using"), parameters.get("value")));
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
HealingServiceImpl healingServiceImpl = new HealingServiceImpl(new SelfHealingEngine(driver));
Optional<By> healedBy = healingServiceImpl.healLocators(new PageAwareBy(driver.getTitle(),by), null, stackTrace) ;
if(healedBy.isPresent()) {
commandTracker.getParameters().putAll(toParams(healedBy.get()));
commandTracker.setRetry(true);
}
}
}
}

Unity app crashes when built for iOS with camera enabled

I have an app which uses zxing to scan qr codes in the app. However when I build the app with these scripts in the scene the app crashes on startup. I thought it was something in the Awake() or Start() but I've wrapped those methods in a try catch, and even then I'm not getting any errors, and it doesn't crash on android and in the editor.
I don't have access to a Mac, and am using Unity Cloud Build to build it.
I also don't know how to enable permissions, I thought I did when creating the .p12 file, but I've also found that there's an info.plist file that I have to request permissions with.
Prior research I found this Unity Question about adding items to the Xcode project but not only did including the xcodeapi give me errors, but the using statements didn't work.
There are two scripts
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class WebCamController : MonoBehaviour {
public int desiredWidth = 1280;
public int desiredHeight = 720;
public int desiredFPS = 60;
public RawImage output;
[HideInInspector]
public WebCamTexture webcamTexture;
void Start ()
{
webcamTexture = new WebCamTexture(desiredWidth, desiredHeight, desiredFPS);
output.texture = webcamTexture;
Play();
}
public void Play()
{
webcamTexture.Play();
}
public void Pause()
{
webcamTexture.Stop();
}
}
and
using UnityEngine;
using System.Collections;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
using System;
public class CodeScanner : MonoBehaviour {
private static CodeScanner _instance;
public static CodeScanner Instance
{
get
{
if(null == _instance)
{
Debug.Log("Code Scanner Instance not found");
}
return _instance;
}
}
[Header("References")]
public WebCamController wcc;
[Header("Properties")]
private BarcodeReader codeScanner;
private string lastScanned = "";
public delegate void Found(string text, string type);
public event Found OnCodeScanned;
private bool active;
public void Awake()
{
_instance = this;
}
void Start () {
codeScanner = new BarcodeReader();
StartCoroutine(ReadCode());
wcc.Play();
}
IEnumerator ReadCode()
{
while (active)
{
try
{
var data = codeScanner.Decode(wcc.webcamTexture.GetPixels32(), wcc.webcamTexture.width, wcc.webcamTexture.height);
if (data != null)
{
//if (data.Text != lastScanned)
//{
OnCodeScanned(data.Text, data.BarcodeFormat.ToString());
//}
lastScanned = data.Text;
}
}
catch(Exception e)
{
}
yield return new WaitForSeconds(1.0f);
}
}
public void Activate()
{
wcc.Play();
active = true;
StartCoroutine(ReadCode());
}
public void Stop()
{
active = false;
wcc.Pause();
}
}
My device is added properly to the .p12 certificate I can compile and run the program without these scripts in the scene.

Steps doesn't generate in Extent Report in specflow

I am generating an extent report in specflow, I have written the code and my test execute successfully and report generating but it displays only the feature name no steps name displayed in the report.
Please suggest me what mistake I am doing in the code.
I am attaching a screenshot of my generated report, When I go to report dashboard it displays the number of steps there.
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
using AventStack.ExtentReports.Reporter.Configuration;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace Extent_Report
{
[Binding]
[TestFixture]
class Hooks
{
public static ExtentReports extent;
public static ExtentHtmlReporter htmlReporter;
public static ExtentTest test;
// public static object Theme { get; private set; }
static Hooks()
{
if (extent == null)
{
BasicSetUp();
}
}
[BeforeScenario]
public static void Setup()
{
BasePage.Intitialize();
BasePage.Navigate();
test = extent.CreateTest(ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario]
public void TearDown()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
extent.AddTestRunnerLogs(errormessage);
test.Log(Status.Error, errormessage);
test.Fail(errormessage);
}
BasePage.Quit();
}
[OneTimeSetUp]
public static void BasicSetUp()
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
// string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
Console.WriteLine(" -----------Project Path--------------------------------------");
Console.WriteLine(projectPath);
string reportPath = projectPath + "Reports\\TestExecutionRunReport.html";
// Console.WriteLine("Report Path is " + reportPath);
htmlReporter = new ExtentHtmlReporter(reportPath);
htmlReporter.Configuration().Theme = Theme.Dark;
htmlReporter.Configuration().DocumentTitle = "SpecFlow Test Resport Document";
htmlReporter.Configuration().ReportName = "Feature Run Results";
extent = new ExtentReports();
extent.AttachReporter(htmlReporter);
//extent.LoadConfig(projectPath + "Extent-Config.xml");
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
}
}
}
Reference:
You need to use hook [After step] or [Before step] and add below content to it
test = test.info(ScenarioStepContext.Current.StepInfo.Text);
you can also manipulate and provide more information in it if required.

Start an Android activity in Xamarin Forms?

I am trying to view a hosted PDF file with the default Android pdf viewer in my App with the following code
var intent = new Intent(Intent.ActionView);
intent.SetDataAndType(Uri.Parse("http://sample/url.pdf"), "application/pdf");
intent.SetFlags(ActivityFlags.ClearTop);
Android.Content.Context.StartActivity(intent);
I have used this code in a Native project, so I know that it works within an Android activity. For Xamarin Forms, is there a way for me to start an Android activity from a content page, and vice versa?
You can use DependencyService to implement this function:
INativePages in PCL:
public interface INativePages
{
void StartActivityInAndroid();
}
Implement the interface in Xamarin.Android:
[assembly: Xamarin.Forms.Dependency(typeof(NativePages))]
namespace PivotView.Droid
{
public class NativePages : INativePages
{
public NativePages()
{
}
public void StartAc()
{
var intent = new Intent(Forms.Context, typeof(YourActivity));
Forms.Context.StartActivity(intent);
}
}
}
Start an Android Activity in PCL :
private void Button_Clicked(object sender, EventArgs e)
{
Xamarin.Forms.DependencyService.Register<INativePages>();
DependencyService.Get<INativePages>().StartAc();
}
Forms.Context is obsolete now.
The workaround is to instantiate the current context in Main activity class of Android project as under:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static Xamarin.Forms.Platform.Android.FormsAppCompatActivity Instance { get; private set; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
Instance = this;
}
And retrieve the local context in your NativePages StartAc() method as under:
public void StartAc()
{
var intent = new Intent(MainActivity.Instance, typeof(YourActivity));
MainActivity.Instance.StartActivity(intent);
}
Create an class for this function in an android project:
public class PdfLauncher : IPdfLauncher
{
public void LaunchPdf(string url)
{
//implementation
}
}
Create an interface in a portable project
public interface IPdfLauncher
{
void LaunchPdf(string url);
}
Add a property to your viewmodel so you can call the function from your portable project
public IPdfLauncher PdfLauncher {get;set;}
Add the interface to your viewmodel constructor and pass in an instance that you create in your android main activity. You can now call android code from your xforms commands and, if you ever add iOS or UWP you can simply implement that interface in those projects and pass them in at runtime. I use an injection framework from MVVM to automate creating these platform specific implementations, and I'd recommend you look into it if you find yourself doing these often.

Object reference not set to an instance of an object - Select statement Sqlite Xamarin iOS

I am fetching the values from sqlite database in my iOS application. I have written a Select statement like stringquery = "Select * from tablename" and executing it using
database.Query < table > (stringquery);
and assigning the values to the properties in a class. The class has properties with the same name that the columns has in the table in sqlite database.
as the above statement executes i am getting error Object reference not set to an instance of an object
Please suggest the solution this issue.
Thanks
It sounds like you are initializing the SQLite Database incorrectly. I've added code below that shows how to implement a SQLite Database in Xamarin.Forms.
This Xamarin.Forms app, contains a fully implemented SQLite Database:
https://github.com/brminnick/InvestmentDataSampleApp
ISQLite.cs
Create this file in the Xamarin.Forms PCL. It allows us to access the iOS and Android File Systems to create our Database Connection
using SQLite;
namespace SampleApp
{
public interface ISQLite
{
SQLiteAsyncConnection GetConnection();
}
}
SQLite_Android.cs
Create this file in the Android project. It returns the Android file path for our SQLite Database Connection.
using System.IO;
using SampleApp.Droid;
using SQLite;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_Android))]
namespace SampleApp.Droid
{
public class SQLite_Android : ISQLite
{
#region ISQLite implementation
public SQLiteAsyncConnection GetConnection()
{
var sqliteFilename = "DatabaseFileName.db3";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
// Return the database connection
return conn;
}
#endregion
}
}
SQLite_iOS.cs
Create this file in the iOS project. It returns the iOS file path for our SQLite Database Connection.
using System;
using System.IO;
using SQLite;
using Xamarin.Forms;
using SampleApp.iOS;
[assembly: Dependency(typeof(SQLite_iOS))]
namespace SampleApp.iOS
{
public class SQLite_iOS : ISQLite
{
#region ISQLite implementation
public SQLiteAsyncConnection GetConnection()
{
var sqliteFilename = "DatabaseFileName.db3";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
var path = Path.Combine(libraryPath, sqliteFilename);
var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
// Return the database connection
return conn;
}
#endregion
}
}
SampleModelDatabase.cs
Create this file in your Xamarin.Forms PCL
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using SQLite;
using Xamarin.Forms;
namespace SampleApp
{
public static class SampleModelDatabase
{
#region Constant Fields
static readonly SQLiteAsyncConnection _database = DependencyService.Get<ISQLite>().GetConnection();
#endregion
#region Fields
static bool _isInitialized;
#endregion
#region Methods
public static async Task<IList<SampleModel>> GetAllItemsAsync()
{
if (!_isInitialized)
await Initialize();
return await _database.Table<SampleModel>().ToListAsync();
}
public static async Task<int> SaveItemAsync(SampleModel model)
{
if (!_isInitialized)
await Initialize();
return await _database.InsertOrReplaceAsync(model);
}
public static async Task<int> DeleteItemAsync(SampleModel model)
{
if (!_isInitialized)
await Initialize();
return await _database.DeleteAsync(model);
}
public static async Task<int> GetNumberOfRowsAsync()
{
if (!_isInitialized)
await Initialize();
return await _database.Table<SampleModel>().CountAsync();
}
static async Task Initialize()
{
await _database.CreateTableAsync<SampleModel>();
_isInitialized = true;
}
#endregion
}
}
I encountered the same problem as you. I found out that the point is database connection, a process that takes time, hasn't completely finished at the moment I started my query. so the solution will be something like:
await Connectdb();
// now do your query
var treatment = _database.Query<ClassName>("SELECT * FROM [TableName] WHERE ...");
where the Connectdb() is a function that does:
DependencyService.Get<IDatabaseConnection>().DbConnection();

Resources