Commit 3a4c4875 authored by Kirill's avatar Kirill

Авторизовывается пользователь и загружаются корректно эстейты

parent 8add35b7
using System;
using System.Collections.Generic;
namespace TourDataManager {
public class BigantoErrorException : Exception {
public BigantoErrorList ErrorsList;
public BigantoErrorException(BigantoErrorList errors){
ErrorsList = errors;
}
}
public struct BigantoErrorList {
public List<BigantoError> Errors;
}
public struct BigantoError {
public int Code;
public string Message;
public override string ToString(){ return $"code={Code};message={Message}"; }
}
}
\ No newline at end of file
...@@ -6,28 +6,23 @@ using System.Data.Entity; ...@@ -6,28 +6,23 @@ using System.Data.Entity;
using System.Data.Entity.Core.Common; using System.Data.Entity.Core.Common;
using System.Data.SQLite; using System.Data.SQLite;
using System.Data.SQLite.EF6; using System.Data.SQLite.EF6;
using System.Linq;
using System.Threading.Tasks;
using SQLite.CodeFirst; using SQLite.CodeFirst;
using TourDataManager.Entities;
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace TourDataManager { namespace TourDataManager {
[Table("Foo")]
public class Foo {
public long Id{ get; set; }
public string Data{ get; set; }
}
public class SQLiteConfiguration : DbConfiguration // ReSharper disable once InconsistentNaming
{ public class SQLiteConfiguration : DbConfiguration{
public SQLiteConfiguration() public SQLiteConfiguration(){
{
SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance); SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance); SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices))); SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
} }
} }
//[DbConfigurationType(typeof(Ef6CodeConfig))]
public class MyDbContext : DbContext{ public class MyDbContext : DbContext{
public MyDbContext(DbConnection connection, bool contextOwnsConnection) public MyDbContext(DbConnection connection, bool contextOwnsConnection)
...@@ -40,31 +35,52 @@ namespace TourDataManager { ...@@ -40,31 +35,52 @@ namespace TourDataManager {
protected override void OnModelCreating(DbModelBuilder modelBuilder){ protected override void OnModelCreating(DbModelBuilder modelBuilder){
//modelBuilder.Entity<Foo>(); // Эта штука отключает самостоятельную генерацию Id и позволяет мне самому устанавливать Id
var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<MyDbContext>(modelBuilder); modelBuilder.Entity<Estate>().Property(estate => estate.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
// Ещё, вероятно, помогло бы [DatabaseGenerated(DatabaseGeneratedOption.None)]
var sqliteConnectionInitializer = new SqliteDropCreateDatabaseWhenModelChanges<MyDbContext>(modelBuilder);
Database.SetInitializer(sqliteConnectionInitializer); Database.SetInitializer(sqliteConnectionInitializer);
} }
public DbSet<Foo> Foo{ get; set; } public DbSet<Estate> Estates{ get; set; }
} }
public class Db { public class Db : IDisposable {
private SQLiteConnection connection;
private MyDbContext context;
public Db(){ public Db(){
connection = new SQLiteConnection("data source=mylovelybase.sqlite");
context = new MyDbContext(connection,true);
}
using (var sqLiteConnection = new System.Data.SQLite.SQLiteConnection("data source=mylovelybase.sqlite")){ public Estate[] GetEstates(){
using (var db = new MyDbContext(sqLiteConnection,true)){ return context.Estates.ToArray();
db.Foo.Add(new Foo{Id = new Random().Next(0,1000), Data = "Yolo"}); }
db.SaveChanges(); public Task<Estate[]> GetEstatesAsync(){
return context.Estates.ToArrayAsync();
//db.Set<Foo>() }
}
}
public void InsertEstates(Estate[] estates){
//context.Estates.AddRange(estates);
foreach (var estate in estates){
context.Estates.Add(estate);
}
foreach (var contextEstate in context.Estates){
Debug.Log(contextEstate.Id);
}
context.SaveChanges();
} }
public void Dispose(){
connection?.Dispose();
}
} }
} }
\ No newline at end of file
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
namespace TourDataManager.Entities { namespace TourDataManager.Entities {
public class Estate { public class Estate {
/// Идентификатор объекта недвижимости /// Идентификатор объекта недвижимости
public long Id{ get; set; } [Key] public long Id{ get; set; }
public string Title{ get; set; } public string Title{ get; set; }
...@@ -16,5 +18,7 @@ namespace TourDataManager.Entities { ...@@ -16,5 +18,7 @@ namespace TourDataManager.Entities {
public string Preview{ get; set; } public string Preview{ get; set; }
public string Created{ get; set; } public string Created{ get; set; }
public override string ToString(){ return $"Estate : {Id} | {Title} | {TourCount} | {Preview} | {Created}"; }
} }
} }
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using Ninject; using Ninject;
using TourDataManager.Entities; using TourDataManager.Entities;
namespace TourDataManager { namespace TourDataManager {
public class GetEstatesUseCase { public class FetchEstatesUseCase {
[Inject]
public HttpClient httpClient{ get; set; }
public struct BigantoErrorList { [Inject] public HttpClient HttpClient{ get; set; }
public List<BigantoError> Errors; [Inject] public Db Database{ get; set; }
}
public struct BigantoError { public Task<Estate[]> FetchEstatesFromDb (){
public int Code; return Database.GetEstatesAsync();
public string Message;
public override string ToString(){ return $"code={Code};message={Message}"; }
}
public class BigantoErrorException : Exception {
public BigantoErrorList ErrorsList;
public BigantoErrorException(BigantoErrorList errors){
ErrorsList = errors;
}
} }
/// <summary> /// <summary>
/// <exception cref="HttpRequestException">Если сервер даст дубу</exception> /// <exception cref="HttpRequestException">Если сервер даст дубу</exception>
/// <exception cref="BigantoErrorException">Если вместо массива эстейтов с сервера получены ошибки</exception> /// <exception cref="BigantoErrorException">Если вместо массива эстейтов с сервера получены ошибки</exception>
/// <exception cref="JsonException">Если вместо массива эстейтов или ошибки пришло нечто иное</exception> /// <exception cref="JsonException">Если вместо массива эстейтов или ошибки пришло нечто иное</exception>
/// </summary> /// </summary>
public async Task<Estate[]> GetEstates(){ public async Task<Estate[]> FetchEstatesFromServer(){
var response = await httpClient.GetAsync("https://biganto.com/api-novus/estates.getList?client=desktopplayer&client_version=3.0&v=2.0"); var response = await HttpClient.GetAsync("https://biganto.com/api-novus/estates.getList?client=desktopplayer&client_version=3.0&v=2.0");
// throw HttpRequestException // throw HttpRequestException
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
...@@ -57,7 +39,7 @@ namespace TourDataManager { ...@@ -57,7 +39,7 @@ namespace TourDataManager {
if (error == null) return estates; if (error == null) return estates;
error = null; error = null;
// Вместо массиво эстейтов в ответе может содержаться json ошибки // Вместо массива эстейтов в ответе может содержаться json ошибки
// Предпринимается попытка десериализовать ошибки и выкинуть BigantoErrorException // Предпринимается попытка десериализовать ошибки и выкинуть BigantoErrorException
var exceptionList = JsonConvert.DeserializeObject<BigantoErrorList>(content,errorHandlerSettings); var exceptionList = JsonConvert.DeserializeObject<BigantoErrorList>(content,errorHandlerSettings);
......
using System; using System;
using System.Data.Entity;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Ninject; using Ninject;
...@@ -7,7 +8,16 @@ using TourDataManager.Entities; ...@@ -7,7 +8,16 @@ using TourDataManager.Entities;
namespace TourDataManager { namespace TourDataManager {
/// <summary>
/// Фасад для всего плагина
/// </summary>
public class TourDataManager { public class TourDataManager {
public FetchEstatesUseCase fetch{ get; set; }
public Db database{ get; set; }
private string persistentPath; private string persistentPath;
private IKernel Container; private IKernel Container;
...@@ -15,6 +25,10 @@ namespace TourDataManager { ...@@ -15,6 +25,10 @@ namespace TourDataManager {
public TourDataManager(string persistentPath){ public TourDataManager(string persistentPath){
this.persistentPath = persistentPath; this.persistentPath = persistentPath;
Container = new StandardKernel(new MyModule(persistentPath)); Container = new StandardKernel(new MyModule(persistentPath));
fetch = Container.Get<FetchEstatesUseCase>();
database = Container.Get<Db>();
} }
public void Login(string email, string password){ public void Login(string email, string password){
...@@ -26,8 +40,15 @@ namespace TourDataManager { ...@@ -26,8 +40,15 @@ namespace TourDataManager {
}); });
} }
public Task<Estate[]> GetEstates(){ public async Task<Estate[]> DownloadEstates(){
return Container.Get<GetEstatesUseCase>().GetEstates(); try{
var estates = await fetch.FetchEstatesFromServer();
database.InsertEstates(estates);
return estates;
} catch (Exception){
Debug.Log("Не удалось загрузить эстейты");
return null;
}
} }
} }
...@@ -51,7 +72,8 @@ namespace TourDataManager { ...@@ -51,7 +72,8 @@ namespace TourDataManager {
Bind<HttpClientHandler>().ToConstant(httpClientHandler).InSingletonScope(); Bind<HttpClientHandler>().ToConstant(httpClientHandler).InSingletonScope();
Bind<HttpClient>().ToConstant(httpClient).InSingletonScope(); Bind<HttpClient>().ToConstant(httpClient).InSingletonScope();
Bind<IAuthenticator>().To<Authenticator>().InSingletonScope(); Bind<IAuthenticator>().To<Authenticator>().InSingletonScope();
Bind<GetEstatesUseCase>().ToSelf().InSingletonScope(); Bind<FetchEstatesUseCase>().ToSelf().InSingletonScope();
Bind<Db>().ToSelf().InSingletonScope();
} }
} }
......
...@@ -104,12 +104,13 @@ ...@@ -104,12 +104,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Authenticator.cs" /> <Compile Include="Authenticator.cs" />
<Compile Include="BigantoErrorException.cs" />
<Compile Include="CookieStorage.cs" /> <Compile Include="CookieStorage.cs" />
<Compile Include="Db.cs" /> <Compile Include="Db.cs" />
<Compile Include="Debug.cs" /> <Compile Include="Debug.cs" />
<Compile Include="Entities\Estate.cs" /> <Compile Include="Entities\Estate.cs" />
<Compile Include="Entities\Tour.cs" /> <Compile Include="Entities\Tour.cs" />
<Compile Include="GetEstatesUseCase.cs" /> <Compile Include="FetchEstatesUseCase.cs" />
<Compile Include="IAuthenticator.cs" /> <Compile Include="IAuthenticator.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TourDataManager.cs" /> <Compile Include="TourDataManager.cs" />
......
...@@ -15,12 +15,12 @@ namespace TourDataManagerConsoleApplication { ...@@ -15,12 +15,12 @@ namespace TourDataManagerConsoleApplication {
tourDataManager.Login(defaultLogin, defaultPassword); tourDataManager.Login(defaultLogin, defaultPassword);
//new Db(); //new Db();
tourDataManager.GetEstates().ContinueWith(task => {
var est = task.Result; tourDataManager.DownloadEstates().ContinueWith(task => {
foreach (var estate in task.Result){
Debug.Log(estate);
}
}); });
Console.Read(); Console.Read();
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment