How to update a specific value in a database item? - database

This is a todo list app and uses a database to use the CRUD functions. When the user does a specific action such as tap or swipe i want to mark the task as complete. I am a bit new to databases and am unsure on how to use update item to update the status of a task (completed or not completed).
Could i get a suggestion on what is the correct way to update the _isDone value without deleting a task from the database
Tried to search for other examples of to do list apps but they delete the completed task intead of marking it as completed
database code -
//This is the database
String _itemName;
String _dateCreated;
int _id;
bool _isDone;
TodoItem(this._itemName, this._dateCreated, [this._isDone]);
TodoItem.map(dynamic obj) {
this._itemName = obj["itemName"];
this._dateCreated = obj["dateCreated"];
this._id = obj["id"];
this._isDone = obj["isDone"];
}
String get itemName => _itemName;
String get dateCreated => _dateCreated;
int get id => _id;
bool get isDone => _isDone;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map["itemName"] = _itemName;
map["dateCreated"] = _dateCreated;
if (_id != null) {
map["id"] = _id;
}
return map;
}
TodoItem.fromMap(Map<String, dynamic> map) {
this._itemName = map["itemName"];
this._dateCreated = map["dateCreated"];
this._id = map["id"];
this._isDone = map["isDone"];
}
update item function -
Future<int> updateItem(TodoItem item) async {
var dbClient = await db;
return await dbClient.update("$tableName", item.toMap(),
where: "$columnId = ?", whereArgs: [item.id]);
}

please reference this document https://medium.com/flutter-community/using-sqlite-in-flutter-187c1a82e8b
In sqlite example below, update the whole record via a key, "id" here
updateClient(Client newClient) async {
final db = await database;
var res = await db.update("Client", newClient.toMap(),
where: "id = ?", whereArgs: [newClient.id]);
return res;
}
In your example, you update TodoItem and TodoItem include isDone field.
and your syntax is correct
another reference doc https://www.developerlibs.com/2018/07/flutter-sqlite-database-example.html
code snippet of this example
Future<bool> update(User user) async {
var dbClient = await db;
int res = await dbClient.update("User", user.toMap(),
where: "id = ?", whereArgs: <int>[user.id]);
return res > 0 ? true : false;
}
official document about use of sqlite https://flutter.dev/docs/cookbook/persistence/sqlite
code snippet of official document
Future<void> updateDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
// Update Fido's age.
await updateDog(Dog(
id: 0,
name: 'Fido',
age: 42,
));
You can build a Database Helper as the example and include your update function
import 'dart:async';
import 'dart:io' as io;
import 'package:flutter_database/database/model/user.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async {
if (_db != null) return _db;
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "main.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db, int version) async {
// When creating the db, create the table
await db.execute(
"CREATE TABLE User(id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT, dob TEXT)");
}
Future<int> saveUser(User user) async {
var dbClient = await db;
int res = await dbClient.insert("User", user.toMap());
return res;
}
Future<List<User>> getUser() async {
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM User');
List<User> employees = new List();
for (int i = 0; i < list.length; i++) {
var user =
new User(list[i]["firstname"], list[i]["lastname"], list[i]["dob"]);
user.setUserId(list[i]["id"]);
employees.add(user);
}
print(employees.length);
return employees;
}
Future<int> deleteUsers(User user) async {
var dbClient = await db;
int res =
await dbClient.rawDelete('DELETE FROM User WHERE id = ?', [user.id]);
return res;
}
Future<bool> update(User user) async {
var dbClient = await db;
int res = await dbClient.update("User", user.toMap(),
where: "id = ?", whereArgs: <int>[user.id]);
return res > 0 ? true : false;
}
}

Related

Unhandled Exception: LateInitializationError: Field '_db#26138511' has not been initialized

In my datbase I'm using the static late Database _db; to finalize the _db but as i had to use the late initializer here i'm getting this error. Also if i don't use the late initializer i get error where it tells me to use this initializer.
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: LateInitializationError: Field '_db#26138511' has not been initialized.
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart'; // for the use of datbase
import 'dart:async';
import 'package:path_provider/path_provider.dart'; // for the use of path
import 'dart:io'; // for the use of new directory
import 'package:path/path.dart'; // to use the join and make a path for our directory
import '../models/user.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper.internal();
factory DatabaseHelper() =>
_instance;
// here we'll create some final string for our table that we'll create in the db
final String tableUser = "userTable";
final String columnId = "id";
final String columnUserName = "username";
final String columnPassword = "password";
static late Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db =
await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
//get a location using the getDatabasesPath
Directory documentDirectory =
await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path,
"main.db");
//open database
var ourDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return ourDb;
}
// here we'll create the db, and table for our database
/*
id | username | password
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 | Rana | rana
2 | Riya | riya
*/
void _onCreate(Database db, int version) async {
await db.execute(
"CREATE TABLE $tableUser($columnId INTEGER PRIMERY KEY, $columnUserName TEXT, $columnPassword TEXT)"); // this is our dataase id that we created
}
// CREATE, READ, UPDATE, DELETE-----From DATABase
//insertion
Future<int> saveUser(User user) async {
var dbClient = await db;
int result =
await dbClient.insert("$tableUser", user.toMap()); // creating our table
return result;
}
/// get the users
Future<List> getAllUsers() async {
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $tableUser");
return result.toList(); // -- making the result to a list
}
/// get counted the id
Future<int?> getCount() async {
var dbClient = await db;
return Sqflite.firstIntValue(
await dbClient.rawQuery("SELECT COUNT(*) FROM $tableUser"),
);
}
/// get only one user from database
Future<User?> getUser(int id) async {
var dbClient = await db;
var result = await dbClient
.rawQuery("SELECT * FROM $tableUser WHERE $columnId = $id");
if (result.length == 0) return null;
return User.fromMap(result.first);
}
/// delete from the database
Future<int> deletUser(int id) async {
var dbClient = await db;
return await dbClient
.delete(tableUser, where: "$columnId = ?", whereArgs: [id]);
}
/// update the database
Future<int> updateUser(User user) async {
var dbClient = await db;
return await dbClient.update(tableUser, user.toMap(),
where: "$columnId = ?", whereArgs: [user.id]);
}
/// closeing the database
Future closeDatabase() async {
var dbClient = await db;
return dbClient.close();
}
}
Dart null-safety feature does not promote class fields when doing. refer to here
if (_db == null)
the solution would be to rewrite:
static late Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDb();
return _db;
}
to:
static Database? _database;
Future<Database> get db async => _db ??= await _initiateDatabase();
The ??= operator will check if _db is null and set it to the value of await _initiateDatabase()
if that is the case and then return the new value of _db, or return if it already has a value
and finally enforce the datatype on db initialisation, to avoid future problems
...
Future<Database> initDb() async {
...

How to create a single store in objectbox flutter?

Flutter database objectbox error - " Unsupported operation: Cannot create multiple Store instances for the same directory in the same isolate. Please use a single Store, close() the previous instance before opening another one or attach to it in another isolate ". I am using objectbox as my app database.How can I solve this problem. Here is my code -
// First File
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../objectbox.g.dart';
#Entity()
class MarkEvent {
int? id;
int habitId;
String dateTime;
MarkEvent({required this.dateTime, required this.habitId, this.id = 0});
}
class HabitDetailProvider with ChangeNotifier {
List<MarkEvent> marks = [];
Future<void> deleteMark(int id) async {
final index = marks.indexWhere((element) => element.id == id);
marks.removeAt(index);
var store = await openStore();
var box = store.box<MarkEvent>();
box.remove(id);
store.close();
// await DataBaseHelper.deleteEvent(id);
notifyListeners();
}
Future<void> addMark(MarkEvent mark) async {
marks.add(MarkEvent(dateTime: mark.dateTime, habitId: mark.habitId));
var store = await openStore();
var box = store.box<MarkEvent>();
box.put(mark);
store.close();
notifyListeners();
}
Future<void> fetchAndSetMarks() async {
var store = await openStore();
var box = store.box<MarkEvent>();
final markList = box.query().build().find();
store.close();
marks = markList
.map((e) => MarkEvent(dateTime: e.dateTime, habitId: e.habitId))
.toList();
notifyListeners();
}
}
// Another file
import 'package:flutter/material.dart';
import 'package:habit_app/objectbox.g.dart';
import '../model/habit_model.dart';
class HabitListNotifier with ChangeNotifier {
List<HabitModel> _habitList = [];
List<HabitModel> get Habit_List {
return [..._habitList];
}
Future<Store> get originalStore {
return openStore();
}
void addHabit(HabitModel habit) async {
HabitModel newHabit = HabitModel(
hour: habit.hour,
minutes: habit.minutes,
reminderHour: habit.reminderHour,
reminderMinute: habit.reminderMinute,
alarmId: habit.alarmId,
notificationText: habit.notificationText,
reason: habit.reason,
notificationId: habit.notificationId,
iconData: habit.iconData.toString(),
title: habit.title,
plan: habit.plan,
);
_habitList.add(newHabit);
var store = await originalStore;
var box = store.box<HabitModel>();
box.put(habit);
store.close();
notifyListeners();
}
void updateHabit(HabitModel newHabit) async {
final oldHabitIndex =
_habitList.indexWhere((habit) => habit.id == newHabit.id);
_habitList[oldHabitIndex] = newHabit;
var store = await originalStore;
var box = store.box<HabitModel>();
box.put(newHabit);
store.close();
notifyListeners();
}
Future<void> fetchAndSetHabits() async {
var store = await originalStore;
var box = store.box<HabitModel>();
var query = box.query().build();
_habitList = query.find();
store.close();
notifyListeners();
}
Future<void> deleteHabit(int id) async {
final existingHabit = _habitList.indexWhere((element) => element.id == id);
_habitList.removeAt(existingHabit);
var store = await originalStore;
var box = store.box<HabitModel>();
box.remove(id);
store.close();
notifyListeners();
}
}
// Another file
import 'package:flutter/material.dart';
import 'package:habit_app/providers/habit_provider.dart';
import 'package:provider/provider.dart';
import '../objectbox.g.dart';
class NoteModel {
int habitId;
int? id;
String dateTime;
String note;
NoteModel(
{required this.dateTime,
required this.habitId,
this.id = 0,
required this.note});
}
class Notes with ChangeNotifier {
List<NoteModel> notes = [];
List<NoteModel> get dupNoteList {
return notes;
}
Future<void> addNote(
NoteModel note, int habitId, BuildContext context) async {
notes.add(note);
var store = await Provider.of<HabitListNotifier>(context, listen: false)
.originalStore;
var box = store.box<NoteModel>();
box.put(note);
store.close();
fetchAndSetNotes(habitId);
notifyListeners();
}
Future<void> deleteNote(int id) async {
final index = notes.indexWhere((element) => element.id == id);
notes.removeAt(index);
var store = await openStore();
var box = store.box<NoteModel>();
box.remove(id);
store.close();
notifyListeners();
}
Future<void> updateNote(NoteModel newNote) async {
var store = await openStore();
var box = store.box<NoteModel>();
box.put(newNote);
store.close();
final oldNote = notes.indexWhere((habit) => habit.id == newNote.id);
notes[oldNote] = newNote;
notifyListeners();
}
Future<void> fetchAndSetNotes(int habitId) async {
var store = await openStore();
var box = store.box<NoteModel>();
var query = box.query().build();
final note = query.find();
store.close();
notes = note.where((notes) => notes.habitId == habitId).toList();
notifyListeners();
}
}
//Models file
import 'package:objectbox/objectbox.dart';
#Entity()
class NoteModel {
String habitId;
int? id;
String dateTime;
String note;
NoteModel({
required this.dateTime,
required this.habitId,
required this.note,
this.id = 0,
});
}
import 'dart:core';
import 'package:objectbox/objectbox.dart';
class ClockTime {
int? id;
int hour;
int minutes;
ClockTime(this.hour, this.minutes);
}
#Entity()
class HabitModel {
String title;
String reason;
String plan;
String iconData;
int? id;
int alarmId;
int notificationId;
String notificationText;
int hour;
int reminderHour;
int reminderMinute;
int minutes;
HabitModel({
required this.reason,
required this.notificationText,
required this.reminderHour,
required this.reminderMinute,
required this.notificationId,
required this.plan,
required this.alarmId,
required this.iconData,
required this.title,
this.id = 0,
required this.hour,
required this.minutes,
});
}

migrating from Azure Active Directory Graph Api to Microsoft Graph Api

I have an application I am signing in to using SSO office 365 to authenticate the user. I am also calling the azure active directory graph api to pull a list of all users in the organization. I want to stop using the azure active directory graph api (since it is being deprecated as of 2/2019) and move over to microsoft-graph api. If I use microsoft graph to pull users, will I also have to authenticate with diff way (not Azure)?
this is my current auth code in startup file:
public void ConfigureAuth(IAppBuilder app)
{
string strIssuers = ConfigurationManager.AppSettings["validIssuers"];
string[] validIssuers = strIssuers.Split(',');
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
ValidIssuers = validIssuers
}
});
}
in graph call:
public async Task<List<User>> GetAdUsers(string tid, string path = "users")
{
var identity = HttpContext.Current.User.Identity as ClaimsIdentity;
string email = identity?.Name;
var selectvalues = "";//(path.ToLower() == "users" ? "$select=*" : "");
List<User> tmpUsers;
string skipToken;
string skipTokenResult;
int skipTokenIndex;
string strAuth = "https://login.microsoftonline.com/" + tid + "/oauth2/v2.0/token";
var client = ConfigurationManager.AppSettings["ida:Audience"];
var secret = ConfigurationManager.AppSettings["clientSecret"];
string clientId = client;
string clientSecret = secret;
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null;
AuthenticationContext _authContext = new AuthenticationContext(strAuth);
Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential creds
= new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret);
result = await _authContext.AcquireTokenAsync("https://graph.microsoft.com", creds);
var _httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage Res = await _httpClient.GetAsync("https://graph.microsoft.com/v1.0/" + path + "?$top=999" + selectvalues);
if (Res.IsSuccessStatusCode)
{
string strJson = Res.Content.ReadAsStringAsync().Result;
JavaScriptSerializer json = new JavaScriptSerializer();
RootObject rootObj = json.Deserialize<RootObject>(strJson);
List<User> adUsers = rootObj.Value;
var parseRes = JObject.Parse(strJson);
bool stop = false;
while (!stop)
{
try
{
skipTokenResult = parseRes["#odata.nextLink"].Value<string>();
skipTokenIndex = skipTokenResult.IndexOf("skiptoken=");
skipToken = skipTokenResult.Substring(skipTokenIndex + 10, skipTokenResult.Length - skipTokenIndex - 10);
Res = await _httpClient.GetAsync("https://graph.microsoft.com/v1.0/" + path + "?$top=999&$skiptoken=" + skipToken + selectvalues);
if (Res.IsSuccessStatusCode)
{
strJson = Res.Content.ReadAsStringAsync().Result;
rootObj = json.Deserialize<RootObject>(strJson);
tmpUsers = rootObj.Value;
adUsers.AddRange(tmpUsers);
parseRes = JObject.Parse(strJson);
}
else
{
stop = true;
}
}
catch (ArgumentNullException) // no skip token, stop looping !!!!
{
stop = true;
}
}
return adUsers;
}
else
{
// return null;
throw new Exception("GetAdUsers: Graph API failed for path: " + path + ", tid: " + tid + ". Reason: " + Res.ReasonPhrase);
}
}
//UPDATE: I was able to update the code to use SOAP Microsoft Graph API like this:
public GraphServiceClient AuthGraph(string tid, string groupId)
{
try
{
var clientId = ConfigurationManager.AppSettings["ida:Audience"];
var clientSecret = ConfigurationManager.AppSettings["ida:clientSecret"];
var tenantID = tid;
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
//.WithRedirectUri(redirectUri)
.WithTenantId(tenantID)
.WithClientSecret(clientSecret)
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
return graphClient;
}
catch (Exception e)
{
throw e;
}
}
public async Task<List<User>> GetAdUsers(string tid, string groupId)
{
try
{
GraphServiceClient graphClient = AuthGraph(tid, groupId);
var graphUsers = await graphClient.Users
.Request()
.GetAsync();
List<User> users = graphUsers.Select(x => new User
{
Id = x.Id,
BusinessPhones = x.BusinessPhones.ToArray(),
DisplayName = x.DisplayName,
GivenName = x.GivenName,
JobTitle = x.JobTitle,
Mail = x.Mail,
MobilePhone = x.MobilePhone,
OfficeLocation = x.OfficeLocation,
PreferredLanguage = x.PreferredLanguage,
Surname = x.Surname,
UserPrincipalName = x.UserPrincipalName
}
).ToList();
if (!string.IsNullOrEmpty(groupId))
{
var membersInGroups = await GetNonSSOUsers(Globals.mghsTid, groupId);
users.AddRange(membersInGroups);
}
return users;
}
catch(Exception ex)
{
_errService.LogError("UserController.Update", tid, ex.HResult, ex.ToString().Substring(0, Math.Min(ex.ToString().Length, Globals.maxErrDescLen)), "getAdUsersService", 1, DateTime.Now.ToString());
throw ex;
}
}
public async Task<List<User>> GetNonSSOUsers(string tid, string groupId)
{
try
{
GraphServiceClient graphClient = AuthGraph(tid, groupId);
var members = await graphClient.Groups[groupId].Members
.Request()
.GetAsync();
List<User> users = new List<User>();
//while (members.NextPageRequest != null && (members = await members.NextPageRequest.GetAsync()).Count > 0)
//{
foreach (var member in members)
{
if (member is Microsoft.Graph.User)
{
var user = (Microsoft.Graph.User)member;
users.Add(new User
{
Id = user.Id,
BusinessPhones = user.BusinessPhones.ToArray(),
DisplayName = user.DisplayName,
GivenName = user.GivenName,
JobTitle = user.JobTitle,
Mail = user.Mail,
MobilePhone = user.MobilePhone,
OfficeLocation = user.OfficeLocation,
PreferredLanguage = user.PreferredLanguage,
Surname = user.Surname,
UserPrincipalName = user.UserPrincipalName
});
}
}
// }
return users;
}
catch (Exception e)
{
throw e;
}
}
The Microsoft Graph API is also protected under Azure AD. So, basically, you just need to add and grant necessary Graph API permissions to your application registered in Azure AD.
After that, you can call the Microsoft Graph API by adding an authorization header.

Can't get Novell.Directory.Ldap.NETStandard library to query

I need to let the user query an Active Directory for names in .Net Core.
So I am building an Active Directory Search Web API Service.
I am able to connect with the bind statement.
But I am not able to get any results back with my query although there is no error.
Another programmer sent me some code he uses in other applications. But it uses the DirectoryEntry object which is not available in .Net Core.
So I am trying to use the Novell.Directory.Ldap.NetStandard library.
Here is the code the other developer sent me:
public static List<UserProfileModel> GetADUsers(string alias)
{
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
// Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
de2.Path = ConfigurationManager.AppSettings["AD_Path"];
de2.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de2;
deSearch.Filter = "(samaccountname=*" + alias + "*)";
LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));
SearchResultCollection results = deSearch.FindAll();
String raw = "";
LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));
if (results.Count > 0)
{
foreach (SearchResult item in results)
{
UserProfileModel userProfileModel = new UserProfileModel();
userProfileModel.Name = GetADProperty("name", item);
userProfileModel.email = GetADProperty("mail", item);
userProfileModel.identity = GetADProperty("userPrincipalName", item);
userProfileModel.first_name = GetADProperty("givenName", item);
userProfileModel.last_name = GetADProperty("sn", item);
users.Add(userProfileModel);
raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
}
LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
}
}
catch (Exception e)
{
LOGGER.Error("Unable to Query Active Directory", e);
}
return users;
}
I need to translate this into Novell's LDAP library.
Here is my attempt:
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = "ourOrg.gov";
string loginDn = #"ourOrg\myName";
string password = "myPass";
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchResults results = con.Search(
"cn=users,dc=ourOrg,dc=gov",
LdapConnection.SCOPE_ONE,
"samaccountname=*",
null,
false);
// NO RESULTS:(
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
I don't get an error.
But there are 0 results.
I originally had this part:
"samaccountname=*",
like:
"samaccountname={alias}",
but I'm just trying to get back results at this point.
I got this working:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Hrsa.Core.Web.App.Controllers.Api
{
[Route("api/[controller]")]
public class ActiveDirectoryController : Controller
{
private readonly AppSettings _appSettings;
public ActiveDirectoryController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = _appSettings.HrsaLdapHost; // ourOrgName.gov
string loginDn = _appSettings.AdUser;
string password = _appSettings.AdPassword;
string searchBase = _appSettings.HrsaAdSearchBase;
string searchFilter = $"(samaccountname=*{alias}*)";
string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
"description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchQueue queue = con.Search(
searchBase,
LdapConnection.SCOPE_SUB,
searchFilter,
attributes,
false,
(LdapSearchQueue)null,
(LdapSearchConstraints)null);
LdapMessage message;
while ((message = queue.getResponse()) != null)
{
if (message is LdapSearchResult)
{
LdapEntry entry = ((LdapSearchResult)message).Entry;
LdapAttributeSet attributeSet = entry.getAttributeSet();
users.Add(new UserProfileModel
{
Cn = attributeSet.getAttribute("cn")?.StringValue,
UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
St = attributeSet.getAttribute("st")?.StringValue,
Givenname = attributeSet.getAttribute("givenname")?.StringValue,
Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
Description = attributeSet.getAttribute("description")?.StringValue,
Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
Department = attributeSet.getAttribute("department")?.StringValue,
Displayname = attributeSet.getAttribute("displayname")?.StringValue,
Name = attributeSet.getAttribute("name")?.StringValue,
Mail = attributeSet.getAttribute("mail")?.StringValue,
GivenName = attributeSet.getAttribute("givenName")?.StringValue,
Sn = attributeSet.getAttribute("sn")?.StringValue
});
}
}
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
}
}

Windows Phone 8.1 (appx) Database solution

I'm trying to find the best solution to have a local database in my WP8.1 application.
I'm using the standard WP8.1 (non-SL) and Visual Studio 2013.
I've looked into SQLite but I couldn't manage to get it to work on my application/Visual Studio.
If I can use SQLite, I need someone to point me out the way to go. Else, please refer me the best solution.
Thanks in advance!
Here's a repository class that leverages SQLite:
public class ContactsRepository : IContactsRepository
{
SQLiteAsyncConnection _connection = null;
static ContactsRepository _repository = null;
private ContactsRepository()
{
}
public async Task Initialize()
{
_connection = new SQLiteAsyncConnection(Constants.DATABASE_FILE_NAME);
await EnsureTableExist<ContactReference>(_connection);
}
public static ContactsRepository Instance
{
get
{
if (_repository == null)
{
_repository = new ContactsRepository();
}
return _repository;
}
}
public async Task Add(Category category, Contact contact)
{
var result = await _connection.Table<ContactReference>().Where(c => c.ContactId == contact.Id).FirstOrDefaultAsync();
if (result != null)
{
result.CategoryName = category.Name;
await _connection.UpdateAsync(result);
}
else
{
await _connection.InsertAsync(new ContactReference()
{
CategoryName = category.Name,
ContactId = contact.Id
});
}
}
public async Task Update(Category category, Contact contact)
{
var result = await _connection.Table<ContactReference>().Where(c => c.ContactId == contact.Id).FirstOrDefaultAsync();
Debug.Assert(result != null);
if (result == null)
{
throw new Exception("Unable to update category. Candidate not found");
}
if (result != null)
{
result.CategoryName = category.Name;
await _connection.UpdateAsync(result);
}
}
public async Task<ObservableCollection<Contact>> Get(string categoryName)
{
var result = new ObservableCollection<Contact>();
var query = _connection.Table<ContactReference>().Where(c => c.CategoryName == categoryName);
var queryResult = await query.ToListAsync();
foreach(var contact in queryResult)
{
var phoneContacts = ResourceLocator.Instance[typeof(ObservableCollection<Contact>)] as ObservableCollection<Contact>;
var phoneContact = phoneContacts.Where(c => c.Id == contact.ContactId).FirstOrDefault();
Debug.Assert(phoneContact != null);
if (phoneContact != null)
{
result.Add(phoneContact);
}
}
return result;
}
public async Task<ObservableCollection<ContactReference>> Get()
{
var result = new ObservableCollection<ContactReference>();
var query = _connection.Table<ContactReference>();
var queryResult = await query.ToListAsync();
foreach (var contact in queryResult)
{
result.Add(contact);
}
return result;
}
private async Task EnsureTableExist<T>(SQLiteAsyncConnection connection) where T : new()
{
bool noTableExists = false;
try
{
var query = await connection.Table<T>().FirstOrDefaultAsync();
}
catch (SQLiteException ex)
{
if (ex.Message.Contains("no such table"))
{
noTableExists = true;
}
}
if (noTableExists)
{
await connection.CreateTableAsync<T>();
}
}
}

Resources