SQLite Xamarin/C# inserting data - c#

I am developing an application. I have connected my project to SQLIte, now I am trying to add an advert, which I am failing to do.
my SQLInterface
public interface ISQLiteInterface
{
SQLiteConnection GetSQLiteConnection();
}
my Droid SQL
public class SQLiteDb : ISQLiteInterface
{
public SQLiteDb()
{
}
public SQLiteConnection GetSQLiteConnection()
{
var fileName = "Mydatabase.db";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(dbpath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}
}
}
my model
public class AdLogEntry
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string SellerName { get; set; }
public string Name { get; set; }
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
public string Image { get; set; }
public string Video { get; set; }
public string Description { get; set; }
public string Price { get; set; }
public string LoadedDate { get; set; }
public string Location { get; set; }
public int Age { get; set; }
}
public class Picture
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] Image { get; set; }
}
public class Video
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] ImageVideo { get; set; }
}
}
this is my task
private async void NextStep_Clicked(object sender, EventArgs e)
{
await SaveAdLog();
}
private async Task SaveAdLog()
{
if (string.IsNullOrWhiteSpace(NameEntry.Text) || (string.IsNullOrWhiteSpace(PriceEntry.Text) || (string.IsNullOrWhiteSpace(LocationEntry.Text))))
{
await DisplayAlert("error", "fill all entries", "OK");
}
else {
var adLogEntry = new AdLogEntry
{
Location = LocationEntry.Text,
Price = PriceEntry.Text,
Name = NameEntry.Text,
};
var result = _adService.CreateAddLogEntry(adLogEntry); //ok
if (result == null)
{
await DisplayAlert("Gratulace", "", "OK");
App.Current.MainPage = new AppShell();
}
};
}
this is my advertservice
class AdService
{
private SQLiteConnection _conn;
public AdService()
{
_conn = DependencyService.Get<Helpers.ISQLiteInterface>().GetSQLiteConnection();
_conn.CreateTable<AdLogEntry>();
}
public string CreateAddLogEntry(AdLogEntry adLogEntry)
{
var detail = _conn.Table<AdLogEntry>();
var d1 = detail.Connection.Insert(adLogEntry);
return "Thank you";
}
}
}
Once I press the button nothing happens. When I try to debug it i get 'Object reference not set to an instance of an object.'
Edit.
This app is supposed to be something like LetItGo so all values should be able to repeat
I have ISQLite interface implemented.

According to your error message, I can not see where you instantiate a new instance of the AdService class.
So please try to add the following code before you call _adService.CreateAddLogEntry() method.
_adService = new AdService();

i think SQLite can't process this properties in your model
List< Picture > and
List< Video >
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
I suggest that you change the property to string and serialize the data before saving

Related

Most efficient way to compare an Entity Model to a DTO Model in C#/LINQ

I am passing back a DTO object with a more than a dozen properties that I want to update in the database only if one or more of the properties differ with the current EF object. What is the most programmatically simple way to accomplish this using C# and Lambda-syntax LINQ?
Try this example.
[HttpPost]
[Route("Client/UpdateClient")]
[Authorize]
public ActionResult UpdateClient(ClientDTO client)
{
var user = GetLoggerUser(BOAccount);
client.LastModifiedBy = user.EmailAddress;
client.LastModifiiedOn = DateTime.UtcNow;
var resultclient = BOClient.UpdateClient(client, user);
return Json(resultclient);
}
// BOClient.UpdateClient
public ClientDTO UpdateClient(ClientDTO client, UserDTO user)
{
var _clientRepo = ((UnitOfWork)_unitOfWork).ClientRepository;
var _client = _clientRepo.Get(filter: u => u.Id == client.Id).Single();
_client.Id = client.Id;
_client.Phone = client.Phone;
_client.Address = client.Address;
_client.Email = client.Email;
_client.Type = client.Type;
_client.Name = client.Name;
object _transaction = _unitOfWork.BeginTransaction();
try
{
_clientRepo.Update(_client);
_unitOfWork.CommitTransaction(_transaction);
}
catch (Exception)
{
_unitOfWork.RollbackTransaction(_transaction);
return client;
}
finally
{
_unitOfWork.DestroyTransaction(_transaction);
}
return client;
}
And Created model is
namespace OptiLeadInfrastructure.Models
{
public class ClientDTO
{
public long Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public Nullable<short> Type { get; set; }
public string logo { get; set; }
public Nullable<DateTime> CreatedOn { get; set; }
public string CreatedBy { get; set; }
public Nullable<DateTime> LastModifiiedOn { get; set; }
public virtual ICollection<ClientDetailDTO> ClientDetails { get; set; }
} public string LastModifiedBy { get; set; }
}

How do i link JSON result to Syncfusion Scheduler xamarin

I have a syncfusion scheduler on my App and i need to display Json result in the schedular
public partial class test : ContentPage
{
public Picker viewPicker;
public class Data
{
public DateTime date_start { get; set; }
public DateTime date_end { get; set; }
public string salle { get; set; }
public string professeur { get; set; }
public string lib1_formation { get; set; }
public string semaine { get; set; }
public string jours { get; set; }
public string module { get; set; }
public string groupe_de_classe { get; set; }
public string type { get; set; }
public string remarque { get; set; }
public string autre_professeur { get; set; }
public string autre_groupe { get; set; }
public string descrption { get; set; }
public Color Color { get; set; }
}
public test ()
{
SfSchedule schedule;
InitializeComponent();
Calend();
Rest();
}
public void Rest()
{
Restcours Rest_3 = new Restcours();
Rest Student = new Rest();
IRestResponse result_Student = Rest_3.Student("y.abasri#net.estia.fr");
var JResponse_student = JsonConvert.DeserializeObject<dynamic>(result_Student.Content);
Trace.Write(string.Format("Request completed in {0} ms, Response: {1} ", 50, "ffffffffffffffffffffffff"));
Console.WriteLine("This is the JSON RESULT --> " + JResponse_student);
List<Data> lstData = new List<Data>();
lstData.Add(JResponse_student.events);
Console.WriteLine("hada houwaa --->" + JResponse_student.data.events);
}
public void Calend()
{
schedule = new SfSchedule();
new ContentPage { Content = schedule };
schedule.FirstDayOfWeek = (int)DayOfWeek.Tuesday;
schedule.ScheduleView = ScheduleView.MonthView;
MonthViewSettings monthViewSettings = new MonthViewSettings();
monthViewSettings.AppointmentIndicatorCount = 2;
schedule.MonthViewSettings = monthViewSettings;
}
i didn't find any tutorials or docs about linking JSON to Syncfusion only the syncfusion link : https://help.syncfusion.com/xamarin/sfschedule/getting-started
Please help me out THANK YOU

How to implement different class types within one variable?

I have 3 object classes:
public class MessageData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public string EmployeeInfo { get; set; }
}
public class MultiMessageData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public byte MessageType { get; set; }
public string MessageType { get; set; }
public string Platform { get; set; }
public string EmployeeInfo { get; set; }
}
public class SocialData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public bool IsReceived { get; set; }
public byte MessageType { get; set; }
public string MessageType { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
}
Then I have a function right now that only implement the MessageData class:
public void SendData()
{
List<MessageData> data = new List<MessageData>();
// some work here with data variable...
_sendRepository.Send(data);
}
Now what I need is to keep most of the logic but a way that I can instantiate a variable that can be of any class type for example:
public void SendData()
{
var data;
if(logic == 1){
data = new List<MessageData>();
} else if(logic == 2){
data = new List<MultiMessageData>();
}else {
data = new List<SocialData>();
}
// some work here...
// if I do that then this Send method I will change it to be a Generic T maybe.
_sendRepository.Send(data);
}
Any clue?
Inheritance is the way to go:
public class MessageDataBase
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
}
public class MessageData : MessageDataBase
{
public string EmployeeInfo { get; set; }
}
public class MultiMessageData : MessageDataBase
{
public byte MessageType { get; set; }
public string MessageTypeString { get; set; }
public string Platform { get; set; }
public string EmployeeInfo { get; set; }
}
public class SocialData : MessageDataBase
{
public bool IsReceived { get; set; }
public byte MessageType { get; set; }
public string MessageTypeString { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
}
Use an interface, but you will have to make common changes in the //..do some work here section
public interface IMessageData
{
//Example required function for all MessageData classes
void SetDate(DateTime date);
void SetIsSent(bool date);
}
public abstract class BaseMessageData : IMessageData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public BaseMessageData(string messageID)
{
MessageID=messageID;
}
public void SetDate(DateTime date)
{
Date = date.ToString("MM/dd/yyyy");
}
public void SetIsSent(bool sentStatus)
{
IsSent = sentStatus;
}
}
public class MessageData : BaseMessageData, IMessageData
{
public string EmployeeInfo { get; set; }
}
public class MultiMessageData : MessageData,IMessageData
{
public byte MessageType { get; set; }
public string MessageType { get; set; }
public string Platform { get; set; }
}
public class SocialData : BaseMessageData, IMessageData
{
public bool IsReceived { get; set; }
public byte MessageType { get; set; }
//Can't have to properties named the same.
//public string MessageType { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
}
Then in your SendData
public void SendData()
{
List<IMessageData> data;
if (logic == 1)
{
data = new List<MessageData>();
}
else if (logic == 2)
{
data = new List<MultiMessageData>();
}
else
{
data = new List<SocialData>();
}
// some work here...
foreach (var d in data)
{
//Only methods that will work are ones declared in the IMessageData interface
d.SesDate(DateTime.Now);
d.SetIsSent(true);
}
// if I do that then this Send method I will change it to be a Generic T maybe.
_sendRepository.Send(data);
}
You can use my open source library, OneOf https://github.com/mcintyre321/OneOf
A OneOf is a special Type which can hold one value from a range of Types, like a Discriminated Union in F#. It provides an alternative to using inheritance/polymorphism.
You would write your method like this:
public void SendData()
{
OneOf<List<MessageData>, List<MultiMessageData>, List<SocialData>> data = null;
if(logic == 1){
data = new List<MessageData>();
} else if(logic == 2){
data = new List<MultiMessageData>();
}else {
data = new List<SocialData>();
}
// some work here...
_sendRepository.Send(data);
}
Or you could have var data = List<OneOf<MessageData, MultiMessageData, SocialData>>(); if you prefer, especially if you want to have different
Types in the list.
install-package OneOf
It supports net451 and netstandard1.6

Pass values of variables

I writing app for UWP
I have PCL where I writing methods for downloading json from OpenWeather
Here is code.
public class WeatherRepositoryForUWP
{
private string url = "http://api.openweathermap.org/data/2.5/weather?q=London&units=imperial&APPID=274c6def18f89eb1d9a444822d2574b5";
public async void DownloadWeather()
{
var json = await FetchAsync(url);
Debug.WriteLine(json.ToString());
}
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
//var stream = httpClient.GetStreamAsync(url).Result;
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
// Classes for parser
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public int temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public int deg { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string #base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
}
}
Also I have GUI where user write it city and it writing o variable when he\she taps button.
Here is code for this:
private void city_button_Click(object sender, RoutedEventArgs e)
{
string city_name;
city_name = city_text.Text;
Debug.WriteLine(city_name);
}
I need to take value from city_name and pass it to class in PCL and write to string variable.
How I can do this?
Thank's for help!
In order to be able to retrieve weather information for a custom city, you need to change your WeatherRepositoryForUWP class the following way:
public class WeatherRepositoryForUWP
{
private string urlFormat = "http://api.openweathermap.org/data/2.5/weather?q={0}&units=imperial&APPID=274c6def18f89eb1d9a444822d2574b5";
public async Task<string> DownloadWeather(string city)
{
return await FetchAsync(string.Format(urlFormat, city));
}
// Rest of class remains unchanged....
}
Then, in your click event handler, you have to do the following:
private void city_button_Click(object sender, RoutedEventArgs e)
{
string city_name;
city_name = city_text.Text;
var weatherService = new WeatherRepositoryForUWP();
string weatherData = weatherService.DownloadWeather(city_name).Result;
}

Entity Framework Null Reference Exception

I am trying to grasp EF Code First but I still do not get how to access the referenced objects from another class (due to lack of enough knowledge, I cannot even formulate the question).
Here's what my simple code looks like:
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
public class BreakAwayContext: DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
private static void InsertDestination()
{
var destination = new Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using(var context = new BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
private static void InsertLodging()
{
var lodging = new Lodging()
{
Name = "x",
IsResort = false,
Owner = "asdasd"
};
using(var context = new BreakAwayContext())
{
var dest = context.Destinations.Find(1);
lodging.Destination = dest;
context.Lodgings.Add(lodging);
context.SaveChanges();
}
}
private static void ShowLodgings()
{
using(var context = new BreakAwayContext())
{
foreach(var l in context.Lodgings)
{
Console.WriteLine("{0} {1} {2}", l.Name, l.Owner, l.Destination.Name);
}
}
}
I get a NullReferenceException on the line I try to write the destination name to the console.
Thanks in advance.
Try using navigation properties:
First make Destination virtual
public virtual Destination Destination { get; set; }
Then use Include method
foreach(var l in context.Lodgings.Include(x => x.Destination))
Just set Destination property in your Lodging class, virtual. This tell, the EF to load Destination automatically when you need it(Lazy Loading).
So your Lodging class should looks like:
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public virtual Destination Destination { get; set; }
}

Categories