Trying to establish sqlite connection results in null reference - c#

Xamarin forms newbie here, and I am trying to establish an SQLite connection so that I may interact with a created database in my application.
I get no flags on this in the IDE, but when I compile, I'm getting a null reference error! Specifically, my _SQLiteConnection var is null, and I think it may have something to do with not setting the path properly?
I've referenced a few guides on doing this online, and although a little dated, they go about setting this up in the same manner I am.
Heres some code:
UserDb.cs:
using PluralBuddy.Models;
using SQLite;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace PluralBuddy.Data
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class UserDB
{
private SQLiteConnection _SQLiteConnection;
public UserDB()
{
_SQLiteConnection = DependencyService.Get<ISQLiteInterface>().GetConnection();
_SQLiteConnection.CreateTable<User>();
}
ISQLiteInterface.cs:
using SQLite;
namespace PluralBuddy.Models
{
public interface ISQLiteInterface
{
SQLiteConnection GetConnection();
}
}
References:
https://code.tutsplus.com/tutorials/an-introduction-to-xamarinforms-and-sqlite--cms-23020
https://dzone.com/articles/register-and-login-using-sqlite-in-xamarinforms
As always, any help is appreciated!

So for anyone who stumbles across this post looking for an answer to a similar problem, make sure that you are initializing your database and giving it a path. Be very careful following guides as they will often leave out vital context, either on purpose or by mistake.
Here is what I did
in App.Xaml
using PluralBuddy.Data;
using PluralBuddy.Views;
using System;
using System.IO;
using Xamarin.Forms;
namespace PluralBuddy
{
public partial class App : Application
{
static UserDB userDB;
public static UserDB UserDB
{
get
{
if (userDB == null)
{
userDB = new UserDB(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "user.db3"));
}
return userDB;
}
}
UserDB.cs
namespace PluralBuddy.Data
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class UserDB
{
private readonly SQLiteConnection _SQLiteConnection;
public UserDB(string dbPath)
{
_SQLiteConnection = new SQLiteConnection(dbPath);
_SQLiteConnection.CreateTable<User>();
}
and just in case anyone needs it, here is a more up to date guide from one of the same guys as referenced in the original post:
https://xmonkeys360.com/2019/07/10/register-login-and-update-using-sqlite-in-xamarin-forms/

Related

SolrNet in C# example

I am trying to write a simple c# program to just connect to my Solr instance. I have downloaded the SolrNet library and made reference to SolrNet.dll in my project. I am following some of the examples online but have been getting the error "ServiceLocationProvider must be set" when the last line of my code is executed. Following is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using CommonServiceLocator;
using SolrNet;
using SolrNet.Attributes;
using SolrNet.Impl;
using SolrNet.Impl.DocumentPropertyVisitors;
using SolrNet.Impl.FacetQuerySerializers;
using SolrNet.Impl.FieldParsers;
using SolrNet.Impl.FieldSerializers;
using SolrNet.Impl.QuerySerializers;
using SolrNet.Impl.ResponseParsers;
using SolrNet.Mapping;
using SolrNet.Mapping.Validation;
using SolrNet.Mapping.Validation.Rules;
using SolrNet.Schema;
using SolrNet.Utils;
namespace WebApplication1
{
public class Post
{
[SolrField("id")]
public string id { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var connection = new SolrConnection("http://localhost:8983/solr/test");
Startup.Init<Post>(connection.ServerURL);
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Post>>();
}
}
}
Can someone tell me what am I missing?
Thank You

How to access GetSystemService(AudioService) in the UI layer

I am developing android App in Xamarin. I want to create an interface and its implementing class in the UI layer. As you see in the below code,
I am getting an error when ever, I use
this.GetSystemService(AudioService);
it is never recognized.
please have a look at the imports below. please let me know how to get it working.
code:
public class ImplClass :
InterfaceFile
{
public bool IsAllowed(Context ctx)
{
AudioManager audioMgr =
(AudioManager)this.GetSystemService(AudioService);
}
}
import:
using System;
using System.Runtime.Remoting.Contexts;
using Android.Media;
using MvvmCross.Platform;
using Android.Content.PM;
You can use the "Application Context".
Example:
public class ImplClass : InterfaceFile
{
public bool IsAllowed(Context ctx)
{
AudioManager audioMgr = (AudioManager)Application.Context.GetSystemService(AudioService);
}
}
I am using this and it works.
global::Android.App.Application.Context.GetSystemService

Can anyone assist with "The name 'posttype' does not exist in the current context" error

.......So, I have the below class which I have created as part of my automated test pack, but I am getting an error against the 'ListPostsPage.GoTo(PostType.Page)' line of code, advising that: 'the name PostType does not exist in the current context'. The code for this class is below:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordpressTests
{
[TestClass]
public class PageTests
{
[TestInitialize]
public void Init()
{
Driver.Initialise();
}
[TestMethod]
public void CanEditAPage()
{
LoginPage.GoTo();
LoginPage.LoginAs("XXXXXX").WithPassword("XXXXXX").Login();
**ListPostsPage.GoTo(PostType.Page);**
ListPostsPage.SelectPost("Sample Page");
Assert.IsTrue(NewPostPage.IsInEditMode(), "Wasn't in edit mode");
Assert.AreEqual("Sample Page", NewPostPage.Title, "Title did not match");
}
[TestCleanup]
public void Cleanup()
{
Driver.Close();
}
}
}
Just for reference, the code for the ListPostsPage class is as follows:
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordpressTests
{
public class ListPostsPage
{
public static void GoTo(PostType postType)
{
switch (postType)
{
case PostType.Page:
Driver.Instance.FindElement(By.Id("menu-pages")).Click();
Driver.Instance.FindElement(By.LinkText("All Pages")).Click();
break;
}
}
public static void SelectPost(string title)
{
var postLink = Driver.Instance.FindElement(By.LinkText("Sample Page"));
postLink.Click();
}
public enum PostType
{
Page
}
}
}
Does anyone have any ideas as to what the issue may be? Please bear in mind I am fairly new to this, so please be nice! :-)
Any help would be much appreciated.
Cheers
Andy
PostType is an enum member of ListPostsPage but you're trying to access it as if it were a static class.
You should do this:
ListPostsPage.GoTo(ListPostsPage.PostType.Page);

Custom Class Inside a WCF Service Object

A bit rusty here with regards to WCF Services.
I have a custom class named cSecurity.cs which does some custom functions.
I want to use this custom class inside my Service:
This is the App.svc.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace AppServices
{
public class App : IApp
{
public cSecurity _csec;
public string GetItems(int agentID, string agentName)
{
// Need to use some functions from the cSecurity class here???
return _csec.getItems();
}
}
}
This is the cSecurity.cs class:
using System.Collections;
using System.Configuration;
using System.Net;
namespace AppServices
{
public class cSecurity
{
// Some functions defined here....
public string getItems(){
return string.Empty;
}
}
}
But I am getting an error on the line:
public cSecurity _csec;
"The type or namespace name 'cSecurity' could not be found."
This seems pretty trivial but I seem to be lost here.
Appreciate any insight. Thanks.
For some reason, the solution for this was for me to close and restart VS. Not sure what caused the class for it to be not referenced by VS.

The name 'ninja' does not exist in the current context

With the below code I get thee following error:
NinjaSteps.cs(16,13): error CS0103: The name 'ninja' does not exist in the current context
The command line I use to compile is:
csc /target:library /reference:C:\Ruby193\lib\ruby\gems\1.9.1\gems\
cuke4nuke-0.4.0\dotnet\Cuke4Nuke.Framework.dll /reference:C:\Fitnesse\FitNesseRo
ot\jediwhale-fitsharp-a78d820\binary\tools\nunit\framework\nunit.framework.dll /
reference:C:\Users\Rahul\Documents\Visual~1\Projects\ConsoleApplication3\Console
Application3\Ninja.dll NinjaSteps.cs
The code I am trying to compile is from a tutorial on Cucumber automation technology:
NinjaSteps.cs:
http://cuke4ninja.com/sec_ninja_survival_net.html
using System;
using System.Collections.Generic;
using System.Text;
using Cuke4Nuke.Framework;
using NUnit.Framework;
using NinjaSurvivalRate;
namespace ConsoleApplication3
{
class NinjaSteps
{ [Given(#"^the ninja has a ([a-z]*) level black-belt$")]
public void TheNinjaHasABlackBelt(String level)
{ ninja = new Ninja(level);
}
[When(#"^attacked by [a\s]*(.*)$")]
public void AttackedBy(String opponent)
{
actions = ninja.AttackedBy(opponent);
}
[Then("^the ninja should (.*)$")]
public void TheNinjaShould(String action)
{
Assert.IsTrue(actions.Contains(action));
}
}
}
Ninja.cs is below, compiled to Ninja.dll:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace NinjaSurvivalRate
{
public class Ninja
{
public Ninja(String beltLevel)
{
}
public List<String> AttackedBy(String opponent)
{
if ("Chuck Norris" == opponent)
return new List<string>(
new String[] { "run for his life" });
else
return new List<string>(
new String[] { "engage the opponent" });
}
}
}
Answers and feedback will be appreciated. Going through similar threads, I found that the resolution depended on a case by case basis and their was no consistent root cause, and felt I had to detail exact code details to get an understanding of the cause. You time and help will be greatly appreciated. Thanks.
You haven't defined the variable ninja. You need:
var ninja = new Ninja(level);
Do the same for actions.
EDIT:
Actually both the variables are supposed to be fields/properties in the class itself, if I understand your intentions correctly.
The tutorial is not telling you the whole history. If you go to the source code you will see that there is actually a field ninja declared that is initialized in the method TheNinjaHasABlackBelt (that you already have).

Categories