Test Creation DesktopApp

This commit is contained in:
2019-03-09 14:03:25 +01:00
parent e8fd116eab
commit ac9614a70a
34 changed files with 1131 additions and 189 deletions

View File

@@ -23,19 +23,6 @@ namespace LaDOSE.Api.Controllers
this._gameService = gameService; this._gameService = gameService;
} }
[HttpGet("GetUsers/{eventId}/{wpEventId}/{gameId}")]
public List<WPUser> GetUsers(int eventId, int wpEventId,int gameId)
{
var game = _gameService.GetById(gameId);
return _service.GetBooking(eventId, wpEventId,game);
}
[HttpGet("Generate/{eventId}/{wpEventId}")]
public bool GenerateChallonge(int eventId, int wpEventId)
{
return _service.CreateChallonge(eventId, wpEventId);
} }
} }
}

View File

@@ -18,7 +18,7 @@ namespace LaDOSE.Api.Controllers
[HttpPost] [HttpPost]
public TU Post([FromBody]TU dto) public TU Post([FromBody]TU dto)
{ {
return _service.Create(dto); return _service.AddOrUpdate(dto);
} }
[HttpGet] [HttpGet]
public List<TU> Get() public List<TU> Get()

View File

@@ -1,28 +0,0 @@
using LaDOSE.Business.Interface;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LaDOSE.Api.Controllers
{
[Authorize]
[Produces("application/json")]
[Route("api/[controller]")]
public class UtilController : Controller
{
private IUtilService _service;
public UtilController(IUtilService service)
{
_service = service;
}
[HttpGet("UpdateBooking")]
public bool UpdateBooking()
{
return _service.UpdateBooking();
}
}
}

View File

@@ -11,20 +11,62 @@ namespace LaDOSE.Api.Controllers
[Route("api/[controller]")] [Route("api/[controller]")]
public class WordPressController : Controller public class WordPressController : Controller
{ {
public IGameService GameService { get; }
private IWordPressService _service;
// GET // GET
public WordPressController(IWordPressService service) public WordPressController(IWordPressService service, IGameService gameService )
{ {
GameService = gameService;
_service = service; _service = service;
} }
private IWordPressService _service;
[HttpGet("WPEvent")] [HttpGet("WPEvent")]
public List<WPEvent> Event() public List<WPEvent> Event()
{ {
return _service.GetWpEvent(); var wpEvents = _service.GetWpEvent();
foreach (var wpEvent in wpEvents)
{
foreach (var wpEventWpBooking in wpEvent.WPBookings)
{
wpEventWpBooking.WPEvent = null;
wpEventWpBooking.WPUser.WPBookings = null;
}
}
return wpEvents;
}
[HttpGet("GetUsers/{wpEventId}/{gameId}")]
public List<WPUser> GetUsers(int wpEventId, int gameId)
{
var game = GameService.GetById(gameId);
return _service.GetBooking(wpEventId, game);
} }
[HttpGet("GetUsersOptions/{wpEventId}/{gameId}")]
public List<WPUser> GetUsersOptions(int wpEventId, int gameId)
{
var game = GameService.GetById(gameId);
return _service.GetBookingOptions(wpEventId, game);
}
[HttpGet("UpdateDb")]
public bool UpdateDb()
{
return _service.UpdateBooking();
}
[HttpGet("CreateChallonge/{gameId:int}/{wpEventId:int}")]
public bool CreateChallonge(int gameId, int wpEventId)
{
return _service.CreateChallonge(gameId, wpEventId);
}
} }
} }

View File

@@ -44,7 +44,11 @@ namespace LaDOSE.Api
services.AddCors(); services.AddCors();
services.AddMvc().AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddMvc().AddJsonOptions(x =>
{
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
x.SerializerSettings.MaxDepth= 4;
});
services.AddDbContextPool<LaDOSEDbContext>( // replace "YourDbContext" with the class name of your DbContext services.AddDbContextPool<LaDOSEDbContext>( // replace "YourDbContext" with the class name of your DbContext
options => options.UseMySql($"Server={MySqlServer};Database={MySqlDatabase};User={MySqlUser};Password={MySqlPassword};", // replace with your Connection String options => options.UseMySql($"Server={MySqlServer};Database={MySqlDatabase};User={MySqlUser};Password={MySqlPassword};", // replace with your Connection String
mysqlOptions => mysqlOptions =>
@@ -99,7 +103,6 @@ namespace LaDOSE.Api
services.AddScoped<IGameService, GameService>(); services.AddScoped<IGameService, GameService>();
services.AddScoped<IEventService, EventService>(); services.AddScoped<IEventService, EventService>();
services.AddScoped<ISeasonService, SeasonService>(); services.AddScoped<ISeasonService, SeasonService>();
services.AddScoped<IUtilService, UtilService>();
services.AddScoped<IWordPressService, WordPressService>(); services.AddScoped<IWordPressService, WordPressService>();
services.AddTransient<IChallongeProvider>(p => new ChallongeProvider(this.Configuration["ApiKey:ChallongeApiKey"])); services.AddTransient<IChallongeProvider>(p => new ChallongeProvider(this.Configuration["ApiKey:ChallongeApiKey"]));
} }

View File

@@ -5,5 +5,7 @@
public int Id { get; set; } public int Id { get; set; }
public string Name { get; set; } public string Name { get; set; }
public string ImgUrl { get; set; } public string ImgUrl { get; set; }
public string WordPressTag { get; set; }
public string WordPressTagOs { get; set; }
} }
} }

View File

@@ -12,6 +12,20 @@ namespace LaDOSE.DTO
public string Name { get; set; } public string Name { get; set; }
public string Slug { get; set; } public string Slug { get; set; }
public DateTime? Date { get; set; } public DateTime? Date { get; set; }
public List<WPBooking> WpBookings { get; set; }
}
public class WPBooking
{
public WPUser WpUser { get; set; }
public string Message { get; set; }
public string Meta { get; set; }
}
public class WPUser
{
public string Name { get; set; }
}
} }
}

View File

@@ -1,5 +1,10 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<configuration> <configuration>
<appSettings>
<add key="ApiUri" value="http://localhost:5000"/>
<add key="ApiUser" value="User"/>
<add key="ApiPassword" value="Password"/>
</appSettings>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup> </startup>

View File

@@ -4,6 +4,7 @@
xmlns:local="clr-namespace:LaDOSE.DesktopApp" xmlns:local="clr-namespace:LaDOSE.DesktopApp"
> >
<Application.Resources> <Application.Resources>
<ResourceDictionary> <ResourceDictionary>
<ResourceDictionary.MergedDictionaries> <ResourceDictionary.MergedDictionaries>
<ResourceDictionary> <ResourceDictionary>

View File

@@ -48,6 +48,7 @@
<HintPath>..\packages\RestSharp.106.6.5\lib\net452\RestSharp.dll</HintPath> <HintPath>..\packages\RestSharp.106.6.5\lib\net452\RestSharp.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Web" /> <Reference Include="System.Web" />
<Reference Include="System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Reference Include="System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
@@ -72,7 +73,13 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
</ApplicationDefinition> </ApplicationDefinition>
<Compile Include="Bootstrapper.cs" /> <Compile Include="Bootstrapper.cs" />
<Compile Include="Utils\PhpSerialize.cs" />
<Compile Include="Services\RestService.cs" /> <Compile Include="Services\RestService.cs" />
<Compile Include="UserControls\BookingUserControl.xaml.cs">
<DependentUpon>BookingUserControl.xaml</DependentUpon>
</Compile>
<Compile Include="Utils\WpEventDeserialize.cs" />
<Compile Include="Utils\WpfUtil.cs" />
<Compile Include="ViewModels\ShellViewModel.cs" /> <Compile Include="ViewModels\ShellViewModel.cs" />
<Compile Include="ViewModels\GameViewModel.cs" /> <Compile Include="ViewModels\GameViewModel.cs" />
<Compile Include="ViewModels\WordPressViewModel.cs" /> <Compile Include="ViewModels\WordPressViewModel.cs" />
@@ -89,6 +96,10 @@
<DependentUpon>App.xaml</DependentUpon> <DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Page Include="UserControls\BookingUserControl.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Views\ShellView.xaml"> <Page Include="Views\ShellView.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType> <SubType>Designer</SubType>
@@ -127,7 +138,9 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config">
<SubType>Designer</SubType>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\LaDOSE.DTO\LaDOSE.DTO.csproj"> <ProjectReference Include="..\LaDOSE.DTO\LaDOSE.DTO.csproj">
@@ -135,6 +148,8 @@
<Name>LaDOSE.DTO</Name> <Name>LaDOSE.DTO</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup /> <ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>

View File

@@ -1,10 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration;
using System.Windows; using System.Windows;
using LaDOSE.DTO; using LaDOSE.DTO;
using RestSharp; using RestSharp;
using RestSharp.Authenticators; using RestSharp.Authenticators;
using RestSharp.Serialization.Json; using RestSharp.Serialization.Json;
using DataFormat = RestSharp.DataFormat;
namespace LaDOSE.DesktopApp.Services namespace LaDOSE.DesktopApp.Services
{ {
@@ -14,9 +16,14 @@ namespace LaDOSE.DesktopApp.Services
public RestService() public RestService()
{ {
Client = new RestClient("http://localhost:5000/");
var appSettings = ConfigurationManager.AppSettings;
string url = (string) appSettings["ApiUri"];
string user = (string)appSettings["ApiUser"];
string password = (string) appSettings["ApiPassword"];
Client = new RestClient(url);
var restRequest = new RestRequest("users/auth", Method.POST); var restRequest = new RestRequest("users/auth", Method.POST);
restRequest.AddJsonBody(new { username = "****", password = "*****" }); restRequest.AddJsonBody(new { username = user, password = password });
var response = Client.Post(restRequest); var response = Client.Post(restRequest);
if (response.IsSuccessful) if (response.IsSuccessful)
{ {
@@ -26,10 +33,42 @@ namespace LaDOSE.DesktopApp.Services
} }
else else
{ {
throw new Exception("No Service Avaliable"); MessageBox.Show("Unable to contact services, i m useless, BYEKTHX","Error",MessageBoxButton.OK,MessageBoxImage.Error);
Application.Current.Shutdown(-1);
} }
} }
#region PostFix
private T Post<T>(string resource,T entity)
{
var json = new RestSharp.Serialization.Json.JsonSerializer();
var jsonD = new RestSharp.Serialization.Json.JsonDeserializer();
var request = new RestRequest();
request.Method = Method.POST;
request.Resource = resource;
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-type", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json; charset=utf-8", json.Serialize(entity), ParameterType.RequestBody);
request.AddObject(entity);
var response = Client.Execute(request);
//var content = response.Content; // raw content as string
try
{
return jsonD.Deserialize<T>(response);
}
catch (Exception)
{
return default(T);
}
}
#endregion
#region WordPress
public List<WPEvent> GetEvents() public List<WPEvent> GetEvents()
{ {
var restRequest = new RestRequest("/api/wordpress/WPEvent", Method.GET); var restRequest = new RestRequest("/api/wordpress/WPEvent", Method.GET);
@@ -37,11 +76,59 @@ namespace LaDOSE.DesktopApp.Services
return restResponse.Data; return restResponse.Data;
} }
public bool CreateChallonge(int gameId, int eventId)
{
var restRequest = new RestRequest($"/api/wordpress/CreateChallonge/{gameId}/{eventId}", Method.GET);
var restResponse = Client.Get<bool>(restRequest);
return restResponse.Data;
}
public bool RefreshDb()
{
var restRequest = new RestRequest("/api/Wordpress/UpdateDb", Method.GET);
var restResponse = Client.Get<bool>(restRequest);
return restResponse.Data;
}
public List<WPUser> GetUsers(int wpEventId, int gameId)
{
var restRequest = new RestRequest($"/api/Wordpress/GetUsers/{wpEventId}/{gameId}", Method.GET);
var restResponse = Client.Get<List<WPUser>>(restRequest);
return restResponse.Data;
}
public List<WPUser> GetUsersOptions(int wpEventId, int gameId)
{
var restRequest = new RestRequest($"/api/Wordpress/GetUsersOptions/{wpEventId}/{gameId}", Method.GET);
var restResponse = Client.Get<List<WPUser>>(restRequest);
return restResponse.Data;
}
#endregion
#region Games
public List<Game> GetGames() public List<Game> GetGames()
{ {
var restRequest = new RestRequest("/api/Game", Method.GET); var restRequest = new RestRequest("/api/Game", Method.GET);
var restResponse = Client.Get<List<Game>>(restRequest); var restResponse = Client.Get<List<Game>>(restRequest);
return restResponse.Data; return restResponse.Data;
} }
public Game UpdateGame(Game eventUpdate)
{
return Post("Api/Game", eventUpdate);
}
#endregion
#region Events
#endregion
} }
} }

View File

@@ -0,0 +1,30 @@
<UserControl x:Class="LaDOSE.DesktopApp.UserControls.BookingUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:LaDOSE.DesktopApp.UserControls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
>
<UserControl.Resources>
</UserControl.Resources>
<Grid>
<ListView Grid.Row ="1" ItemsSource="{Binding Path=Reservation}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="Green" x:Name="Panel" VerticalAlignment="Stretch" >
<Label Content="{Binding Name}"></Label>
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Valid}" Value="False">
<Setter TargetName="Panel" Property="Background" Value="Red" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</UserControl>

View File

@@ -0,0 +1,75 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LaDOSE.DesktopApp.Utils;
using LaDOSE.DTO;
namespace LaDOSE.DesktopApp.UserControls
{
/// <summary>
/// Interaction logic for BookingUserControl.xaml
/// </summary>
public partial class BookingUserControl : UserControl
{
public readonly String[] EventManagerField = new[] {"HR3", "HR2", "COMMENT", "BOOKING_COMMENT"};
public String Current
{
get { return (String)GetValue(CurrentProperty); }
set { SetValue(CurrentProperty, value); }
}
// Using a DependencyProperty as the backing store for Current. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CurrentProperty =
DependencyProperty.Register("Current", typeof(String), typeof(BookingUserControl), new PropertyMetadata("",PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
BookingUserControl uc = d as BookingUserControl;
if (uc != null)
{
uc.Parse((string) e.NewValue);
}
}
public ObservableCollection<Reservation> Reservation { get; set; }
private void Parse(string value)
{
Reservation.Clear();
var games = WpEventDeserialize.Parse(value);
if (games != null) games.OrderBy(e => e.Name).ToList().ForEach(res => Reservation.Add(res));
}
public BookingUserControl()
{
InitializeComponent();
Reservation = new ObservableCollection<Reservation>();
this.DataContext = this;
}
}
}

View File

@@ -0,0 +1,214 @@
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace LaDOSE.DesktopApp.Utils
{
/// <summary>
/// PhpSerializer Class.
/// </summary>
public class PhpSerializer
{
private readonly NumberFormatInfo nfi;
private int pos; //for unserialize
private Dictionary<ArrayList, bool> seenArrayLists; //for serialize (to infinte prevent loops) lol
//types:
// N = null
// s = string
// i = int
// d = double
// a = array (hashtable)
private Dictionary<Hashtable, bool> seenHashtables; //for serialize (to infinte prevent loops)
//http://www.w3.org/TR/REC-xml/#sec-line-ends
public Encoding StringEncoding = new UTF8Encoding();
public bool
XMLSafe = true; //This member tells the serializer wether or not to strip carriage returns from strings when serializing and adding them back in when deserializing
public PhpSerializer()
{
nfi = new NumberFormatInfo();
nfi.NumberGroupSeparator = "";
nfi.NumberDecimalSeparator = ".";
}
public string Serialize(object obj)
{
seenArrayLists = new Dictionary<ArrayList, bool>();
seenHashtables = new Dictionary<Hashtable, bool>();
return Serialize(obj, new StringBuilder()).ToString();
} //Serialize(object obj)
private StringBuilder Serialize(object obj, StringBuilder sb)
{
if (obj == null) return sb.Append("N;");
if (obj is string)
{
var str = (string) obj;
if (XMLSafe)
{
str = str.Replace("\r\n", "\n"); //replace \r\n with \n
str = str.Replace("\r", "\n"); //replace \r not followed by \n with a single \n Should we do this?
}
return sb.Append("s:" + StringEncoding.GetByteCount(str) + ":\"" + str + "\";");
}
if (obj is bool) return sb.Append("b:" + ((bool) obj ? "1" : "0") + ";");
if (obj is int)
{
var i = (int) obj;
return sb.Append("i:" + i.ToString(nfi) + ";");
}
if (obj is double)
{
var d = (double) obj;
return sb.Append("d:" + d.ToString(nfi) + ";");
}
if (obj is ArrayList)
{
if (seenArrayLists.ContainsKey((ArrayList) obj))
return sb.Append("N;"); //cycle detected
seenArrayLists.Add((ArrayList) obj, true);
var a = (ArrayList) obj;
sb.Append("a:" + a.Count + ":{");
for (var i = 0; i < a.Count; i++)
{
Serialize(i, sb);
Serialize(a[i], sb);
}
sb.Append("}");
return sb;
}
if (obj is Hashtable)
{
if (seenHashtables.ContainsKey((Hashtable) obj))
return sb.Append("N;"); //cycle detected
seenHashtables.Add((Hashtable) obj, true);
var a = (Hashtable) obj;
sb.Append("a:" + a.Count + ":{");
foreach (DictionaryEntry entry in a)
{
Serialize(entry.Key, sb);
Serialize(entry.Value, sb);
}
sb.Append("}");
return sb;
}
return sb;
} //Serialize(object obj)
public object Deserialize(string str)
{
pos = 0;
return this.deserialize(str);
} //Deserialize(string str)
private object deserialize(string str)
{
if (str == null || str.Length <= pos)
return new object();
int start, end, length;
string stLen;
switch (str[pos])
{
case 'N':
pos += 2;
return null;
case 'b':
char chBool;
chBool = str[pos + 2];
pos += 4;
return chBool == '1';
case 'i':
string stInt;
start = str.IndexOf(":", pos) + 1;
end = str.IndexOf(";", start);
stInt = str.Substring(start, end - start);
pos += 3 + stInt.Length;
return int.Parse(stInt, nfi);
case 'd':
string stDouble;
start = str.IndexOf(":", pos) + 1;
end = str.IndexOf(";", start);
stDouble = str.Substring(start, end - start);
pos += 3 + stDouble.Length;
return double.Parse(stDouble, nfi);
case 's':
start = str.IndexOf(":", pos) + 1;
end = str.IndexOf(":", start);
stLen = str.Substring(start, end - start);
var bytelen = int.Parse(stLen);
length = bytelen;
//This is the byte length, not the character length - so we migth
//need to shorten it before usage. This also implies bounds checking
if (end + 2 + length >= str.Length) length = str.Length - 2 - end;
var stRet = str.Substring(end + 2, length);
while (StringEncoding.GetByteCount(stRet) > bytelen)
{
length--;
stRet = str.Substring(end + 2, length);
}
pos += 6 + stLen.Length + length;
if (XMLSafe) stRet = stRet.Replace("\n", "\r\n");
return stRet;
case 'a':
//if keys are ints 0 through N, returns an ArrayList, else returns Hashtable
start = str.IndexOf(":", pos) + 1;
end = str.IndexOf(":", start);
stLen = str.Substring(start, end - start);
length = int.Parse(stLen);
var htRet = new Hashtable(length);
var alRet = new ArrayList(length);
pos += 4 + stLen.Length; //a:Len:{
for (var i = 0; i < length; i++)
{
//read key
var key = deserialize(str);
//read value
var val = deserialize(str);
if (alRet != null)
{
if (key is int && (int) key == alRet.Count)
alRet.Add(val);
else
alRet = null;
}
htRet[key] = val;
}
pos++; //skip the }
if (pos < str.Length && str[pos] == ';'
) //skipping our old extra array semi-colon bug (er... php's weirdness)
pos++;
if (alRet != null)
return alRet;
else
return htRet;
default:
return "";
} //switch
} //unserialzie(object)
}
} //class PhpSerializer

View File

@@ -0,0 +1,44 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using LaDOSE.DesktopApp.UserControls;
namespace LaDOSE.DesktopApp.Utils
{
public class Reservation
{
public string Name { get; set; }
public bool Valid { get; set; }
}
public class WpEventDeserialize
{
public static readonly string[] EventManagerField = new[] { "HR3", "HR2", "COMMENT", "BOOKING_COMMENT" };
public static List<Reservation> Parse(string meta)
{
if (meta == null) return new List<Reservation>();
PhpSerializer p = new PhpSerializer();
var b = p.Deserialize(meta);
Hashtable Wpbook = b as Hashtable;
var games = new List<Reservation>();
if (Wpbook != null)
{
Hashtable reg2 = Wpbook["booking"] as Hashtable;
foreach (string reg2Key in reg2.Keys)
{
if (!EventManagerField.Contains(reg2Key.ToUpperInvariant()))
games.Add(new Reservation()
{
Name = reg2Key,
Valid = (string)reg2[reg2Key] == "1"
});
}
return games;
}
return null;
}
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Windows;
namespace LaDOSE.DesktopApp.Utils
{
public static class WpfUtil
{
public static void AddUI<T>(this ICollection<T> collection, T item)
{
Action<T> addMethod = collection.Add;
Application.Current.Dispatcher.BeginInvoke(addMethod, item);
}
}
}

View File

@@ -7,18 +7,54 @@ namespace LaDOSE.DesktopApp.ViewModels
{ {
public class GameViewModel : Screen public class GameViewModel : Screen
{ {
public override string DisplayName => "Games";
private Game _currentGame;
private List<Game> _games;
private RestService RestService { get; set; } private RestService RestService { get; set; }
public GameViewModel(RestService restService) public GameViewModel(RestService restService)
{ {
this.RestService = restService; this.RestService = restService;
this.Games=new List<Game>();
} }
public void LoadGames() public void LoadGames()
{ {
this.Games.Clear();
this.Games = this.RestService.GetGames(); this.Games = this.RestService.GetGames();
NotifyOfPropertyChange("Games"); NotifyOfPropertyChange("Games");
} }
public List<Game> Games { get; set; } public List<Game> Games
{
get => _games;
set
{
_games = value;
NotifyOfPropertyChange(()=>this.Games);
}
}
public Game CurrentGame
{
get => _currentGame;
set
{
_currentGame = value;
NotifyOfPropertyChange(()=>CurrentGame);
}
}
public void Update()
{
this.RestService.UpdateGame(this.CurrentGame);
this.Games = RestService.GetGames();
}
public void AddGame()
{
var item = new Game();
this.Games.Add(item);
this.CurrentGame = item;
}
} }
} }

View File

@@ -3,8 +3,16 @@ using LaDOSE.DesktopApp.Services;
namespace LaDOSE.DesktopApp.ViewModels namespace LaDOSE.DesktopApp.ViewModels
{ {
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive public class ShellViewModel : Conductor<IScreen>.Collection.AllActive
{ {
protected override void OnInitialize()
{
var wordPressViewModel = new WordPressViewModel(IoC.Get<RestService>());
ActivateItem(wordPressViewModel);
base.OnInitialize();
}
public void LoadEvent() public void LoadEvent()
{ {
@@ -14,5 +22,6 @@ namespace LaDOSE.DesktopApp.ViewModels
{ {
ActivateItem(new GameViewModel(IoC.Get<RestService>())); ActivateItem(new GameViewModel(IoC.Get<RestService>()));
} }
} }
} }

View File

@@ -1,24 +1,184 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Caliburn.Micro; using Caliburn.Micro;
using LaDOSE.DesktopApp.Services; using LaDOSE.DesktopApp.Services;
using LaDOSE.DesktopApp.Utils;
using LaDOSE.DTO; using LaDOSE.DTO;
using Action = System.Action;
namespace LaDOSE.DesktopApp.ViewModels namespace LaDOSE.DesktopApp.ViewModels
{ {
public class WordPressViewModel : Screen public class WordPressViewModel : Screen
{ {
public override string DisplayName => "Events";
private WPEvent _selectedWpEvent;
private Game _selectedGame;
private ObservableCollection<WPUser> _players;
private ObservableCollection<WPUser> _playersOptions;
private RestService RestService { get; set; } private RestService RestService { get; set; }
public WordPressViewModel(RestService restService) public WordPressViewModel(RestService restService)
{ {
this.RestService = restService; this.RestService = restService;
Players = new ObservableCollection<WPUser>();
PlayersOptions = new ObservableCollection<WPUser>();
} }
public void LoadEvents() public void LoadEvents()
{ {
this.Events = this.RestService.GetEvents(); Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
NotifyOfPropertyChange("Events"); var tsk = Task.Factory.StartNew(Load);
tsk.ContinueWith(t =>
{
MessageBox.Show(t.Exception.InnerException.Message);
Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
},
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
} }
private void Load()
{
GamesFound = new ObservableCollection<Game>();
this.Games = this.RestService.GetGames();
this.Events = this.RestService.GetEvents();
NotifyOfPropertyChange("Events");
Application.Current.Dispatcher.Invoke(() =>
System.Windows.Input.Mouse.OverrideCursor = null);
}
public bool CanGenerate
{
get { return SelectedWpEvent != null && SelectedGame != null; }
}
public List<WPEvent> Events { get; set; } public List<WPEvent> Events { get; set; }
public WPEvent SelectedWpEvent
{
get => _selectedWpEvent;
set
{
_selectedWpEvent = value;
SelectedGame = null;
ParseGame(_selectedWpEvent);
}
}
public Game SelectedGame
{
get => _selectedGame;
set
{
_selectedGame = value;
Players.Clear();
PlayersOptions.Clear();
Task.Factory.StartNew(LoadPlayers,TaskCreationOptions.LongRunning).ContinueWith(t =>
{
},
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
NotifyOfPropertyChange(() => SelectedGame);
NotifyOfPropertyChange(() => this.CanGenerate);
NotifyOfPropertyChange(() => Players);
NotifyOfPropertyChange(() => PlayersOptions);
}
}
public ObservableCollection<WPUser> Players
{
get => _players;
set
{
_players = value;
NotifyOfPropertyChange(()=>Players);
}
}
public ObservableCollection<WPUser> PlayersOptions
{
get => _playersOptions;
set
{
_playersOptions = value;
NotifyOfPropertyChange(() => PlayersOptions);
}
}
public ObservableCollection<Game> GamesFound { get; set; }
public List<Game> Games { get; set; }
private void ParseGame(WPEvent selectedWpEvent)
{
var reservation = SelectedWpEvent.WpBookings.FirstOrDefault();
var games = WpEventDeserialize.Parse(reservation.Meta);
GamesFound.Clear();
if (games != null)
{
foreach (string wpTag in games.Select(e => e.Name))
{
var foundGame = Games.FirstOrDefault(e =>
e.WordPressTag != null && e.WordPressTag.Split(';').Contains(wpTag));
if (foundGame != null)
{
if (!GamesFound.Contains(foundGame))
{
GamesFound.Add(foundGame);
}
}
}
}
NotifyOfPropertyChange(() => GamesFound);
}
private void LoadPlayers()
{
if (SelectedWpEvent != null)
if (SelectedGame != null)
{
this.RestService.GetUsers(SelectedWpEvent.Id, SelectedGame.Id).ForEach((e) => this.Players.AddUI(e));
this.RestService.GetUsersOptions(SelectedWpEvent.Id, SelectedGame.Id).ForEach((e) => this.PlayersOptions.AddUI(e));
}
}
public void UpdateDb()
{
if (this.RestService.RefreshDb())
MessageBox.Show("DataBaseUpdated");
else
MessageBox.Show("Update Failed");
}
public void Generate()
{
if (this.RestService.CreateChallonge(SelectedGame.Id, SelectedWpEvent.Id))
MessageBox.Show("Challonge Created");
else
MessageBox.Show("Didn't worl :(");
}
} }
} }

View File

@@ -14,17 +14,47 @@
<RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Button Grid.Row="0" x:Name="LoadGames">Load Games</Button> <Button Grid.Row="0" x:Name="LoadGames">Load Games</Button>
<ListView Grid.Row="1" ItemsSource="{Binding Games}">
<ListView Grid.Row="1" ItemsSource="{Binding Games}" x:Name="GamesListView" SelectedItem="{Binding CurrentGame}">
<ListView.ItemTemplate> <ListView.ItemTemplate>
<DataTemplate> <DataTemplate>
<StackPanel> <StackPanel Orientation="Horizontal">
<Label Content="{Binding Id}"></Label> <Label Content="{Binding Id}"></Label>
<Label> - </Label>
<Label Content="{Binding Name}"></Label> <Label Content="{Binding Name}"></Label>
<Label Content="{Binding ImgUrl}"></Label>
</StackPanel> </StackPanel>
</DataTemplate> </DataTemplate>
</ListView.ItemTemplate> </ListView.ItemTemplate>
</ListView> </ListView>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" Grid.ColumnSpan="2" x:Name="AddGame">Add Games</Button>
<Label Grid.Row="1" Grid.Column="0">Id</Label>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=CurrentGame.Id,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True"></TextBox>
<Label Grid.Row="2" Grid.Column="0">Name</Label>
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=CurrentGame.Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></TextBox>
<Label Grid.Row="3" Grid.Column="0">WpTag</Label>
<TextBox Grid.Row="4" Grid.ColumnSpan="2" Text="{Binding Path=CurrentGame.WordPressTag,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></TextBox>
<Label Grid.Row="5" Grid.Column="0">WpTagOs</Label>
<TextBox Grid.Row="6" Grid.ColumnSpan="2" Text="{Binding Path=CurrentGame.WordPressTagOs,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></TextBox>
<Button Grid.Row="7" Grid.ColumnSpan="2" x:Name="Update">Update</Button>
</Grid>
</Grid> </Grid>
</UserControl> </UserControl>

View File

@@ -35,8 +35,18 @@
<MenuItem Header="_Close" /> <MenuItem Header="_Close" />
</MenuItem> </MenuItem>
</Menu> </Menu>
<ContentControl Grid.Row="1" x:Name="ActiveItem" />
<TabControl Grid.Row="1" x:Name="Items">
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding DisplayName}" />
<Button Content="X"
cal:Message.Attach="DeactivateItem($dataContext,'true')" />
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
<StatusBar Grid.Row="2"> <StatusBar Grid.Row="2">

View File

@@ -4,27 +4,128 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:LaDOSE.DesktopApp.Views" xmlns:local="clr-namespace:LaDOSE.DesktopApp.Views"
xmlns:userControls="clr-namespace:LaDOSE.DesktopApp.UserControls"
xmlns:cal="http://www.caliburnproject.org"
mc:Ignorable="d" mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"> d:DesignHeight="450" d:DesignWidth="800">
<Grid Row="4" Column="1"> <Grid Row="4" Column="2">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto" />
<RowDefinition Height="*"></RowDefinition> <RowDefinition Height="*" />
<RowDefinition Height="*"></RowDefinition> <RowDefinition Height="*" />
<RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Button Grid.Row="0" x:Name="LoadEvents">Load Events</Button> <Grid.ColumnDefinitions>
<ListView Grid.Row="1" ItemsSource="{Binding Events}"> <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<DockPanel Grid.Row="0">
<Button x:Name="UpdateDb">Update DB</Button>
<Button x:Name="LoadEvents">Load Events</Button>
</DockPanel>
<ListView Grid.Row="1" ItemsSource="{Binding Events}" x:Name="EventsList"
SelectedItem="{Binding SelectedWpEvent, Mode=TwoWay}">
<ListView.ItemTemplate> <ListView.ItemTemplate>
<DataTemplate> <DataTemplate>
<StackPanel> <StackPanel Orientation="Horizontal">
<Label Content="{Binding Id}"></Label> <Label Content="{Binding Id}" />
<Label Content="{Binding Name}"></Label> <Label Content="{Binding Name}" />
<Label Content="{Binding Date}"></Label> <Label Content="{Binding Date}" />
</StackPanel> </StackPanel>
</DataTemplate> </DataTemplate>
</ListView.ItemTemplate> </ListView.ItemTemplate>
</ListView> </ListView>
<Grid Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ListView Grid.Column="0" ItemsSource="{Binding ElementName=EventsList,Path=SelectedItem.WpBookings}"
x:Name="BookingList">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding WpUser.Name}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30" />
<RowDefinition Height="60" />
</Grid.RowDefinitions>
<userControls:BookingUserControl Grid.Row="0"
Current="{Binding ElementName=BookingList,Path=SelectedItem.Meta,UpdateSourceTrigger=PropertyChanged}" />
<Label Grid.Row="1">Message</Label>
<TextBox Grid.Row="2" IsReadOnly="True" Text="{Binding ElementName=BookingList,Path=SelectedItem.Message}" TextWrapping="Wrap" AcceptsReturn="False" VerticalScrollBarVisibility="Auto" />
</Grid>
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" cal:Message.Attach="Generate">Generate</Button>
<ListView Grid.Row="1" x:Name="GameFoundListView" ItemsSource="{Binding GamesFound}"
SelectedItem="{Binding SelectedGame,UpdateSourceTrigger=PropertyChanged}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Orientation="Horizontal">
<Label>Registred Players (</Label>
<Label Content="{Binding Players.Count,UpdateSourceTrigger=PropertyChanged}"></Label>
<Label>)</Label>
</StackPanel>
<ListView Grid.Row="1" Grid.Column="0" x:Name="PlayersList" ItemsSource="{Binding Players,UpdateSourceTrigger=PropertyChanged}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal">
<Label>Optional Players (</Label>
<Label Content="{Binding PlayersOptions.Count,UpdateSourceTrigger=PropertyChanged}"></Label>
<Label>)</Label>
</StackPanel>
<ListView Grid.Row="1" Grid.Column="1" x:Name="PlayersOptionsList" ItemsSource="{Binding PlayersOptions,UpdateSourceTrigger=PropertyChanged}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Grid>
</Grid>
</Grid> </Grid>
</UserControl> </UserControl>

View File

@@ -24,5 +24,7 @@ namespace LaDOSE.DesktopApp.Views
{ {
InitializeComponent(); InitializeComponent();
} }
} }
} }

View File

@@ -8,7 +8,8 @@ namespace LaDOSE.Entity
{ {
public string Name { get; set; } public string Name { get; set; }
public string ImgUrl { get; set; } public string ImgUrl { get; set; }
public string WordPressTag { get; set; }
public string WordPressTagOs { get; set; }
public virtual IEnumerable<SeasonGame> Seasons { get; set; } public virtual IEnumerable<SeasonGame> Seasons { get; set; }
public virtual IEnumerable<EventGame> Events { get; set; } public virtual IEnumerable<EventGame> Events { get; set; }

View File

@@ -0,0 +1,8 @@
namespace LaDOSE.Business.Helper
{
public class Reservation
{
public string Name { get; set; }
public bool Valid { get; set; }
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace LaDOSE.Business.Helper
{
public static class WpEventDeserialize
{
public static readonly List<String> EventManagerField =new List<string>(new []{"HR3", "HR2", "COMMENT", "BOOKING_COMMENT"});
public static List<Reservation> Parse(string meta)
{
if (meta == null) return new List<Reservation>();
PhpSerializer p = new PhpSerializer();
var b = p.Deserialize(meta);
Hashtable Wpbook = b as Hashtable;
var games = new List<Reservation>();
if (Wpbook != null)
{
Hashtable reg2 = Wpbook["booking"] as Hashtable;
foreach (string reg2Key in reg2.Keys)
{
if (!EventManagerField.Contains(reg2Key.ToUpperInvariant()))
games.Add(new Reservation()
{
Name = reg2Key,
Valid = (string)reg2[reg2Key] == "1"
});
}
return games;
}
return null;
}
}
}

View File

@@ -9,5 +9,7 @@ namespace LaDOSE.Business.Interface
T Create(T entity); T Create(T entity);
bool Update(T entity); bool Update(T entity);
bool Delete(int id); bool Delete(int id);
T AddOrUpdate(T entity);
} }
} }

View File

@@ -6,7 +6,7 @@ namespace LaDOSE.Business.Interface
{ {
public interface IEventService : IBaseService<Event> public interface IEventService : IBaseService<Event>
{ {
bool CreateChallonge(int eventId, int wpEventId);
List<WPUser> GetBooking(int eventId, int wpEventId, Game game);
} }
} }

View File

@@ -1,7 +0,0 @@
namespace LaDOSE.Business.Interface
{
public interface IUtilService
{
bool UpdateBooking();
}
}

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using LaDOSE.Entity;
using LaDOSE.Entity.Wordpress; using LaDOSE.Entity.Wordpress;
namespace LaDOSE.Business.Interface namespace LaDOSE.Business.Interface
@@ -6,5 +7,9 @@ namespace LaDOSE.Business.Interface
public interface IWordPressService public interface IWordPressService
{ {
List<WPEvent> GetWpEvent(); List<WPEvent> GetWpEvent();
List<WPUser> GetBooking(int wpEventId, Game game);
List<WPUser> GetBookingOptions(int wpEventId, Game game);
bool UpdateBooking();
bool CreateChallonge(int gameId, int wpEventId);
} }
} }

View File

@@ -3,10 +3,11 @@ using System.Linq;
using LaDOSE.Business.Interface; using LaDOSE.Business.Interface;
using LaDOSE.Entity.Context; using LaDOSE.Entity.Context;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace LaDOSE.Business.Service namespace LaDOSE.Business.Service
{ {
public class BaseService<T> : IBaseService<T> where T : class public class BaseService<T> : IBaseService<T> where T : Entity.Context.Entity
{ {
protected LaDOSEDbContext _context; protected LaDOSEDbContext _context;
@@ -43,5 +44,21 @@ namespace LaDOSE.Business.Service
_context.Remove(find); _context.Remove(find);
return _context.Entry(find).State == EntityState.Deleted; return _context.Entry(find).State == EntityState.Deleted;
} }
public virtual T AddOrUpdate(T entity)
{
EntityEntry<T> entityEntry;
if (entity.Id == 0)
{
entityEntry = this._context.Add(entity);
}
else
{
entityEntry = this._context.Update(entity);
}
this._context.SaveChanges();
return entityEntry.Entity;
}
} }
} }

View File

@@ -22,7 +22,8 @@ namespace LaDOSE.Business.Service
public override Event GetById(int id) public override Event GetById(int id)
{ {
return _context.Event.Include(e=>e.Season).Include(e=>e.Games).ThenInclude(e=>e.Game).FirstOrDefault(e=>e.Id == id); return _context.Event.Include(e => e.Season).Include(e => e.Games).ThenInclude(e => e.Game)
.FirstOrDefault(e => e.Id == id);
} }
public override Event Create(Event e) public override Event Create(Event e)
@@ -37,71 +38,5 @@ namespace LaDOSE.Business.Service
return eventAdded.Entity; return eventAdded.Entity;
} }
public List<WPUser> GetBooking(int eventId, int wpEventId,Game game)
{
var currentEvent = _context.Event.Include(e => e.Games).ThenInclude(e => e.Game).FirstOrDefault(e => e.Id == eventId);
var currentWpEvent = _context.WPEvent.Include(e => e.WPBookings).ThenInclude(e => e.WPUser).Where(e => e.Id == wpEventId).ToList();
List<WPBooking> bookings = currentWpEvent.SelectMany(e => e.WPBookings).ToList();
List<WPUser> users = new List<WPUser>();
foreach (var booking in bookings)
{
PhpSerializer p = new PhpSerializer();
var b = p.Deserialize(booking.Meta);
Hashtable Wpbook = b as Hashtable;
Hashtable reg = Wpbook["registration"] as Hashtable;
Hashtable reg2 = Wpbook["booking"] as Hashtable;
if (reg2.ContainsKey(game.Name) && ((string)reg2[game.Name]) == "1")
{
booking.WPUser.WPBookings = null;
users.Add(booking.WPUser);
}
}
return users;
}
public bool CreateChallonge(int eventId,int wpEventId)
{
var currentEvent = _context.Event.Include(e=>e.Games).ThenInclude(e=>e.Game).FirstOrDefault(e=>e.Id == eventId);
var currentWpEvent = _context.WPEvent.Include(e => e.WPBookings).ThenInclude(e => e.WPUser).Where(e=>e.Id == wpEventId);
var users = currentWpEvent.SelectMany(e => e.WPBookings.Select(u => u.WPUser));
var userNames = users.Select(e => e.Name).Distinct().ToList();
if (currentEvent != null)
{
var games = currentEvent.Games.Select(e => e.Game);
var s = currentEvent.Date.ToString("MM/dd/yy");
foreach (var game in games)
{
var url = $"TestDev{game.Id}{game.Name}";
var name = $"[{s}]Ranking {currentEvent.Name}{game.Name}";
var tournament = _challongeProvider.CreateTournament(name,url).Result;
var eventGame = currentEvent.Games.FirstOrDefault(e => e.GameId == game.Id);
eventGame.ChallongeId = tournament.id;
eventGame.ChallongeUrl = tournament.url;
foreach (var userName in userNames)
{
try
{
_challongeProvider.AddPlayer(tournament.id, userName);
}
catch
{
Console.WriteLine($"Erreur d ajout sur {userName}" );
continue;
}
}
_context.Entry(eventGame).State = EntityState.Modified;
}
_context.SaveChanges();
return true;
}
return false;
}
} }
} }

View File

@@ -1,24 +0,0 @@
using LaDOSE.Business.Interface;
using LaDOSE.Entity.Context;
using Microsoft.EntityFrameworkCore;
namespace LaDOSE.Business.Service
{
public class UtilService : IUtilService
{
private LaDOSEDbContext _context;
public UtilService(LaDOSEDbContext context)
{
_context = context;
}
public bool UpdateBooking()
{
_context.Database.SetCommandTimeout(60);
_context.Database.ExecuteSqlCommand("call ladoseapi.ImportEvent();");
_context.Database.SetCommandTimeout(30);
return true;
}
}
}

View File

@@ -1,22 +1,136 @@
using System.Collections.Generic; using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using LaDOSE.Business.Helper;
using LaDOSE.Business.Interface; using LaDOSE.Business.Interface;
using LaDOSE.Entity;
using LaDOSE.Entity.Context; using LaDOSE.Entity.Context;
using LaDOSE.Entity.Wordpress; using LaDOSE.Entity.Wordpress;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace LaDOSE.Business.Service namespace LaDOSE.Business.Service
{ {
public class WordPressService : IWordPressService public class WordPressService : IWordPressService
{ {
private LaDOSEDbContext _context; private LaDOSEDbContext _context;
public WordPressService(LaDOSEDbContext context) private IChallongeProvider _challongeProvider;
public WordPressService(LaDOSEDbContext context, IChallongeProvider challongeProvider)
{ {
this._context = context; this._context = context;
this._challongeProvider = challongeProvider;
} }
public List<WPEvent> GetWpEvent() public List<WPEvent> GetWpEvent()
{ {
return _context.Set<WPEvent>().ToList(); var wpEvents = _context.Set<WPEvent>().OrderByDescending(e => e.Id).Include(e => e.WPBookings)
.ThenInclude(e => e.WPUser).Where(e => e.WPBookings.Count() != 0).Take(10).ToList();
return wpEvents;
}
public bool UpdateBooking()
{
_context.Database.SetCommandTimeout(60);
_context.Database.ExecuteSqlCommand("call ladoseapi.ImportEvent();");
_context.Database.SetCommandTimeout(30);
return true;
}
public List<WPUser> GetBooking(int wpEventId, Game game)
{
var selectedGameWpId = game.WordPressTag.Split(';');
var currentWpEvent = _context.WPEvent.Include(e => e.WPBookings).ThenInclude(e => e.WPUser).Where(e => e.Id == wpEventId).ToList();
List<WPBooking> bookings = currentWpEvent.SelectMany(e => e.WPBookings).ToList();
List<WPUser> users = new List<WPUser>();
foreach (var booking in bookings)
{
var reservations = WpEventDeserialize.Parse(booking.Meta);
if (reservations != null)
{
var gamesReservation = reservations.Where(e => e.Valid).Select(e => e.Name);
if (selectedGameWpId.Any(e => gamesReservation.Contains(e)))
{
users.Add(booking.WPUser);
}
}
}
return users;
}
public List<WPUser> GetBookingOptions(int wpEventId, Game game)
{
var selectedGameWpId = game.WordPressTagOs.Split(';');
var currentWpEvent = _context.WPEvent.Include(e => e.WPBookings).ThenInclude(e => e.WPUser).Where(e => e.Id == wpEventId).ToList();
List<WPBooking> bookings = currentWpEvent.SelectMany(e => e.WPBookings).ToList();
List<WPUser> users = new List<WPUser>();
foreach (var booking in bookings)
{
var reservations = WpEventDeserialize.Parse(booking.Meta);
if (reservations != null)
{
var gamesReservation = reservations.Where(e => e.Valid).Select(e => e.Name);
if (selectedGameWpId.Any(e => gamesReservation.Contains(e)))
{
users.Add(booking.WPUser);
}
}
}
return users;
}
public bool CreateChallonge(int gameId, int wpEventId)
{
var selectedGame = _context.Game.FirstOrDefault(e => e.Id == gameId);
var selectedGameWpId = selectedGame.WordPressTag.Split(';');
var currentWpEvent = _context.WPEvent.Include(e => e.WPBookings).ThenInclude(e => e.WPUser)
.Where(e => e.Id == wpEventId);
var users = currentWpEvent.SelectMany(e => e.WPBookings.Select(u => u.WPUser));
if (selectedGame != null)
{
var currentEvent = currentWpEvent.FirstOrDefault();
var eventDate = currentEvent.Date?.ToString("MM/dd/yy");
var remove = currentEvent.Date?.ToString("Mdyy");
var url = $"{remove}{selectedGame.Id}";
var name = $"[{eventDate}]Ranking {currentEvent.Name} {selectedGame.Name}";
var tournament = _challongeProvider.CreateTournament(name, url).Result;
foreach (var booking in currentEvent.WPBookings)
{
var reservations = WpEventDeserialize.Parse(booking.Meta);
if (reservations != null)
{
var gamesReservation = reservations.Where(e=>e.Valid).Select(e=>e.Name);
if(selectedGameWpId.Any(e => gamesReservation.Contains(e)))
{
try
{
_challongeProvider.AddPlayer(tournament.id, booking.WPUser.Name);
}
catch
{
Console.WriteLine($"Erreur d ajout sur {booking.WPUser.Name}");
continue;
}
}
}
}
return true;
}
return false;
} }
} }
} }