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;
using System.Data.Entity.Core.Common;
using System.Data.SQLite;
using System.Data.SQLite.EF6;
using System.Linq;
using System.Threading.Tasks;
using SQLite.CodeFirst;
using TourDataManager.Entities;
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace TourDataManager {
[Table("Foo")]
public class Foo {
public long Id{ get; set; }
public string Data{ get; set; }
}
public class SQLiteConfiguration : DbConfiguration
{
public SQLiteConfiguration()
{
// ReSharper disable once InconsistentNaming
public class SQLiteConfiguration : DbConfiguration{
public SQLiteConfiguration(){
SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
}
}
//[DbConfigurationType(typeof(Ef6CodeConfig))]
public class MyDbContext : DbContext{
public MyDbContext(DbConnection connection, bool contextOwnsConnection)
......@@ -40,31 +35,52 @@ namespace TourDataManager {
protected override void OnModelCreating(DbModelBuilder modelBuilder){
//modelBuilder.Entity<Foo>();
var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<MyDbContext>(modelBuilder);
// Эта штука отключает самостоятельную генерацию Id и позволяет мне самому устанавливать Id
modelBuilder.Entity<Estate>().Property(estate => estate.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
// Ещё, вероятно, помогло бы [DatabaseGenerated(DatabaseGeneratedOption.None)]
var sqliteConnectionInitializer = new SqliteDropCreateDatabaseWhenModelChanges<MyDbContext>(modelBuilder);
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(){
connection = new SQLiteConnection("data source=mylovelybase.sqlite");
context = new MyDbContext(connection,true);
}
using (var sqLiteConnection = new System.Data.SQLite.SQLiteConnection("data source=mylovelybase.sqlite")){
using (var db = new MyDbContext(sqLiteConnection,true)){
db.Foo.Add(new Foo{Id = new Random().Next(0,1000), Data = "Yolo"});
db.SaveChanges();
//db.Set<Foo>()
}
}
public Estate[] GetEstates(){
return context.Estates.ToArray();
}
public Task<Estate[]> GetEstatesAsync(){
return context.Estates.ToArrayAsync();
}
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.Serialization;
namespace TourDataManager.Entities {
public class Estate {
/// Идентификатор объекта недвижимости
public long Id{ get; set; }
[Key] public long Id{ get; set; }
public string Title{ get; set; }
......@@ -16,5 +18,7 @@ namespace TourDataManager.Entities {
public string Preview{ 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.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Ninject;
using TourDataManager.Entities;
namespace TourDataManager {
public class GetEstatesUseCase {
[Inject]
public HttpClient httpClient{ get; set; }
public class FetchEstatesUseCase {
public struct BigantoErrorList {
public List<BigantoError> Errors;
}
[Inject] public HttpClient HttpClient{ get; set; }
[Inject] public Db Database{ get; set; }
public struct BigantoError {
public int Code;
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;
}
public Task<Estate[]> FetchEstatesFromDb (){
return Database.GetEstatesAsync();
}
/// <summary>
/// <exception cref="HttpRequestException">Если сервер даст дубу</exception>
/// <exception cref="BigantoErrorException">Если вместо массива эстейтов с сервера получены ошибки</exception>
/// <exception cref="JsonException">Если вместо массива эстейтов или ошибки пришло нечто иное</exception>
/// </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
var content = await response.Content.ReadAsStringAsync();
......@@ -57,7 +39,7 @@ namespace TourDataManager {
if (error == null) return estates;
error = null;
// Вместо массиво эстейтов в ответе может содержаться json ошибки
// Вместо массива эстейтов в ответе может содержаться json ошибки
// Предпринимается попытка десериализовать ошибки и выкинуть BigantoErrorException
var exceptionList = JsonConvert.DeserializeObject<BigantoErrorList>(content,errorHandlerSettings);
......
using System;
using System.Data.Entity;
using System.Net.Http;
using System.Threading.Tasks;
using Ninject;
......@@ -7,7 +8,16 @@ using TourDataManager.Entities;
namespace TourDataManager {
/// <summary>
/// Фасад для всего плагина
/// </summary>
public class TourDataManager {
public FetchEstatesUseCase fetch{ get; set; }
public Db database{ get; set; }
private string persistentPath;
private IKernel Container;
......@@ -15,6 +25,10 @@ namespace TourDataManager {
public TourDataManager(string persistentPath){
this.persistentPath = persistentPath;
Container = new StandardKernel(new MyModule(persistentPath));
fetch = Container.Get<FetchEstatesUseCase>();
database = Container.Get<Db>();
}
public void Login(string email, string password){
......@@ -26,8 +40,15 @@ namespace TourDataManager {
});
}
public Task<Estate[]> GetEstates(){
return Container.Get<GetEstatesUseCase>().GetEstates();
public async Task<Estate[]> DownloadEstates(){
try{
var estates = await fetch.FetchEstatesFromServer();
database.InsertEstates(estates);
return estates;
} catch (Exception){
Debug.Log("Не удалось загрузить эстейты");
return null;
}
}
}
......@@ -51,7 +72,8 @@ namespace TourDataManager {
Bind<HttpClientHandler>().ToConstant(httpClientHandler).InSingletonScope();
Bind<HttpClient>().ToConstant(httpClient).InSingletonScope();
Bind<IAuthenticator>().To<Authenticator>().InSingletonScope();
Bind<GetEstatesUseCase>().ToSelf().InSingletonScope();
Bind<FetchEstatesUseCase>().ToSelf().InSingletonScope();
Bind<Db>().ToSelf().InSingletonScope();
}
}
......
......@@ -104,12 +104,13 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Authenticator.cs" />
<Compile Include="BigantoErrorException.cs" />
<Compile Include="CookieStorage.cs" />
<Compile Include="Db.cs" />
<Compile Include="Debug.cs" />
<Compile Include="Entities\Estate.cs" />
<Compile Include="Entities\Tour.cs" />
<Compile Include="GetEstatesUseCase.cs" />
<Compile Include="FetchEstatesUseCase.cs" />
<Compile Include="IAuthenticator.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TourDataManager.cs" />
......
......@@ -15,12 +15,12 @@ namespace TourDataManagerConsoleApplication {
tourDataManager.Login(defaultLogin, defaultPassword);
//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();
}
......
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