Object reference not set to an instance of an object - Select statement Sqlite Xamarin iOS - 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();

Related

How can we update and Upload content to Blob in Azure using C#

I am putting the question and also the answer hoping to benefit others. You need to install Azure.Storage.Blobs pacakage
See the code below
// A content uploader class
// install package Azure.Storage.Blobs
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace AnAzureFunctionApp
{
public class ContentUploader
{
public async Task UploadContentsToBlob(string azureStorageAccountConnectionString,
string storageContainerName, string blobFileName)
{
var blobServiceClient = new BlobServiceClient(azureStorageAccountConnectionString);
// Create the container and return a container client object
var containerClient = blobServiceClient.GetBlobContainerClient(storageContainerName);
await containerClient.CreateIfNotExistsAsync();
var blobClient = containerClient.GetBlockBlobClient(blobFileName);
await AddBlobContents(blobClient);
}
private async Task AddBlobContents(BlockBlobClient blobClient)
{
await using var memoryStream = new MemoryStream();
// Download the blob's contents if it exist and save it to a memory file
if (blobClient.Exists())
{
var blobDownloadInfo = await blobClient.DownloadAsync();
await blobDownloadInfo.Value.Content.CopyToAsync(memoryStream);
}
byte[] timeBytes = Encoding.UTF8.GetBytes("Process is Run at " + DateTime.Now + Environment.NewLine);
await memoryStream.WriteAsync(timeBytes, 0, timeBytes.Length);
memoryStream.Position = 0;
//Upload the contents
await blobClient.UploadAsync(memoryStream);
memoryStream.Close();
}
}
}

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.

Available Wifi connections list by using list view in Xmamrin

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

mvc-mini-profiler, entity framework gives: The space 'SSpace' has no associated collection

I'm trying to use the mvc-mini-profiler in my mvc application. I created a wrapper for my context and Castle Windsor creates the instance. However, I get the error "The space 'SSpace' has no associated collection". The edmx is in assembly A, DigidosEntities in assembly B and this is in assembly C. Any idea what can be the problem? I got the latest version of the profiler.
public interface IDataStore : IDisposable
{
int SaveChanges(int personId);
IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class;
}
public class ProfiledDigidosEntities : IDataStore, IDisposable
{
private DigidosEntities _context = null;
public ProfiledDigidosEntities()
{
var connectionString = ConfigurationManager.ConnectionStrings["DigidosEntities"].ConnectionString;
var connection = new EntityConnection(connectionString);
var conn = ProfiledDbConnection.Get(connection);
_context = ObjectContextUtils.CreateObjectContext<DigidosEntities>(conn); /* Error: The space 'SSpace' has no associated collection */
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
}
public int SaveChanges(int personId)
{
return _context.SaveChanges(personId);
}
public IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class
{
return _context.CreateObjectSet<TEntity>();
}
}
Ok, here was my problem: The profiler wants a workspace to make a new profiled connection, the workspace is created through this method (in ObjectContextUtils.cs):
static MetadataCache()
{
workspace = new System.Data.Metadata.Edm.MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { typeof(U).Assembly });
}
As you can see it will search in assembly of the type you want to create. Since in my case the type of the model was not in the same assembly, the creation of the workspace failed. Moving the DigidosEntities to the same assembly as the edmx fixed it.

Resources