in order to use EF7 commands
This commit is contained in:
31
Yavsc/Helpers/BillingHelpers.cs
Normal file
31
Yavsc/Helpers/BillingHelpers.cs
Normal file
@ -0,0 +1,31 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Yavsc.Abstract.FileSystem;
|
||||
using Yavsc.Billing;
|
||||
using Yavsc.Models.Billing;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
public static class BillingHelpers
|
||||
{
|
||||
public static decimal Addition(this List<IBillItem> items) => items.Aggregate<IBillItem, decimal>(0m, (t, l) => t + l.Count * l.UnitaryCost);
|
||||
|
||||
public static decimal Addition(this List<CommandLine> items) => items.Select(i=>((IBillItem)i)).ToList().Addition();
|
||||
|
||||
public static string GetBillText(this IBillable query) {
|
||||
string total = query.GetBillItems().Addition().ToString("C", CultureInfo.CurrentUICulture);
|
||||
string bill = string.Join("\n", query.GetBillItems().Select(l=> $"{l.Name} {l.Description} : {l.UnitaryCost} € " + ((l.Count != 1) ? "*"+l.Count.ToString() : ""))) +
|
||||
$"\n\nTotal: {total}";
|
||||
return bill;
|
||||
}
|
||||
|
||||
public static FileInfo GetBillInfo(this IBillable bill)
|
||||
{
|
||||
var suffix = bill.GetIsAcquitted() ? "-ack":null;
|
||||
var filename = bill.GetFileBaseName()+".pdf";
|
||||
return new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
|
||||
}
|
||||
}
|
||||
}
|
21
Yavsc/Helpers/CompanyInfoHelpers.cs
Normal file
21
Yavsc/Helpers/CompanyInfoHelpers.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
using Models.societe.com;
|
||||
public static class ComapnyInfoHelpers {
|
||||
public static async Task<CompanyInfoMessage> CheckSiren(this HttpClient web,
|
||||
string siren, CompanyInfoSettings api)
|
||||
{
|
||||
using (var request = new HttpRequestMessage(HttpMethod.Get,
|
||||
string.Format(Constants.CompanyInfoUrl,siren,api.ApiKey))) {
|
||||
using (var response = await web.SendAsync(request)) {
|
||||
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
|
||||
return payload.ToObject<CompanyInfoMessage>();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
9
Yavsc/Helpers/DbHelpers.cs
Normal file
9
Yavsc/Helpers/DbHelpers.cs
Normal file
@ -0,0 +1,9 @@
|
||||
namespace Yavsc.Server.Helpers
|
||||
{
|
||||
public static class DbHelpers
|
||||
{
|
||||
// FIXME BUG [fr] DependencyInjection Pourquoi ce champ ne pourrait pas devenir une propriété ?
|
||||
// : casse à l'execution d'un controlleur, se plaignant d'une valeur nule
|
||||
public static string ConnectionString = "Server=Your-Server-Adress;Port=5432;Database=YourDadabaseName;Username=YourDatabaseUserName;Password=YourPassword;";
|
||||
}
|
||||
}
|
129
Yavsc/Helpers/GoogleHelpers.cs
Normal file
129
Yavsc/Helpers/GoogleHelpers.cs
Normal file
@ -0,0 +1,129 @@
|
||||
//
|
||||
// GoogleHelpers.cs
|
||||
//
|
||||
// Author:
|
||||
// Paul Schneider <paul@pschneider.fr>
|
||||
//
|
||||
// Copyright (c) 2015 GNU GPL
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.AspNet.Identity.EntityFramework;
|
||||
|
||||
using Google.Apis.Auth.OAuth2;
|
||||
using Google.Apis.Services;
|
||||
using Google.Apis.Compute.v1;
|
||||
using Google.Apis.Auth.OAuth2.Flows;
|
||||
using Google.Apis.Util.Store;
|
||||
using Google.Apis.Auth.OAuth2.Responses;
|
||||
using Google.Apis.Util;
|
||||
|
||||
namespace Yavsc.Helpers
|
||||
{
|
||||
using Models;
|
||||
using Models.Calendar;
|
||||
using Services;
|
||||
using Server.Helpers;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Google helpers.
|
||||
/// </summary>
|
||||
public static class GoogleHelpers
|
||||
{
|
||||
|
||||
|
||||
|
||||
public static async Task<GoogleCredential> GetCredentialForApi(IEnumerable<string> scopes)
|
||||
{
|
||||
GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
|
||||
var baseClientService = new BaseClientService.Initializer()
|
||||
{
|
||||
HttpClientInitializer = credential
|
||||
};
|
||||
var compute = new ComputeService(new BaseClientService.Initializer()
|
||||
{
|
||||
HttpClientInitializer = credential
|
||||
});
|
||||
if (credential.IsCreateScopedRequired)
|
||||
{
|
||||
credential = credential.CreateScoped(scopes);
|
||||
}
|
||||
return credential;
|
||||
}
|
||||
public static async Task<IdentityUserLogin<string>> GetGoogleUserLoginAsync(
|
||||
this ApplicationDbContext context,
|
||||
string yavscUserId)
|
||||
{
|
||||
var user = context.Users.FirstOrDefaultAsync(u=>u.Id==yavscUserId);
|
||||
if (user==null) return null;
|
||||
var googleLogin = await context.UserLogins.FirstOrDefaultAsync(
|
||||
x => x.UserId == yavscUserId && x.LoginProvider == "Google"
|
||||
);
|
||||
return googleLogin;
|
||||
}
|
||||
public static async Task<UserCredential> GetGoogleCredential(GoogleAuthSettings googleAuthSettings, IDataStore store, string googleUserLoginKey)
|
||||
{
|
||||
if (string.IsNullOrEmpty(googleUserLoginKey))
|
||||
throw new InvalidOperationException("No Google login");
|
||||
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer());
|
||||
var token = await store.GetAsync<TokenResponse>(googleUserLoginKey);
|
||||
// token != null
|
||||
var c = SystemClock.Default;
|
||||
if (token.IsExpired(c)) {
|
||||
token = await RefreshToken(googleAuthSettings, token);
|
||||
}
|
||||
return new UserCredential(flow, googleUserLoginKey, token);
|
||||
}
|
||||
public static async Task<Period[]> GetFreeTime (this ICalendarManager manager, string calId, DateTime startDate, DateTime endDate)
|
||||
{
|
||||
var evlist = await manager.GetCalendarAsync(calId, startDate, endDate, null) ;
|
||||
var result = evlist.Items
|
||||
.Where(
|
||||
ev => ev.Transparency == "transparent"
|
||||
)
|
||||
.Select(
|
||||
ev => new Period {
|
||||
Start = ev.Start.DateTime.Value,
|
||||
End = ev.End.DateTime.Value
|
||||
}
|
||||
);
|
||||
return result.ToArray();
|
||||
}
|
||||
|
||||
public static async Task<TokenResponse> RefreshToken(this GoogleAuthSettings settings, TokenResponse oldResponse)
|
||||
{
|
||||
string ep = " https://www.googleapis.com/oauth2/v4/token";
|
||||
// refresh_token client_id client_secret grant_type=refresh_token
|
||||
try {
|
||||
using (var m = new SimpleJsonPostMethod(ep)) {
|
||||
return await m.Invoke<TokenResponse>(
|
||||
new { refresh_token= oldResponse.RefreshToken, client_id=settings.ClientId,
|
||||
client_secret=settings.ClientSecret,
|
||||
grant_type="refresh_token" }
|
||||
);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new Exception ("Quelque chose s'est mal passé à l'envoi",ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
139
Yavsc/Helpers/RequestHelper.cs
Normal file
139
Yavsc/Helpers/RequestHelper.cs
Normal file
@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Yavsc.Server.Model;
|
||||
|
||||
namespace Yavsc.Server.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Thanks to Stefan @ Stackoverflow
|
||||
/// </summary>
|
||||
public class RequestHelper
|
||||
{
|
||||
string WRPostMultipart(string url, Dictionary<string, object> parameters, string authorizationHeader = null)
|
||||
{
|
||||
|
||||
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
|
||||
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
|
||||
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.ContentType = "multipart/form-data; boundary=" + boundary;
|
||||
request.Method = "POST";
|
||||
request.KeepAlive = true;
|
||||
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
|
||||
if (authorizationHeader != null)
|
||||
request.Headers["Authorization"] = authorizationHeader;
|
||||
if (parameters != null && parameters.Count > 0)
|
||||
{
|
||||
|
||||
using (Stream requestStream = request.GetRequestStream())
|
||||
{
|
||||
using (WebResponse response = request.GetResponse())
|
||||
{
|
||||
|
||||
|
||||
foreach (KeyValuePair<string, object> pair in parameters)
|
||||
{
|
||||
|
||||
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
|
||||
if (pair.Value is FormFile)
|
||||
{
|
||||
FormFile file = pair.Value as FormFile;
|
||||
string header = "Content-Disposition: form-data; name=\"" + pair.Key + "\"; filename=\"" + file.Name + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
|
||||
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
|
||||
requestStream.Write(bytes, 0, bytes.Length);
|
||||
byte[] buffer = new byte[32768];
|
||||
int bytesRead;
|
||||
if (file.Stream == null)
|
||||
{
|
||||
// upload from file
|
||||
using (FileStream fileStream = File.OpenRead(file.FilePath))
|
||||
{
|
||||
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
|
||||
requestStream.Write(buffer, 0, bytesRead);
|
||||
fileStream.Close();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// upload from given stream
|
||||
while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
|
||||
requestStream.Write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
|
||||
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
|
||||
requestStream.Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
|
||||
requestStream.Write(trailer, 0, trailer.Length);
|
||||
requestStream.Close();
|
||||
|
||||
using (Stream responseStream = response.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(responseStream))
|
||||
{
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
} // end WebResponse response
|
||||
|
||||
} // end using requestStream
|
||||
|
||||
}
|
||||
else throw new ArgumentOutOfRangeException("no parameter found ");
|
||||
|
||||
}
|
||||
|
||||
public static async Task<string> PostMultipart(string url, FormFile[] formFiles, string access_token = null)
|
||||
{
|
||||
|
||||
if (formFiles != null && formFiles.Length > 0)
|
||||
{
|
||||
var client = new HttpClient();
|
||||
var formData = new MultipartFormDataContent();
|
||||
|
||||
if (access_token != null)
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
|
||||
foreach (var formFile in formFiles)
|
||||
{
|
||||
HttpContent fileStreamContent = new StreamContent(formFile.Stream);
|
||||
if (formFile.ContentType!=null)
|
||||
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(formFile.ContentType);
|
||||
else fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
|
||||
// fileStreamContent.Headers.ContentDisposition = formFile.ContentDisposition!=null? new ContentDispositionHeaderValue(
|
||||
// formFile.ContentDisposition) : new ContentDispositionHeaderValue("form-data; name=\"file\"; filename=\"" + formFile.Name + "\"");
|
||||
fileStreamContent.Headers.Add("Content-Disposition", formFile.ContentDisposition);
|
||||
fileStreamContent.Headers.Add("Content-Length", formFile.Stream.Length.ToString());
|
||||
|
||||
//fileStreamContent.Headers.Add("FilePath", formFile.FilePath);
|
||||
|
||||
formData.Add(fileStreamContent, "file", formFile.Name);
|
||||
|
||||
}
|
||||
|
||||
var response = client.PostAsync(url, formData).Result;
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
} // end if formFiles != null
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
8
Yavsc/Helpers/ResourcesHelpers.cs
Normal file
8
Yavsc/Helpers/ResourcesHelpers.cs
Normal file
@ -0,0 +1,8 @@
|
||||
using System;
|
||||
using System.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
public static class ResourcesHelpers {
|
||||
public static IStringLocalizer GlobalLocalizer = null ;
|
||||
|
||||
}
|
99
Yavsc/Helpers/SimpleJsonPostMethod.cs
Normal file
99
Yavsc/Helpers/SimpleJsonPostMethod.cs
Normal file
@ -0,0 +1,99 @@
|
||||
//
|
||||
// PostJson.cs
|
||||
//
|
||||
// Author:
|
||||
// Paul Schneider <paulschneider@free.fr>
|
||||
//
|
||||
// Copyright (c) 2015 Paul Schneider
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
using System.Net;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Json;
|
||||
|
||||
namespace Yavsc.Server.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Simple json post method.
|
||||
/// </summary>
|
||||
public class SimpleJsonPostMethod : IDisposable
|
||||
{
|
||||
private HttpWebRequest request=null;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the Yavsc.Helpers.SimpleJsonPostMethod class.
|
||||
/// </summary>
|
||||
/// <param name="pathToMethod">Path to method.</param>
|
||||
public SimpleJsonPostMethod (string pathToMethod, string authorizationHeader = null, string method = "POST")
|
||||
{
|
||||
request = (HttpWebRequest) WebRequest.Create (pathToMethod);
|
||||
request.Method = method;
|
||||
request.Accept = "application/json";
|
||||
request.ContentType = "application/json";
|
||||
request.SendChunked = true;
|
||||
request.TransferEncoding = "UTF-8";
|
||||
if (authorizationHeader!=null)
|
||||
request.Headers["Authorization"]=authorizationHeader;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
request.Abort();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoke the specified query.
|
||||
/// </summary>
|
||||
/// <param name="query">Query.</param>
|
||||
public async Task<TAnswer> Invoke<TAnswer>(object query)
|
||||
{
|
||||
|
||||
using (Stream streamQuery = await request.GetRequestStreamAsync()) {
|
||||
using (StreamWriter writer = new StreamWriter(streamQuery)) {
|
||||
writer.Write (JsonConvert.SerializeObject(query));
|
||||
}}
|
||||
TAnswer ans = default (TAnswer);
|
||||
using (WebResponse response = await request.GetResponseAsync ()) {
|
||||
using (Stream responseStream = response.GetResponseStream ()) {
|
||||
using (StreamReader rdr = new StreamReader (responseStream)) {
|
||||
ans = (TAnswer) JsonConvert.DeserializeObject<TAnswer> (rdr.ReadToEnd ());
|
||||
}
|
||||
}
|
||||
response.Close();
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
public async Task<JsonValue> InvokeJson(object query)
|
||||
{
|
||||
JsonValue jsonDoc=null;
|
||||
using (Stream streamQuery = request.GetRequestStream()) {
|
||||
using (StreamWriter writer = new StreamWriter(streamQuery)) {
|
||||
writer.Write (JsonConvert.SerializeObject(query));
|
||||
}}
|
||||
using (WebResponse response = request.GetResponse ()) {
|
||||
using (Stream stream = response.GetResponseStream ()) {
|
||||
if (stream.Length>0)
|
||||
jsonDoc = await Task.Run (() => JsonObject.Load (stream));
|
||||
}
|
||||
response.Close();
|
||||
}
|
||||
return jsonDoc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user