How to Get GPS base on Wifi using Xamarin - xamarin.android

This code base on the link below:
http://docs.xamarin.com/guides/android/platform_features/maps_and_location/part_3_-_location_services
I could not get any Lat/Lon ( Gps/Wifi)
The code is below :
I have added:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
&lt:uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Android.Locations
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
//-- add these
using Android.Locations;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Linq;
using System.Xml;
namespace GPSWifi
{
[Activity (Label = "GPSWifi", MainLauncher = true)]
public class Activity1 : Activity
{
int count = 1;
private LocationManager _locMgr;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
InitializeLocationManager();
}
private void InitializeLocationManager()
{
_locMgr = (LocationManager) GetSystemService(LocationService);
var locationCriteria = new Criteria();
locationCriteria.Accuracy = Accuracy.NoRequirement;
locationCriteria.PowerRequirement = Power.NoRequirement;
string locationProvider = _locMgr.GetBestProvider(locationCriteria, true);
_locMgr.RequestLocationUpdates (locationProvider, 2000, 1, this);
}
protected override void OnResume ()
{
base.OnResume ();
_locMgr.RequestLocationUpdates (LocationManager.GpsProvider, 2000, 1, this);
}
protected override void OnPause ()
{
base.OnPause ();
_locMgr.RemoveUpdates (this);
}
public void OnProviderDisabled(string provider) {}
public void OnProviderEnabled(string provider) {}
public void OnLocationChanged (Location location)
{
var locationText = FindViewById<TextView>(Resource.Id.locationTextView);
locationText.Text = String.Format ("Latitude = {0}, Longitude = {1}",
location.Latitude, location.Longitude);
}
}
}
Your help is much appreciated.
-- Error Message :
C:\Program Files
(x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(2,2):
Error MSB4018: The "Aapt" task failed unexpectedly.
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Xamarin.Android.Tasks.BuildToolsUtils.GetBuildToolsPath(String
androidSdkDirectory)
at Xamarin.Android.Tasks.Aapt.GenerateFullPathToTool()
at Microsoft.Build.Utilities.ToolTask.ComputePathToTool()
at Microsoft.Build.Utilities.ToolTask.Execute()
at Xamarin.Android.Tasks.Aapt.Execute()
at
Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at
Microsoft.Build.BackEnd.TaskBuilder.d__20.MoveNext()
(MSB4018) (GPSWifi)

This error: The "Aapt" task failed unexpectedly. has just started occurring recently - I think it's to do with the very latest sdk's from Android/Google - I think they've moved a file location.
Check other questions like Xamarin Studio 2 - latest stable update - Error executing task Aapt: The source sequence is empty
Then check with Xamarin support - they'll issue an update to fix this.

Related

Show ProgressBar programattically while user logging on

I found this class at Centering ProgressBar Programmatically in Android which would display a progressbar programmatically, problem is it's an Xamarin Android Studio example and I'm trying to convert it to Xamarin for Visual Studio 2017. This is the code that I have successfully converted with those lines that I can't seem to find a Xamarin VS 2017 equivalent for.
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace OML_Android
{
class ProgressBarHandler
{
private ProgressBar mProgressBar;
private Context mContext;
public ProgressBarHandler(Context context)
{
mContext = context;
ViewGroup layout = (ViewGroup)((Activity)context).FindViewById(Android.Resource.Id.Content).RootView;
mProgressBar = new ProgressBar(context, null, Android.Resource.Attribute.ProgressBarStyleLarge);
// there is no setIndeterminate method for progressbar
mProgressBar.setIndeterminate(true);
// I cannot find an equivilent for LayoutParams
RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
RelativeLayout rl = new RelativeLayout(context);
// No equivalent for Gravity.CENTER
rl.SetGravity(Gravity.CENTER);
rl.AddView(mProgressBar);
layout.AddView(rl, params);
hide();
}
public void show()
{
mProgressBar.Visibility = Android.Views.ViewStates.Visible;
}
public void hide()
{
mProgressBar.Visibility = Android.Views.ViewStates.Invisible;
}
}
}
Once I have this converted and working I want it to overlay my logon view until the view finishes processing.
I help you transform Java code to C#, there is running GIF.
There is code.
class ProgressBarHandler
{
private ProgressBar mProgressBar;
private Context mContext;
public ProgressBarHandler(Context context)
{
mContext = context;
ViewGroup layout = (ViewGroup)((Activity)context).FindViewById(Android.Resource.Id.Content).RootView;
mProgressBar = new ProgressBar(context, null, Android.Resource.Attribute.ProgressBarStyleLarge);
// there is no setIndeterminate method for progressbar
// mProgressBar.SetIndeterminate(true);
mProgressBar.Indeterminate = true;
// I cannot find an equivilent for LayoutParams
RelativeLayout.LayoutParams layoutparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
RelativeLayout rl = new RelativeLayout(context);
// No equivalent for Gravity.CENTER
rl.SetGravity(GravityFlags.Center );
rl.AddView(mProgressBar);
layout.AddView(rl, layoutparams);
hide();
}
public void show()
{
mProgressBar.Visibility = Android.Views.ViewStates.Visible;
}
public void hide()
{
mProgressBar.Visibility = Android.Views.ViewStates.Invisible;
}
}
You can use it directly like following code in Activity.
var progress= new ProgressBarHandler(this);
progress.show();

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.

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();

Access violation when streaming video with emgu opencv

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Emgu.CV;
using Emgu.CV.Structure;
namespace CrackleTest
{
public static class Controller
{
public static Capture capture = new Capture();
public static VideoWriter CaptureOutput;
public static void Init()
{
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 1920);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 1080);
CaptureOutput = new VideoWriter
(
"output.avi",
-1, //CvInvoke.CV_FOURCC("W","M","V","1"),
30, //fps
(int)capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH),
(int)capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT),
true
);
capture.ImageGrabbed += SaveFrame;
capture.Start();
}
public static void Stop()
{
capture.Stop();
CaptureOutput.Dispose();
}
public static void SaveFrame(Object sender, EventArgs e)
{
Image<Bgr, Byte> video = capture.RetrieveBgrFrame();
CaptureOutput.WriteFrame(video);
}
}
}
When I call the stop function I get an error message
An unhandled exception of type 'System.AccessViolationException'
occurred in Emgu.CV.dll
Additional information: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
I'm not sure what the best practices are for streaming video from usb webcam in opencv.

CK30: After using BarcodeReader() my keyboard stops working

I`m developing for a Intermec handheld device CK30 with a 2D reader in C# compact framework 2.0 (windows mobile 6.1).
Everytime I use barcode mey keyboard stops working. Any ideas why?
Heres the code. The first section is a class that configures the barcode reader. The second section is a form that uses the barcode reader to fill a textbox.
After reading something with the barcode reader the keyboard stops working...
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Intermec.DataCollection;
namespace BarCodeReaderTest
{
class LeitorCodigoDeBarras
{
public BarcodeReader LerCodigoDeBarras()
{
try
{
BarcodeReader meuLeitor = new BarcodeReader("default", 4096);
meuLeitor.ScannerEnable = true;
meuLeitor.ThreadedRead(true);
return meuLeitor;
}
catch (BarcodeReaderException bx)
{
MessageBox.Show("Não foi possível inicializar o leitor de código de barras. Contate seu supervisor. \n" + bx.Message);
return null;
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Intermec.DataCollection;
namespace BarCodeReaderTest
{
public partial class Form1 : Form
{
public BarcodeReader leitor;
public Form1()
{
InitializeComponent();
LeitorCodigoDeBarras classeLeitor = new LeitorCodigoDeBarras();
leitor = classeLeitor.LerCodigoDeBarras();
leitor.BarcodeRead += new BarcodeReadEventHandler(this.eventoLeitorCodigoDeBarras);
}
void eventoLeitorCodigoDeBarras(object sender, BarcodeReadEventArgs e)
{
tbCodLido.Text = e.strDataBuffer;
}
}
}
OK, I now relaized that you are using the BarcodeReader within a separate class.
Please try the follwing, standard, example (one listbox and one button in form):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Intermec.DataCollection;
namespace BarcodeReader
{
public partial class Form1 : Form
{
private Intermec.DataCollection.BarcodeReader bcr;
public Form1()
{
InitializeComponent();
bcr = new Intermec.DataCollection.BarcodeReader();
bcr.BarcodeRead += new BarcodeReadEventHandler(bcr_BarcodeRead);
bcr.ThreadedRead(true);
}
void bcr_BarcodeRead(object sender, BarcodeReadEventArgs bre)
{
this.listBox1.Items.Add(bre.strDataBuffer);
}
}
private void btnExit_Click(object sender, EventArgs e)
{
if (bcr !=null)
{
bcr.Dispose();
}
Application.Exit();
}
}
If that works (see also the examples coming with the Intermec Datacollection resource kit), we can examine, why you construct does not work. I assume you have the latest DataCollection Resource Kit installed.

Resources