using SQLite in windows phone 8.1 c# - sqlite

there is my problem;
I need to use sqlite in my wp8.1 app, i have install the nugets, extensions etc.
I have to save a JSON string into my db.
I know that i have to create a class that i will use to create the table of my sqlite.
Next to that, i know that i have to do a create fct for the table, a insert fct to put my Json string into my table, and a read to get it back and to use that.
I have find tutorial etc and each time i am trying something, it does not work.
I am not a pro in c# and in windows phone 8.1, i am not pro in database. I am in front of a big wall since 3days.
Does anyone can help me plz?
Thank you verry much.

I have create a Json class for my table;
Here is the code:
namespace PhoneApp5.Model
{
public class Json
{
[PrimaryKey]
public string Key { get; set; } //Key for my table
public string String { get; set; } //value String Json for my table
}
}
And then i create some fontion to use the table:
private async void CreateTable() // create my table
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.CreateTableAsync<Json>();
}
public async void InsertJson(Json json) // insert my Json into my table
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.InsertAsync(json);
}
public async Task<Json> GetJson(string Key) // read my Json string from table
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
var query = conn.Table<Json>().Where(x => x.Key == Key);
var result = await query.ToListAsync();
return result; // result here is not working because of convertion of System.Connection.Generic.List<PhoneApp5.Model.Json> into PhoneApp5.Model.Json
}
public async void UpdatePost(Json json) // fct update
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.UpdateAsync(json);
}
public async void DeletePost(Json json) // fct delete
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.DeleteAsync(json);
}
Then, i don't know what to do.
Thx you for helping

Related

SQLite Xamarin.forms dosn't return the saved Data

I stuck with Xamarin.Forms SQLite.
i use this NuGet package : sqlite-net-pcl
My SQLITE Tables
I want to save the Data from my Table to a Variable with this following code
SQLiteConnection myconnection = new SQLiteConnection(Constants.DatabasePath);
SQLiteCommand cmd = new SQLiteCommand(myconnection);
myconnection.CreateTable<Modul>();
var Mods = myconnection.Query<Modul>("SELECT * FROM Modul");
Mods returns with = Count=0;
But i have saved Data. Click here
My modul class:
MoulID has Primary Key on Top [Primarykey]...
public int ModulID { get; set; }
public string Modul_Name { get; set; }
I will include my existing Database from Here
with this class
public class{
public const string DatabaseFilename = "VocalDB.db";
public static string DatabasePath
{
get
{
var basePath = "D:/C#-Projets/Vocabul/Vocabul/Vocabul/DataBase/";
return Path.Combine(basePath, DatabaseFilename);
}
}
}
In your code you create the table then you execute the query... I think the table is empty after you have created it.
myconnection.CreateTable<Modul>();
var Mods = myconnection.Query<Modul>("SELECT * FROM Modul");

How to use Firebase Query for data with anonymous keys

I have the following database data which I intend to display on a ListView with FirebaseListAdapter
My problem is creating a Query since the child elements after date are anonymous. Here is the query code
Query query = FirebaseDatabase.getInstance().getReference().child("Updates").child(refMail).child(day)
.orderByKey();
refMail and day are user email address and date respectively.
Here is also my Data Model Class
public class NotesDataModel {
private String Note;
private String uid;
private String time;
public NotesDataModel(){
}
public NotesDataModel(String Note, String uid, String time){
this.Note=Note;
this.uid=uid;
this.time=time;
}
public String getNote() {
return Note;
}
public void setNote(String note) {
Note = note;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}}
and finally the adapter initialization
FirebaseListOptions<NotesDataModel> options = new FirebaseListOptions.Builder<NotesDataModel>()
.setQuery(query, NotesDataModel.class)
.setLayout(R.layout.notes_cell_layout)
.build();
mAdapter = new FirebaseListAdapter<NotesDataModel>(options) {
#Override
protected void populateView(View view, NotesDataModel note, int position) { //some code }}; notesList.setAdapter(mAdapter);
Previous version worked like this
ref = FirebaseDatabase.getInstance().getReferenceFromUrl(FactoryDaftari.firebaseURL + "Updates/" + refMail + "/" + day);
And the Adapter initialization
mAdapter = new FirebaseListAdapter<NotesDataModel>(this, NotesDataModel.class, R.layout.notes_cell_layout, ref) {
#Override
protected void populateView(View view, NotesDataModel note, int position) { }};
You won't be able to make this query with the way your data is structured. It's common in NoSQL databases to make copies of data, structured for the purpose of specialized querying. So, if you want to query a list of notes, you'll need a structure where all the notes are children of the same parent, then make your query against that structure.
(Also, organizing your notes by a node with a date, like you have now, may not even be the best general structure in the first place.)

AWS SDK Dynamodb query operation on secondary index with encrypted data

I am trying to use DynamodbMapper to query data using gsi.
HashMap<String, AttributeValue> eav = new HashMap<>();
eav.put(":v1", new AttributeValue().withS(employee.getDepartment()));
eav.put(":v2", new AttributeValue().withS(employee.getContactId()));
DynamoDBQueryExpression<Employee> queryExpression =
new DynamoDBQueryExpression()
.withIndexName("DepartmentContactId-index")
.withKeyConditionExpression("Department = :v1 and contactId = :v2")
.withExpressionAttributeValues(eav)
.withConsistentRead(false);
List<Employee> items =
dynamoDBMapper.query(Employee.class, queryExpression);
I am getting bad signature exception.
PS: one of the field(column) in Employee table in dynamodb is encrypted using AWSKMS. I have configured the same KMS key in dynamodb mapper but still getting the same issue. Any pointers?
Mapper class -->
package com.test.model;
import com.amazonaws.services.dynamodbv2.datamodeling.*;
importcom.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt;
import static com.test.util.Constants.*;
#DynamoDBTable(tableName = "Employee")
public class Employee {
private String id;
private String department;
private String contactId;
private RulesData rulesData;
// Partition Key
#DynamoDBHashKey(attributeName = ID)
#DynamoDBAutoGeneratedKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DoNotEncrypt
#DynamoDBRangeKey(attributeName = DEPARTMENT)
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
#DoNotEncrypt
#DynamoDBAttribute(attributeName = CONTACT_ID)
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
#DynamoDBAttribute(attributeName = DATA)
public RulesData getRulesData() {
return rulesData;
}
public void setRulesData(RulesData rulesData) {
this.rulesData = rulesData;
}
}
If you set the projection type of the global secondary index(GSI) to be other than ALL, then the signature attribute will not be in the GSI .
Thus, if you require only unencrypted fields from your query on the GSI, use a new DynamoDBMapper without an AttributeEncryptor.
If you require encrypted fields too, set the projection type of the GSI to be ALL.

VS2008 Crystal Reports Database Connection from Web.config

I have an ASP.NET application I'm developing. In it is a CR report. When I first wrote the report, I had it hard coded to point to my development server (using MSSQL with Windows integrated login). So, when I moved my app to the production server, it of course failed.
I have been searching for an answer on how to connect it to DB listed in the Web.config, but haven't had any luck.
I saw one suggestion that I create a dataset in my project and tie in to that, but now it seems I can't use a parameter to filter the records.
I did see one other suggestion on how you can change the DB source on the fly, but that was designed for those who want to change the DB in mid session, rather than dependent on the machine, and seemed overkill.
Does anyone have a nice simple solution? I have been working on this problem for way too long and feel that I'm about to shoot my computer (that will teach it a lesson). :-(
public static class ReportDocumentExtensions
{
public static void SetConnectionInfo(this ReportDocument report, ReportContextArgs context)
{
SetConnectionInfo(report, context.UserId, context.Password, context.ServerName, context.DatabaseName);
}
public static void SetConnectionInfo(this ReportDocument report, string userId, string password, string serverName, string databaseName)
{
foreach (Table oTable in report.Database.Tables)
{
TableLogOnInfo oInfo = oTable.LogOnInfo;
ConnectionInfo oConnection = oTable.LogOnInfo.ConnectionInfo;
oConnection.UserID = userId;
oConnection.Password = password;
oConnection.ServerName = serverName;
oConnection.DatabaseName = databaseName;
oTable.ApplyLogOnInfo(oInfo);
}
}
}
public class ReportContextArgs
{
private string _userId;
private string _password;
private string _serverName;
private string _databaseName;
public string ServerName
{
get { return _serverName; }
set { _serverName = value; }
}
public string UserId
{
get { return _userId; }
set { _userId = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
public string DatabaseName
{
get { return _databaseName; }
set { _databaseName = value; }
}
}

Unit testing Raven and ASP.NET Membership

I'm starting a web app that will be using asp.net membership services (with a sql server backend) to look after users and RavenDb for everything else.
I'm new to unit testing and would appreciate it if I can run past you what I've got so far with one example method.
This is HelixManager
public class HelixManager:IDisposable
{
private readonly IMembershipProvider _membership;
private readonly IRepository _repos;
public HelixManager()
{
_membership = new AspNetMembershipProvider();
_repos = new RavenRepository();
}
public HelixManager(IMembershipProvider membershipProvider, IRepository repos)
{
_membership = membershipProvider;
_repos = repos;
}
public User CreateAdmin(User newUser, string password)
{
if (String.IsNullOrEmpty(newUser.Email)) throw new ArgumentException("Email must be supplied");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Password must be supplied");
var memberId = _membership.CreateUser(newUser, password);
if (memberId != null)
{
_membership.AddToRole(newUser, "Admin");
newUser.Type = UserType.Admin;
newUser.MemberId = memberId;
_repos.Store<User>(newUser);
}
return newUser;
}
This is IMembershipProvider
public interface IMembershipProvider
{
string CreateUser(User newUser, string password);
void AddToRole(User user, string rolename);
}
and the implementation AspNetMembershipProvider
public class AspNetMembershipProvider : IMembershipProvider
{
public string CreateUser(User newUser, string password)
{
MembershipCreateStatus status;
MembershipUser memUser = System.Web.Security.Membership.CreateUser(newUser.Email, password, newUser.Email, "", "", true, out status);
return memUser.ProviderUserKey.ToString();
}
public void AddToRole(User user, string role)
{
Roles.AddUserToRole(user.Email, role);
}
}
This is IRepository
public interface IRepository
{
T Store<T>(T item);
}
and it's implementation
public class RavenRepository : IRepository
{
private readonly DocumentStore _store;
public RavenRepository()
{
_store = new DocumentStore { DefaultDatabase = "Helix", Url = "http://localhost:8080" };
_store.Initialize();
}
public T Store<T>(T item)
{
using (var session = _store.OpenSession())
{
session.Store(item);
session.SaveChanges();
}
return item;
}
}
In my test project, I have created fake implementations of both of these:
FakeMembershipProvider:
class FakeMembershipProvider : IMembershipProvider
{
public string CreateUser(User newUser, string password)
{
CreatedUser = true;
return newUser.Email == "email#example.com" ? Guid.NewGuid().ToString() : null;
}
public void AddToRole(User user, string rolename)
{
AddedToRole = true;
}
public bool AddedToRole;
public bool CreatedUser;
}
and FakeRepository:
public class FakeRepository : IRepository
{
public T Store<T>(T item)
{
StoreCalled = true;
return item;
}
public bool StoreCalled;
}
The tests are then approx as follows:
public class UserManagementTests
{
private readonly HelixManager _hm;
private readonly IMembershipProvider _fakeMembershipProvider;
private readonly IRepository _fakeRepository;
public UserManagementTests()
{
_fakeMembershipProvider = new FakeMembershipProvider();
_fakeRepository = new FakeRepository();
_hm = new HelixManager(_fakeMembershipProvider, _fakeRepository);
}
[TestMethod]
public void CreateAdminReturnsValidAdminUser()
{
var newUser = new User
{
AvatarName = "fred",
Email = "email#example.com",
Forename = "Fred",
Surname = "Jones"
};
_hm.CreateAdmin(newUser, "password");
Assert.IsNotNull(newUser.MemberId);
Assert.AreEqual(UserType.Admin, newUser.Type);
}
What am I asking is before I get any further down this line, is this the right way to be going about this? Or are there better ways of doing this?
I also plan to have an IntegrationTests project that will use a real db and a real RavenDb instance to test end to end.
Cheers,
Dave
I see nothing wrong with that approach. You could go the route of using a Mocking tool (Rhino Mocks, Moq, NSubstitute) to create your fakes instead of doing it by hand, but that is really a matter of personal preference and your personal comfort-level with the tools.
Your test is clearly structured, asserting based on state (which is a good thing), and your not trying to test too many things at once, which is a common mistake (even for those of us who have been doing this for a while).
If you haven't seen it yet, I can highly recommend Roy Osherove's Art of Unit Testing, which has a lot of very good information about unit testing, including things like keeping tests clean, how to deal with less-testable areas of code, etc.
I say keep truckin' :)
Your tests are look absolutely fine to me. Right approach (mocks) right way (AAA).
Go ahead :)
My problem is actually with this:
I'm starting a web app that will be
using asp.net membership services
(with a sql server backend) to look
after users and RavenDb for everything
else.
Why are you doing this?
It would be easier to make everything in RavenDB, and your unit testing issue would be as simple as new EmbeddableDocumentStore { RunInMemory = true }

Resources