From 2cd531c2425549bbcfd224ba4f1563c659f908c9 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 12 Sep 2020 01:11:30 +0100 Subject: [PATCH] principalement du format de code --- .editorconfig | 7 + Makefile | 4 + omnisharp.json | 2 +- .../OAuthAuthorizationServerHandler.cs | 2 +- src/OAuth.AspNet.AuthServer/project.json | 2 +- .../TicketDataFormatTokenValidator.cs | 2 +- src/OAuth.AspNet.Token/project.json | 2 +- .../Authentication/OAuthenticator.cs | 15 +- src/Yavsc.Abstract/Constants.cs | 2 +- .../FileSystem/AbstractFileSystemHelpers.cs | 18 +-- .../Workflow/Process/Negation.cs | 2 +- src/Yavsc.Abstract/project.json | 5 +- .../Helpers/SimpleJsonPostMethod.cs | 2 +- .../Interfaces/ICalendarManager.cs | 2 +- .../Models/HairCut/HairCutPaymentEvent.cs | 28 ++-- .../Models/HairCut/HairCutQuery.cs | 2 +- .../Models/HairCut/HairCutQueryEvent.cs | 1 - src/Yavsc.Server/Models/IT/Project.cs | 2 +- .../Models/IT/SourceCode/GitClone.cs | 2 +- .../Models/IT/SourceCode/ProjectBuild.cs | 4 +- src/Yavsc.Server/Models/Messaging/Announce.cs | 2 +- .../Models/Messaging/EstimationEvent.cs | 11 +- src/Yavsc.Server/project.json | 3 +- .../Streaming/LiveApiController.cs | 8 +- .../ApiControllers/Survey/BugApiController.cs | 4 +- .../AuthorizationHandlers/BlogViewHandler.cs | 2 +- .../SendMessageHandler.cs | 2 +- .../AuthorizationHandlers/ViewFileHandler.cs | 5 +- .../AuthorizationServer/GoogleHandler.cs | 10 +- .../AuthorizationServer/GoogleMiddleWare.cs | 4 +- .../GoogleOAuthCreatingTicket.cs | 7 +- .../Accounting/AccountController.cs | 5 +- .../Accounting/ManageController.cs | 20 +-- .../Controllers/Accounting/OAuthController.cs | 10 +- .../Controllers/Accounting/UsersController.cs | 2 +- .../MailingTemplateController.cs | 2 +- .../Communicating/BlogspotController.cs | 9 +- .../Communicating/CircleController.cs | 2 +- .../Communicating/CircleMembersController.cs | 2 +- .../Communicating/CommentsController.cs | 2 +- .../Communicating/DevicesController.cs | 2 +- .../Communicating/HyperLinkController.cs | 2 +- .../Communicating/LiveFlowController.cs | 2 +- .../Communicating/MyFSRulesController.cs | 4 +- .../Communicating/NotificationsController.cs | 2 +- .../Contracting/ActivityController.cs | 6 +- .../Contracting/ClientController.cs | 2 +- .../Controllers/Contracting/DoController.cs | 6 +- src/Yavsc/Models/ApplicationDbContext.cs | 12 +- src/Yavsc/Services/BillingService.cs | 4 +- src/Yavsc/Services/ChatHubConnexionManager.cs | 18 +-- src/Yavsc/Services/EMailer.cs | 14 +- src/Yavsc/Services/FileSystemAuthManager.cs | 6 +- .../Services/GoogleApis/CalendarManager.cs | 132 ++++++++---------- src/Yavsc/Services/LiveProcessor.cs | 115 ++++++++------- src/Yavsc/Services/MailSender.cs | 10 +- src/Yavsc/Services/SIRENCheker.cs | 2 +- src/Yavsc/Services/YavscMessageSender.cs | 26 ++-- src/Yavsc/Startup/Startup.OAuth.cs | 3 +- src/Yavsc/Startup/Startup.SanityChecks.cs | 10 +- src/Yavsc/Startup/Startup.WebSockets.cs | 5 +- src/Yavsc/Startup/Startup.Workflow.cs | 8 +- src/Yavsc/Startup/Startup.cs | 19 +-- src/Yavsc/ViewComponents/BillViewComponent.cs | 11 +- .../ViewComponents/BlogIndexViewComponent.cs | 12 +- .../ViewComponents/CalendarViewComponent.cs | 6 +- src/Yavsc/ViewComponents/TaggerComponent.cs | 11 +- .../ViewModels/Streaming/LiveCastHandler.cs | 31 ++-- src/cli/Commands/AuthCommander.cs | 57 ++++---- src/cli/Commands/Builder.cs | 9 +- src/cli/Commands/GenerationCommander.cs | 3 +- src/cli/Commands/Streamer.cs | 58 +++----- src/cli/Helpers/ConsoleHelpers.cs | 12 +- src/cli/Misc/YavscServerFactory.cs | 2 +- src/cli/Program.cs | 30 ++-- src/cli/Services/EMailer.cs | 13 +- src/cli/Services/MvcGenerator.cs | 9 +- src/cli/Startup.cs | 3 +- src/cli/project.json | 2 +- .../Controllers/HomeController.cs | 99 +++++++------ src/sampleWebAsWebApiClient/project.json | 2 +- src/test/Mandatory/AbstractTests.cs | 2 +- src/test/Mandatory/BatchTests.cs | 24 ++-- src/test/Mandatory/Database.cs | 4 +- src/test/Mandatory/EMailling.cs | 6 +- src/test/Mandatory/NodeTests.cs | 24 ++-- src/test/project.json | 2 +- 87 files changed, 510 insertions(+), 550 deletions(-) diff --git a/.editorconfig b/.editorconfig index 0277ae66..c55741fe 100644 --- a/.editorconfig +++ b/.editorconfig @@ -35,3 +35,10 @@ indent_style = space indent_size = 2 +dotnet_naming_rule.locals_should_be_camel_case.severity = none +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + +dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + +dotnet_naming_style.camel_case_style.capitalization = camel_case diff --git a/Makefile b/Makefile index 58ec8433..a0d825fb 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,10 @@ clean: checklibs: ls $(DNXLIBFP) +updatedeps: + cp src/Yavsc/bin/output/approot/packages/*/*/lib/*net451*/*.dll private/lib/ + cp src/Yavsc/bin/output/approot/packages/*/*/lib/*dnx451*/*.dll private/lib/ + test: make -C src/test diff --git a/omnisharp.json b/omnisharp.json index 7df34792..f0bb00d3 100644 --- a/omnisharp.json +++ b/omnisharp.json @@ -8,7 +8,7 @@ "Dnx": { "enabled": true, "enablePackageRestore": false, - "projects": "src/*/project.json;*/project.json;project.json;test/*/project.json" + "projects": "src/*/project.json;*/project.json;project.json;test/*/project.json" }, "Script": { "enabled": false diff --git a/src/OAuth.AspNet.AuthServer/OAuthAuthorizationServerHandler.cs b/src/OAuth.AspNet.AuthServer/OAuthAuthorizationServerHandler.cs index 417208a1..c2012a0a 100644 --- a/src/OAuth.AspNet.AuthServer/OAuthAuthorizationServerHandler.cs +++ b/src/OAuth.AspNet.AuthServer/OAuthAuthorizationServerHandler.cs @@ -33,7 +33,7 @@ namespace OAuth.AspNet.AuthServer MemoryStream stream, memoryStream = null; - StreamWriter streamWriter = null; + StreamWriter streamWriter; try { diff --git a/src/OAuth.AspNet.AuthServer/project.json b/src/OAuth.AspNet.AuthServer/project.json index cc9f2a7e..ff9f989e 100644 --- a/src/OAuth.AspNet.AuthServer/project.json +++ b/src/OAuth.AspNet.AuthServer/project.json @@ -26,7 +26,7 @@ "defaultNamespace": "Yavsc" }, "dependencies": { - "Newtonsoft.Json": "6.0.1-beta1", + "Newtonsoft.Json": "7.0.1", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-*", "OAuth.AspNet.Token": { "type": "build", diff --git a/src/OAuth.AspNet.Token/TicketDataFormatTokenValidator.cs b/src/OAuth.AspNet.Token/TicketDataFormatTokenValidator.cs index f4e34bc2..5db1b918 100644 --- a/src/OAuth.AspNet.Token/TicketDataFormatTokenValidator.cs +++ b/src/OAuth.AspNet.Token/TicketDataFormatTokenValidator.cs @@ -27,7 +27,7 @@ namespace OAuth.AspNet.Tokens #region non-Public Members - private TicketDataFormat _ticketDataFormat; + private readonly TicketDataFormat _ticketDataFormat; private const string _serializationRegex = @"^[A-Za-z0-9-_]*$"; diff --git a/src/OAuth.AspNet.Token/project.json b/src/OAuth.AspNet.Token/project.json index 1752dde4..ecacfbf4 100644 --- a/src/OAuth.AspNet.Token/project.json +++ b/src/OAuth.AspNet.Token/project.json @@ -26,7 +26,7 @@ "defaultNamespace": "Yavsc" }, "dependencies": { - "Newtonsoft.Json": "6.0.1-beta1", + "Newtonsoft.Json": "7.0.1", "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final", "Microsoft.AspNet.DataProtection": "1.0.0-rc1-final" }, diff --git a/src/Yavsc.Abstract/Authentication/OAuthenticator.cs b/src/Yavsc.Abstract/Authentication/OAuthenticator.cs index 613cdbcd..61a26d37 100644 --- a/src/Yavsc.Abstract/Authentication/OAuthenticator.cs +++ b/src/Yavsc.Abstract/Authentication/OAuthenticator.cs @@ -16,13 +16,14 @@ namespace Yavsc.Authentication { } - string clientId; - string clientSecret; - string scope; - Uri authorizeUrl; - Uri accessTokenUrl; - Uri redirectUrl; - GetUsernameAsyncFunc getUsernameAsync; + + readonly string clientId; + readonly string clientSecret; + readonly string scope; + readonly Uri authorizeUrl; + readonly Uri accessTokenUrl; + readonly Uri redirectUrl; + readonly GetUsernameAsyncFunc getUsernameAsync; string requestState; bool reportedForgery = false; diff --git a/src/Yavsc.Abstract/Constants.cs b/src/Yavsc.Abstract/Constants.cs index 0bdcf8f6..cdf5bf61 100644 --- a/src/Yavsc.Abstract/Constants.cs +++ b/src/Yavsc.Abstract/Constants.cs @@ -48,7 +48,7 @@ namespace Yavsc public const string YavscConnectionStringEnvName = "YAVSC_DB_CONNECTION"; // at the end, let 4*4 bytes in peace - public const int WebSocketsMaxBufLen = 4 * 1020; + public const int WebSocketsMaxBufLen = 4096; public static readonly long DefaultFSQ = 1024 * 1024 * 500; diff --git a/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs b/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs index b9de71f8..ccad8d88 100644 --- a/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs +++ b/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs @@ -10,7 +10,7 @@ namespace Yavsc.Helpers { public static string UserBillsDirName { set; get; } public static string UserFilesDirName { set; get; } - + /// /// Is Valid this Path? /// Return true when given value is a valid user file sub-path, @@ -37,7 +37,7 @@ namespace Yavsc.Helpers { return !name.Any(c => !ValidFileNameChars.Contains(c)); } - + // Ensure this path is canonical, // No "dirto/./this", neither "dirt/to/that/" // no .. and each char must be listed as valid in constants @@ -49,11 +49,11 @@ namespace Yavsc.Helpers { if (ValidFileNameChars.Contains(c)) sb.Append(c); - else sb.Append("#"+((int)c).ToString("D3")); + else sb.Append("#" + ((int)c).ToString("D3")); } - return sb.ToString(); + return sb.ToString(); } - + public static UserDirectoryInfo GetUserFiles(string userName, string subdir) { UserDirectoryInfo di = new UserDirectoryInfo(UserFilesDirName, userName, subdir); @@ -71,10 +71,10 @@ namespace Yavsc.Helpers // Only accept descent remote file names public static char[] ValidFileNameChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_~. %#".ToCharArray(); - + // Estimate signature file name format - public static Func - SignFileNameFormat = new Func ((signType,billingCode,estimateId) => $"sign-{billingCode}-{signType}-{estimateId}.png"); - + public static Func + SignFileNameFormat = new Func((signType, billingCode, estimateId) => $"sign-{billingCode}-{signType}-{estimateId}.png"); + } } diff --git a/src/Yavsc.Abstract/Workflow/Process/Negation.cs b/src/Yavsc.Abstract/Workflow/Process/Negation.cs index 343b9940..d8533a83 100644 --- a/src/Yavsc.Abstract/Workflow/Process/Negation.cs +++ b/src/Yavsc.Abstract/Workflow/Process/Negation.cs @@ -3,7 +3,7 @@ namespace Yavsc.Models.Process { public class Negation : IRequisition where Exp : IRequisition { - Exp _expression; + readonly Exp _expression; public Negation(Exp expression) { _expression = expression; diff --git a/src/Yavsc.Abstract/project.json b/src/Yavsc.Abstract/project.json index 7ab20931..1c27060a 100644 --- a/src/Yavsc.Abstract/project.json +++ b/src/Yavsc.Abstract/project.json @@ -24,11 +24,14 @@ "Chat" ] }, + "buildOptions": { + "nowarn": ["IDE1006"] + }, "tooling": { "defaultNamespace": "Yavsc" }, "dependencies": { - "Newtonsoft.Json": "6.0.1-beta1" + "Newtonsoft.Json": "7.0.1" }, "frameworks": { "dnx451": { diff --git a/src/Yavsc.Server/Helpers/SimpleJsonPostMethod.cs b/src/Yavsc.Server/Helpers/SimpleJsonPostMethod.cs index 6b69a270..7de9d358 100644 --- a/src/Yavsc.Server/Helpers/SimpleJsonPostMethod.cs +++ b/src/Yavsc.Server/Helpers/SimpleJsonPostMethod.cs @@ -31,7 +31,7 @@ namespace Yavsc.Server.Helpers /// public class SimpleJsonPostMethod : IDisposable { - private HttpWebRequest request=null; + private readonly HttpWebRequest request=null; /// /// Initializes a new instance of the Yavsc.Helpers.SimpleJsonPostMethod class. diff --git a/src/Yavsc.Server/Interfaces/ICalendarManager.cs b/src/Yavsc.Server/Interfaces/ICalendarManager.cs index ffdf8e7b..01b81e95 100644 --- a/src/Yavsc.Server/Interfaces/ICalendarManager.cs +++ b/src/Yavsc.Server/Interfaces/ICalendarManager.cs @@ -31,7 +31,7 @@ namespace Yavsc.Services /// I calendar manager. /// public interface ICalendarManager { - Task GetCalendarsAsync (string userId, string pageToken); + Task GetCalendarsAsync (string pageToken); Task GetCalendarAsync (string calid, DateTime minDate, DateTime maxDate, string pageToken); Task CreateViewModelAsync( string inputId, diff --git a/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs b/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs index f6ca7a7e..e76bbb37 100644 --- a/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs +++ b/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs @@ -34,19 +34,19 @@ namespace Yavsc.Models.HairCut public string Sender { get; set; } - HairCutQuery query; - - private string invoiceId; - private string payerName; - private string phone; - private string payerEmail; - private string amount; - private HairCutGenders gender; - private string date; - private string lieu; - private string clientFinal; - private string token; - private string payerId; + readonly HairCutQuery query; + + private readonly string invoiceId; + private readonly string payerName; + private readonly string phone; + private readonly string payerEmail; + private readonly string amount; + private readonly HairCutGenders gender; + private readonly string date; + private readonly string lieu; + private readonly string clientFinal; + private readonly string token; + private readonly string payerId; public string CreateBody() { @@ -73,4 +73,4 @@ Le client final: {clientFinal} "; } } -} \ No newline at end of file +} diff --git a/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs b/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs index f6ac6954..4970b520 100644 --- a/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs +++ b/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs @@ -140,7 +140,7 @@ Prestation.Gender == HairCutGenders.Women ? bill.Add(new CommandLine { Name = name, - Description = name = name + shorthairsuffix, + Description = name + shorthairsuffix, UnitaryCost = multicolor ? SelectedProfile.ShortMultiColorPrice : SelectedProfile.ShortColorPrice }); diff --git a/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs b/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs index 31dd8a12..bd30fb78 100644 --- a/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs +++ b/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs @@ -36,6 +36,5 @@ namespace Yavsc.Models.Haircut private set; } - HairCutQuery Data { get; set; } } } diff --git a/src/Yavsc.Server/Models/IT/Project.cs b/src/Yavsc.Server/Models/IT/Project.cs index 160ace97..9880c1bb 100644 --- a/src/Yavsc.Server/Models/IT/Project.cs +++ b/src/Yavsc.Server/Models/IT/Project.cs @@ -39,7 +39,7 @@ namespace Yavsc.Server.Models.IT [ForeignKey("GitId")] public virtual GitRepositoryReference Repository { get; set; } - List bill = new List(); + readonly List bill = new List(); public void AddBillItem(IBillItem item) { bill.Add(item); diff --git a/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs b/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs index bc21d9c0..5c926f3b 100644 --- a/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs +++ b/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs @@ -47,7 +47,7 @@ namespace Yavsc.Server.Models.IT.SourceCode writer.WriteLine(process.StandardOutput.ReadLine()); } } - if (ResultHandler!=null) ResultHandler(true); + ResultHandler?.Invoke(true); } } } diff --git a/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs b/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs index 78a42a2d..3c636e0f 100644 --- a/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs +++ b/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs @@ -36,8 +36,8 @@ namespace Yavsc.Server.Models.IT.SourceCode writer.WriteLine(process.StandardOutput.ReadLine()); } } - if (ResultHandler!=null) ResultHandler(true); + ResultHandler?.Invoke(true); } } -} \ No newline at end of file +} diff --git a/src/Yavsc.Server/Models/Messaging/Announce.cs b/src/Yavsc.Server/Models/Messaging/Announce.cs index d2a3c889..ee807857 100644 --- a/src/Yavsc.Server/Models/Messaging/Announce.cs +++ b/src/Yavsc.Server/Models/Messaging/Announce.cs @@ -21,7 +21,7 @@ public class Announce : BaseEvent, IAnnounce, IOwned public string Message { get; set; } public override string CreateBody() { - return $"Annonce de {Owner.UserName}: {For.ToString()}\n\n{Message}"; + return $"Annonce de {Owner.UserName}: {For}\n\n{Message}"; } } } diff --git a/src/Yavsc.Server/Models/Messaging/EstimationEvent.cs b/src/Yavsc.Server/Models/Messaging/EstimationEvent.cs index 7c5a89ff..32797d4f 100644 --- a/src/Yavsc.Server/Models/Messaging/EstimationEvent.cs +++ b/src/Yavsc.Server/Models/Messaging/EstimationEvent.cs @@ -24,13 +24,14 @@ namespace Yavsc.Models.Messaging Sender = perfer.Performer.UserName; _localizer = SR; } - // TODO via e-mail only: Message = string.Format( - // SR["EstimationMessageToClient"],perfer.Performer.UserName, estimate.Title,estimate.Bill.Addition()); - // + + // TODO via e-mail only: Message = string.Format( + // SR["EstimationMessageToClient"],perfer.Performer.UserName, estimate.Title,estimate.Bill.Addition()); + ProviderClientInfo ProviderInfo { get; set; } Estimate Estimation { get; set; } - private PerformerProfile perfer; + private readonly PerformerProfile perfer; public string Topic { @@ -46,7 +47,7 @@ namespace Yavsc.Models.Messaging public string CreateBody() { - return string.Format( _localizer["EstimationMessageToClient"], perfer.Performer.UserName, this.Estimation.Bill.Addition()); + return string.Format(_localizer["EstimationMessageToClient"], perfer.Performer.UserName, this.Estimation.Bill.Addition()); } } } diff --git a/src/Yavsc.Server/project.json b/src/Yavsc.Server/project.json index d2e2b439..41f33c53 100644 --- a/src/Yavsc.Server/project.json +++ b/src/Yavsc.Server/project.json @@ -41,7 +41,8 @@ "Resources/**/*.resx" ], "publicSign": false, - "keyFile": "../../../sgKey.snk" + "keyFile": "../../../sgKey.snk", + "nowarn": ["IDE1006"] }, "tooling": { "defaultNamespace": "Yavsc" diff --git a/src/Yavsc/ApiControllers/Streaming/LiveApiController.cs b/src/Yavsc/ApiControllers/Streaming/LiveApiController.cs index d8c3223d..a71b7a2f 100644 --- a/src/Yavsc/ApiControllers/Streaming/LiveApiController.cs +++ b/src/Yavsc/ApiControllers/Streaming/LiveApiController.cs @@ -18,10 +18,8 @@ namespace Yavsc.Controllers [Route("api/live")] public class LiveApiController : Controller { - - ILiveProcessor _liveProcessor; - private ApplicationDbContext _dbContext; - ILogger _logger; + readonly ILiveProcessor _liveProcessor; + private readonly ApplicationDbContext _dbContext; /// /// Live Api Controller @@ -30,13 +28,11 @@ namespace Yavsc.Controllers /// public LiveApiController( - ILoggerFactory loggerFactory, ApplicationDbContext context, ILiveProcessor liveProcessor) { _liveProcessor = liveProcessor; _dbContext = context; - _logger = loggerFactory.CreateLogger(); } [HttpGet("filenamehint/{id}")] diff --git a/src/Yavsc/ApiControllers/Survey/BugApiController.cs b/src/Yavsc/ApiControllers/Survey/BugApiController.cs index 7f62944a..153980da 100644 --- a/src/Yavsc/ApiControllers/Survey/BugApiController.cs +++ b/src/Yavsc/ApiControllers/Survey/BugApiController.cs @@ -16,8 +16,8 @@ namespace Yavsc.ApiControllers [Route("~/api/bug")] public class BugApiController : Controller { - private ApplicationDbContext _context; - ILogger _logger; + private readonly ApplicationDbContext _context; + readonly ILogger _logger; public BugApiController(ApplicationDbContext context, ILoggerFactory factory) { diff --git a/src/Yavsc/AuthorizationHandlers/BlogViewHandler.cs b/src/Yavsc/AuthorizationHandlers/BlogViewHandler.cs index 80ea3847..97453e58 100644 --- a/src/Yavsc/AuthorizationHandlers/BlogViewHandler.cs +++ b/src/Yavsc/AuthorizationHandlers/BlogViewHandler.cs @@ -32,4 +32,4 @@ namespace Yavsc.AuthorizationHandlers } } } -} \ No newline at end of file +} diff --git a/src/Yavsc/AuthorizationHandlers/SendMessageHandler.cs b/src/Yavsc/AuthorizationHandlers/SendMessageHandler.cs index a3e35221..71d69c83 100644 --- a/src/Yavsc/AuthorizationHandlers/SendMessageHandler.cs +++ b/src/Yavsc/AuthorizationHandlers/SendMessageHandler.cs @@ -8,7 +8,7 @@ namespace Yavsc.AuthorizationHandlers { public class SendMessageHandler : AuthorizationHandler { - ApplicationDbContext _dbContext ; + readonly ApplicationDbContext _dbContext ; public SendMessageHandler(ApplicationDbContext dbContext) { diff --git a/src/Yavsc/AuthorizationHandlers/ViewFileHandler.cs b/src/Yavsc/AuthorizationHandlers/ViewFileHandler.cs index 9bb99fe3..bd690cce 100644 --- a/src/Yavsc/AuthorizationHandlers/ViewFileHandler.cs +++ b/src/Yavsc/AuthorizationHandlers/ViewFileHandler.cs @@ -5,8 +5,7 @@ using Yavsc.ViewModels.Auth; namespace Yavsc.AuthorizationHandlers { public class ViewFileHandler : AuthorizationHandler { - - IFileSystemAuthManager _authManager; + readonly IFileSystemAuthManager _authManager; public ViewFileHandler (IFileSystemAuthManager authManager) { _authManager = authManager; @@ -28,4 +27,4 @@ namespace Yavsc.AuthorizationHandlers { } } } -} \ No newline at end of file +} diff --git a/src/Yavsc/AuthorizationServer/GoogleHandler.cs b/src/Yavsc/AuthorizationServer/GoogleHandler.cs index af6ee9a1..fe6f4d04 100644 --- a/src/Yavsc/AuthorizationServer/GoogleHandler.cs +++ b/src/Yavsc/AuthorizationServer/GoogleHandler.cs @@ -15,7 +15,7 @@ namespace Yavsc.Auth { internal class GoogleHandler : OAuthHandler { - private ILogger _logger; + private readonly ILogger _logger; public GoogleHandler(HttpClient httpClient,ILogger logger) : base(httpClient) { @@ -92,9 +92,11 @@ namespace Yavsc.Auth { var scope = FormatScope(); - var queryStrings = new Dictionary(StringComparer.OrdinalIgnoreCase); - queryStrings.Add("response_type", "code"); - queryStrings.Add("client_id", Options.ClientId); + var queryStrings = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "response_type", "code" }, + { "client_id", Options.ClientId } + }; // this runtime may not known this value, // it should be get from config, // And always be using a secure sheme ... since Google won't support anymore insecure ones. diff --git a/src/Yavsc/AuthorizationServer/GoogleMiddleWare.cs b/src/Yavsc/AuthorizationServer/GoogleMiddleWare.cs index fbe28db2..9957b803 100644 --- a/src/Yavsc/AuthorizationServer/GoogleMiddleWare.cs +++ b/src/Yavsc/AuthorizationServer/GoogleMiddleWare.cs @@ -16,8 +16,8 @@ namespace Yavsc.Auth /// public class GoogleMiddleware : OAuthMiddleware { - private RequestDelegate _next; - private ILogger _logger; + private readonly RequestDelegate _next; + private readonly ILogger _logger; /// /// Initializes a new . diff --git a/src/Yavsc/AuthorizationServer/GoogleOAuthCreatingTicket.cs b/src/Yavsc/AuthorizationServer/GoogleOAuthCreatingTicket.cs index dfb7fe3b..c94cfde0 100644 --- a/src/Yavsc/AuthorizationServer/GoogleOAuthCreatingTicket.cs +++ b/src/Yavsc/AuthorizationServer/GoogleOAuthCreatingTicket.cs @@ -15,8 +15,9 @@ namespace Yavsc.Auth { _googleUserId = googleUserId; Principal = ticket.Principal; } - AuthenticationTicket _ticket; - string _googleUserId; + + readonly AuthenticationTicket _ticket; + readonly string _googleUserId; public AuthenticationTicket Ticket { get { return _ticket; } } @@ -24,4 +25,4 @@ namespace Yavsc.Auth { } -} \ No newline at end of file +} diff --git a/src/Yavsc/Controllers/Accounting/AccountController.cs b/src/Yavsc/Controllers/Accounting/AccountController.cs index 159f4086..2c75843f 100644 --- a/src/Yavsc/Controllers/Accounting/AccountController.cs +++ b/src/Yavsc/Controllers/Accounting/AccountController.cs @@ -71,7 +71,6 @@ namespace Yavsc.Controllers [Authorize(Roles = Constants.AdminGroupName)] public IActionResult Index(string page, string len) { - return View(); } @@ -262,7 +261,7 @@ namespace Yavsc.Controllers // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); - var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: "https", host: Startup.Authority); + var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, protocol: "https", host: Startup.Authority); var emailSent = await _emailSender.SendEmailAsync(model.UserName, model.Email, _localizer["ConfirmYourAccountTitle"], string.Format(_localizer["ConfirmYourAccountBody"], _siteSettings.Title, callbackUrl, _siteSettings.Slogan, _siteSettings.Audience)); // No, wait for more than a login pass submission: @@ -317,7 +316,7 @@ namespace Yavsc.Controllers { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Account", - new { userId = user.Id, code = code }, protocol: "https", host: Startup.Authority); + new { userId = user.Id, code }, protocol: "https", host: Startup.Authority); var res = await _emailSender.SendEmailAsync(user.UserName, user.Email, this._localizer["ConfirmYourAccountTitle"], string.Format(this._localizer["ConfirmYourAccountBody"], diff --git a/src/Yavsc/Controllers/Accounting/ManageController.cs b/src/Yavsc/Controllers/Accounting/ManageController.cs index 37e8aea1..d473779e 100644 --- a/src/Yavsc/Controllers/Accounting/ManageController.cs +++ b/src/Yavsc/Controllers/Accounting/ManageController.cs @@ -29,18 +29,18 @@ namespace Yavsc.Controllers private readonly SignInManager _signInManager; private readonly IEmailSender _emailSender; private readonly ILogger _logger; - private SiteSettings _siteSettings; + private readonly SiteSettings _siteSettings; - private ApplicationDbContext _dbContext; + private readonly ApplicationDbContext _dbContext; - private GoogleAuthSettings _googleSettings; + private readonly GoogleAuthSettings _googleSettings; - private PayPalSettings _payPalSettings; - private IYavscMessageSender _GCMSender; - private SIRENChecker _cchecker; - private IStringLocalizer _SR; - private CompanyInfoSettings _cinfoSettings; - ICalendarManager _calendarManager; + private readonly PayPalSettings _payPalSettings; + private readonly IYavscMessageSender _GCMSender; + private readonly SIRENChecker _cchecker; + private readonly IStringLocalizer _SR; + private readonly CompanyInfoSettings _cinfoSettings; + readonly ICalendarManager _calendarManager; public ManageController( @@ -300,7 +300,7 @@ namespace Yavsc.Controllers { var uid = User.GetUserId(); - var calendars = await _calendarManager.GetCalendarsAsync(uid, pageToken); + var calendars = await _calendarManager.GetCalendarsAsync(pageToken); return View(new SetGoogleCalendarViewModel { ReturnUrl = returnUrl, Calendars = calendars diff --git a/src/Yavsc/Controllers/Accounting/OAuthController.cs b/src/Yavsc/Controllers/Accounting/OAuthController.cs index 62795c09..feea1fc7 100644 --- a/src/Yavsc/Controllers/Accounting/OAuthController.cs +++ b/src/Yavsc/Controllers/Accounting/OAuthController.cs @@ -20,12 +20,10 @@ namespace Yavsc.Controllers [AllowAnonymous] public class OAuthController : Controller { - ApplicationDbContext _context; - UserManager _userManager; - - SiteSettings _siteSettings; - - ILogger _logger; + readonly ApplicationDbContext _context; + readonly UserManager _userManager; + readonly SiteSettings _siteSettings; + readonly ILogger _logger; private readonly SignInManager _signInManager; public OAuthController(ApplicationDbContext context, SignInManager signInManager, IKeyManager keyManager, diff --git a/src/Yavsc/Controllers/Accounting/UsersController.cs b/src/Yavsc/Controllers/Accounting/UsersController.cs index 993ebcf6..4fb7cf77 100644 --- a/src/Yavsc/Controllers/Accounting/UsersController.cs +++ b/src/Yavsc/Controllers/Accounting/UsersController.cs @@ -10,7 +10,7 @@ namespace Yavsc.Controllers [Authorize("AdministratorOnly")] public class UsersController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public UsersController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Administration/MailingTemplateController.cs b/src/Yavsc/Controllers/Administration/MailingTemplateController.cs index d006eb12..d1e7cb65 100644 --- a/src/Yavsc/Controllers/Administration/MailingTemplateController.cs +++ b/src/Yavsc/Controllers/Administration/MailingTemplateController.cs @@ -16,7 +16,7 @@ namespace Yavsc.Controllers [Authorize("AdministratorOnly")] public class MailingTemplateController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public MailingTemplateController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Communicating/BlogspotController.cs b/src/Yavsc/Controllers/Communicating/BlogspotController.cs index a704beb7..5dfce6cc 100644 --- a/src/Yavsc/Controllers/Communicating/BlogspotController.cs +++ b/src/Yavsc/Controllers/Communicating/BlogspotController.cs @@ -21,11 +21,10 @@ namespace Yavsc.Controllers { public class BlogspotController : Controller { - ILogger _logger; - private ApplicationDbContext _context; - private IAuthorizationService _authorizationService; - - RequestLocalizationOptions _localisationOptions; + readonly ILogger _logger; + private readonly ApplicationDbContext _context; + private readonly IAuthorizationService _authorizationService; + readonly RequestLocalizationOptions _localisationOptions; public BlogspotController( ApplicationDbContext context, diff --git a/src/Yavsc/Controllers/Communicating/CircleController.cs b/src/Yavsc/Controllers/Communicating/CircleController.cs index 000077ff..80fc424b 100644 --- a/src/Yavsc/Controllers/Communicating/CircleController.cs +++ b/src/Yavsc/Controllers/Communicating/CircleController.cs @@ -11,7 +11,7 @@ namespace Yavsc.Controllers { public class CircleController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public CircleController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Communicating/CircleMembersController.cs b/src/Yavsc/Controllers/Communicating/CircleMembersController.cs index a130d6db..48a50bf0 100644 --- a/src/Yavsc/Controllers/Communicating/CircleMembersController.cs +++ b/src/Yavsc/Controllers/Communicating/CircleMembersController.cs @@ -11,7 +11,7 @@ namespace Yavsc.Controllers { public class CircleMembersController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public CircleMembersController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Communicating/CommentsController.cs b/src/Yavsc/Controllers/Communicating/CommentsController.cs index 824dee7a..ed6d2080 100644 --- a/src/Yavsc/Controllers/Communicating/CommentsController.cs +++ b/src/Yavsc/Controllers/Communicating/CommentsController.cs @@ -13,7 +13,7 @@ namespace Yavsc.Controllers /// public class CommentsController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public CommentsController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Communicating/DevicesController.cs b/src/Yavsc/Controllers/Communicating/DevicesController.cs index 273d04d4..023eb27c 100644 --- a/src/Yavsc/Controllers/Communicating/DevicesController.cs +++ b/src/Yavsc/Controllers/Communicating/DevicesController.cs @@ -12,7 +12,7 @@ namespace Yavsc.Controllers using Models.Identity; public class DevicesController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public DevicesController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Communicating/HyperLinkController.cs b/src/Yavsc/Controllers/Communicating/HyperLinkController.cs index ba541b3a..bf45059d 100644 --- a/src/Yavsc/Controllers/Communicating/HyperLinkController.cs +++ b/src/Yavsc/Controllers/Communicating/HyperLinkController.cs @@ -10,7 +10,7 @@ namespace Yavsc.Controllers [Authorize("AdministratorOnly")] public class HyperLinkController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public HyperLinkController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Communicating/LiveFlowController.cs b/src/Yavsc/Controllers/Communicating/LiveFlowController.cs index 3e44e19a..f54b8dae 100644 --- a/src/Yavsc/Controllers/Communicating/LiveFlowController.cs +++ b/src/Yavsc/Controllers/Communicating/LiveFlowController.cs @@ -12,7 +12,7 @@ namespace Yavsc.Controllers { public class LiveFlowController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public LiveFlowController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Communicating/MyFSRulesController.cs b/src/Yavsc/Controllers/Communicating/MyFSRulesController.cs index 1d2934e8..c1556fcb 100644 --- a/src/Yavsc/Controllers/Communicating/MyFSRulesController.cs +++ b/src/Yavsc/Controllers/Communicating/MyFSRulesController.cs @@ -14,8 +14,8 @@ namespace Yavsc.Controllers [Authorize()] public class MyFSRulesController : Controller { - private ApplicationDbContext _context; - private ILogger _logger; + private readonly ApplicationDbContext _context; + private readonly ILogger _logger; public MyFSRulesController(ApplicationDbContext context, ILoggerFactory loggerFactory) diff --git a/src/Yavsc/Controllers/Communicating/NotificationsController.cs b/src/Yavsc/Controllers/Communicating/NotificationsController.cs index 37e551b6..09a1acbf 100644 --- a/src/Yavsc/Controllers/Communicating/NotificationsController.cs +++ b/src/Yavsc/Controllers/Communicating/NotificationsController.cs @@ -9,7 +9,7 @@ namespace Yavsc.Controllers { public class NotificationsController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public NotificationsController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Contracting/ActivityController.cs b/src/Yavsc/Controllers/Contracting/ActivityController.cs index e0436d42..aa5214c0 100644 --- a/src/Yavsc/Controllers/Contracting/ActivityController.cs +++ b/src/Yavsc/Controllers/Contracting/ActivityController.cs @@ -16,9 +16,9 @@ namespace Yavsc.Controllers [Authorize("AdministratorOnly")] public class ActivityController : Controller { - private ApplicationDbContext _context; - IStringLocalizer SR; - ILogger logger; + private readonly ApplicationDbContext _context; + readonly IStringLocalizer SR; + readonly ILogger logger; public ActivityController(ApplicationDbContext context, IStringLocalizer SR, diff --git a/src/Yavsc/Controllers/Contracting/ClientController.cs b/src/Yavsc/Controllers/Contracting/ClientController.cs index 6c8bfa45..f43eb166 100644 --- a/src/Yavsc/Controllers/Contracting/ClientController.cs +++ b/src/Yavsc/Controllers/Contracting/ClientController.cs @@ -12,7 +12,7 @@ namespace Yavsc.Controllers { public class ClientController : Controller { - private ApplicationDbContext _context; + private readonly ApplicationDbContext _context; public ClientController(ApplicationDbContext context) { diff --git a/src/Yavsc/Controllers/Contracting/DoController.cs b/src/Yavsc/Controllers/Contracting/DoController.cs index 6a36d52f..e01ca8da 100644 --- a/src/Yavsc/Controllers/Contracting/DoController.cs +++ b/src/Yavsc/Controllers/Contracting/DoController.cs @@ -17,9 +17,9 @@ namespace Yavsc.Controllers [Authorize] public class DoController : Controller { - private ApplicationDbContext dbContext; - ILogger logger; - IBillingService billing; + private readonly ApplicationDbContext dbContext; + readonly ILogger logger; + readonly IBillingService billing; public DoController( ApplicationDbContext context, IBillingService billing, diff --git a/src/Yavsc/Models/ApplicationDbContext.cs b/src/Yavsc/Models/ApplicationDbContext.cs index 95625530..b3992ef1 100644 --- a/src/Yavsc/Models/ApplicationDbContext.cs +++ b/src/Yavsc/Models/ApplicationDbContext.cs @@ -57,7 +57,7 @@ namespace Yavsc.Models builder.Entity().HasKey(u => new { u.DoesCode, u.UserId }); builder.Entity().HasKey(u => new { u.InstrumentId, u.UserId }); builder.Entity().HasKey(a => new { a.CircleId, a.BlogPostId }); - builder.Entity().HasKey(c => new { MemberId = c.MemberId, CircleId = c.CircleId }); + builder.Entity().HasKey(c => new { c.MemberId, c.CircleId }); builder.Entity().HasKey(c => new { uid = c.UserId, notid = c.NotificationId }); builder.Entity().HasKey(ti => new { ti.TaintId, ti.PrestationId }); builder.Entity().HasKey(l => new { l.HRef, l.Method }); @@ -79,9 +79,9 @@ namespace Yavsc.Models } // this is not a failback procedure. + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - if (optionsBuilder.IsConfigured) return; if (!string.IsNullOrWhiteSpace(Startup.ConnectionString)) { optionsBuilder.UseNpgsql(Startup.ConnectionString); @@ -161,12 +161,6 @@ namespace Yavsc.Models public DbSet Services { get; set; } public DbSet Products { get; set; } - Client FindApplication(string clientId) - { - return Applications.FirstOrDefault( - app => app.Id == clientId); - } - public DbSet ExceptionsSIREN { get; set; } public DbSet Locations { get; set; } @@ -231,7 +225,7 @@ namespace Yavsc.Models public async Task SaveChangesAsync(string userId, CancellationToken ctoken = default(CancellationToken)) { AddTimestamps(userId); - return await base.SaveChangesAsync(); + return await base.SaveChangesAsync(ctoken); } public DbSet Circle { get; set; } diff --git a/src/Yavsc/Services/BillingService.cs b/src/Yavsc/Services/BillingService.cs index 71837149..008deb62 100644 --- a/src/Yavsc/Services/BillingService.cs +++ b/src/Yavsc/Services/BillingService.cs @@ -13,7 +13,6 @@ namespace Yavsc.Services public class BillingService : IBillingService { public ApplicationDbContext DbContext { get; private set; } - private ILogger logger; public static Dictionary> Billing = new Dictionary> (); public static List UserSettings = new List(); @@ -25,9 +24,8 @@ namespace Yavsc.Services get { return GlobalBillingMap; } } - public BillingService(ILoggerFactory loggerFactory, ApplicationDbContext dbContext) + public BillingService(ApplicationDbContext dbContext) { - logger = loggerFactory.CreateLogger(); DbContext = dbContext; } diff --git a/src/Yavsc/Services/ChatHubConnexionManager.cs b/src/Yavsc/Services/ChatHubConnexionManager.cs index e6cf8c50..5c728e16 100644 --- a/src/Yavsc/Services/ChatHubConnexionManager.cs +++ b/src/Yavsc/Services/ChatHubConnexionManager.cs @@ -31,24 +31,24 @@ namespace Yavsc.Services /// /// - static ConcurrentDictionary ChatUserNames = new ConcurrentDictionary(); + static readonly ConcurrentDictionary ChatUserNames = new ConcurrentDictionary(); /// /// by user name /// /// - static ConcurrentDictionary> ChatCxIds = new ConcurrentDictionary>(); + static readonly ConcurrentDictionary> ChatCxIds = new ConcurrentDictionary>(); /// /// by user name, /// the list of its chat rooms /// /// - static ConcurrentDictionary> ChatRoomPresence = new ConcurrentDictionary>(); - static ConcurrentDictionary _isCop = new ConcurrentDictionary(); + static readonly ConcurrentDictionary> ChatRoomPresence = new ConcurrentDictionary>(); + static readonly ConcurrentDictionary _isCop = new ConcurrentDictionary(); public static ConcurrentDictionary Channels = new ConcurrentDictionary(); - ApplicationDbContext _dbContext; - IStringLocalizer _localizer; + readonly ApplicationDbContext _dbContext; + readonly IStringLocalizer _localizer; public HubConnectionManager() { @@ -97,7 +97,7 @@ namespace Yavsc.Services return ChatRoomPresence[userName].Contains(roomName); } - public bool isCop(string userName) + public bool IsCop(string userName) { return _isCop[userName]; } @@ -179,7 +179,7 @@ namespace Yavsc.Services } else { - if (isCop(userName)) + if (IsCop(userName)) { chanInfo.Ops.Add(cxId); } @@ -320,7 +320,7 @@ namespace Yavsc.Services _errorHandler(roomName, _localizer.GetString(ChatHubConstants.HopWontKickOp).ToString()); return false; } - if (isCop(userName)) + if (IsCop(userName)) { _errorHandler(roomName, _localizer.GetString(ChatHubConstants.NoKickOnCop).ToString()); return false; diff --git a/src/Yavsc/Services/EMailer.cs b/src/Yavsc/Services/EMailer.cs index 839a5a3a..856c0b8f 100644 --- a/src/Yavsc/Services/EMailer.cs +++ b/src/Yavsc/Services/EMailer.cs @@ -27,14 +27,12 @@ namespace Yavsc.Lib const string DefaultBaseClassName = "ATemplate"; const string DefaultBaseClass = nameof(UserOrientedTemplate); const string DefaultNamespace = "CompiledRazorTemplates"; - - RazorTemplateEngine razorEngine; - IStringLocalizer stringLocalizer; - - ApplicationDbContext dbContext; - IEmailSender mailSender; - RazorEngineHost host; - ILogger logger; + readonly RazorTemplateEngine razorEngine; + readonly IStringLocalizer stringLocalizer; + readonly ApplicationDbContext dbContext; + readonly IEmailSender mailSender; + readonly RazorEngineHost host; + readonly ILogger logger; public EMailer(ApplicationDbContext context, IEmailSender sender, IStringLocalizer localizer, diff --git a/src/Yavsc/Services/FileSystemAuthManager.cs b/src/Yavsc/Services/FileSystemAuthManager.cs index 9c4700d3..c613f33f 100644 --- a/src/Yavsc/Services/FileSystemAuthManager.cs +++ b/src/Yavsc/Services/FileSystemAuthManager.cs @@ -9,8 +9,8 @@ namespace Yavsc.Services { public class FileSystemAuthManager : IFileSystemAuthManager { - ApplicationDbContext _dbContext; - ILogger _logger; + readonly ApplicationDbContext _dbContext; + readonly ILogger _logger; public FileSystemAuthManager(ApplicationDbContext dbContext, ILoggerFactory loggerFactory) { @@ -70,4 +70,4 @@ namespace Yavsc.Services throw new NotImplementedException(); } } -} \ No newline at end of file +} diff --git a/src/Yavsc/Services/GoogleApis/CalendarManager.cs b/src/Yavsc/Services/GoogleApis/CalendarManager.cs index b52633ee..84db3412 100644 --- a/src/Yavsc/Services/GoogleApis/CalendarManager.cs +++ b/src/Yavsc/Services/GoogleApis/CalendarManager.cs @@ -43,45 +43,22 @@ namespace Yavsc.Services /// /// Google Calendar API client. /// - public class CalendarManager : ICalendarManager + public class CalendarManager : ICalendarManager { public class ExpiredTokenException : Exception { } - protected static string [] scopesCalendar = + protected static string[] scopesCalendar = { "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events" }; - private string _ApiKey; - private IAuthorizationCodeFlow _flow; - ApplicationDbContext _dbContext; + readonly ILogger _logger; + readonly string _client_id; + readonly string _client_secret; - IDataStore _dataStore; - ILogger _logger; - string _client_id; - string _client_secret; - - public CalendarManager( - ApplicationDbContext dbContext, - IDataStore dataStore, - ILoggerFactory loggerFactory, - IOptions settings) + public CalendarManager(ILoggerFactory loggerFactory) { - _client_id = Startup.GoogleWebClientConfiguration["web:cient_id"]; - _client_secret = Startup.GoogleWebClientConfiguration["web:cient_secret"]; - - _ApiKey = settings.Value.ApiKey; - _dbContext = dbContext; + _client_id = Startup.GoogleWebClientConfiguration["web:cient_id"]; + _client_secret = Startup.GoogleWebClientConfiguration["web:cient_secret"]; _logger = loggerFactory.CreateLogger(); - _dataStore = dataStore; - _flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer - { - ClientSecrets = new ClientSecrets - { - ClientId = _client_id, - ClientSecret = _client_secret - }, - Scopes = scopesCalendar , - DataStore = dataStore - }); } /// @@ -98,29 +75,27 @@ namespace Yavsc.Services /// /// The calendars. /// Yavsc user id - public async Task GetCalendarsAsync(string userId, string pageToken) + public async Task GetCalendarsAsync(string pageToken) { - if (string.IsNullOrWhiteSpace(userId)) - throw new Exception("the user id is not specified"); - var service = await CreateUserCalendarServiceAsync(userId); + var service = await CreateUserCalendarServiceAsync(); #if Debug if (service==null) throw new Exception("Could not get service"); #endif - _logger.LogInformation("Got a service"); + _logger.LogInformation("Got a service"); #if Debug if (service.CalendarList==null) throw new Exception("Could not get calendar list"); #endif - CalendarListResource.ListRequest calListReq = service.CalendarList.List (); + CalendarListResource.ListRequest calListReq = service.CalendarList.List(); #if Debug if (calListReq==null) throw new Exception ("list is null"); #endif - calListReq.PageToken = pageToken; - return calListReq.Execute (); + calListReq.PageToken = pageToken; + return calListReq.Execute(); } - + /// /// Gets a calendar event list, between the given dates. /// @@ -158,16 +133,17 @@ namespace Yavsc.Services foreach (var ev in eventList.Items) { - if (ev.Start.DateTime.HasValue && ev.End.DateTime.HasValue ) { - DateTime start = ev.Start.DateTime.Value; - DateTime end = ev.End.DateTime.Value; - - if (ev.Transparency == "transparent") + if (ev.Start.DateTime.HasValue && ev.End.DateTime.HasValue) { + DateTime start = ev.Start.DateTime.Value; + DateTime end = ev.End.DateTime.Value; - free.Add(new Period { Start = start, End = end }); - } - else busy.Add(new Period { Start = start, End = end }); + if (ev.Transparency == "transparent") + { + + free.Add(new Period { Start = start, End = end }); + } + else busy.Add(new Period { Start = start, End = end }); } } @@ -200,7 +176,7 @@ namespace Yavsc.Services if (string.IsNullOrWhiteSpace(calid)) throw new Exception("the calendar identifier is not specified"); - + var service = await GetServiceAsync(); Event ev = new Event { @@ -217,15 +193,16 @@ namespace Yavsc.Services CalendarService _service = null; public async Task GetServiceAsync() { - if (_service==null) { + if (_service == null) + { GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync(); var baseClientService = new BaseClientService.Initializer() - { - HttpClientInitializer = credential - }; + { + HttpClientInitializer = credential + }; if (credential.IsCreateScopedRequired) { - credential = credential.CreateScoped( scopesCalendar ); + credential = credential.CreateScoped(scopesCalendar); }/* var credential = await GoogleHelpers.GetCredentialForApi(new string [] { scopeCalendar }); if (credential.IsCreateScopedRequired) @@ -239,26 +216,26 @@ namespace Yavsc.Services }); }*/ _service = new CalendarService(new BaseClientService.Initializer() - { - HttpClientInitializer = credential, - ApplicationName = "Yavsc" - }); + { + HttpClientInitializer = credential, + ApplicationName = "Yavsc" + }); } return _service; } - /// - /// Creates Google User Credential - /// - /// Yavsc use id - /// - public async Task CreateUserCalendarServiceAsync(string userId) + /// + /// Creates Google User Credential + /// + /// Yavsc use id + /// + public async Task CreateUserCalendarServiceAsync() { GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync(); if (credential.IsCreateScopedRequired) { - credential = credential.CreateScoped( scopesCalendar); + credential = credential.CreateScoped(scopesCalendar); } @@ -268,25 +245,32 @@ namespace Yavsc.Services ApplicationName = "yavsc-001" }); - return service; - } + return service; + } public async Task RefreshToken(TokenResponse oldResponse) { string ep = " https://www.googleapis.com/oauth2/v4/token"; _logger.LogInformation($"rt:{oldResponse.RefreshToken}"); // refresh_token client_id client_secret grant_type=refresh_token - try { - using (var m = new SimpleJsonPostMethod(ep)) { + try + { + using (var m = new SimpleJsonPostMethod(ep)) + { return await m.Invoke( - new { refresh_token= oldResponse.RefreshToken, client_id=_client_id, - client_secret=_client_secret, - grant_type="refresh_token" } + new + { + refresh_token = oldResponse.RefreshToken, + client_id = _client_id, + client_secret = _client_secret, + grant_type = "refresh_token" + } ); } } - catch (Exception ex) { - throw new Exception ("Quelque chose s'est mal passé à l'envoi",ex); + catch (Exception ex) + { + throw new Exception("Quelque chose s'est mal passé à l'envoi", ex); } } } diff --git a/src/Yavsc/Services/LiveProcessor.cs b/src/Yavsc/Services/LiveProcessor.cs index 08501a98..c34affee 100644 --- a/src/Yavsc/Services/LiveProcessor.cs +++ b/src/Yavsc/Services/LiveProcessor.cs @@ -21,14 +21,15 @@ using Newtonsoft.Json; namespace Yavsc.Services { - public class LiveProcessor : ILiveProcessor { - IHubContext _hubContext; - private ILogger _logger; - ApplicationDbContext _dbContext; - public PathString LiveCastingPath {get; set;} = Constants.LivePath; + public class LiveProcessor : ILiveProcessor + { + readonly IHubContext _hubContext; + private readonly ILogger _logger; + readonly ApplicationDbContext _dbContext; + public PathString LiveCastingPath { get; set; } = Constants.LivePath; - public ConcurrentDictionary Casters {get;} = new ConcurrentDictionary(); + public ConcurrentDictionary Casters { get; } = new ConcurrentDictionary(); public LiveProcessor(ApplicationDbContext dbContext, ILoggerFactory loggerFactory) { @@ -37,7 +38,7 @@ namespace Yavsc.Services _logger = loggerFactory.CreateLogger(); } - public async Task AcceptStream (HttpContext context) + public async Task AcceptStream(HttpContext context) { // TODO defer request handling var liveId = long.Parse(context.Request.Path.Value.Substring(LiveCastingPath.Value.Length + 1)); @@ -51,22 +52,23 @@ namespace Yavsc.Services context.Response.StatusCode = 400; return false; } - _logger.LogInformation("flow : "+flow.Title+" for "+uname); - + _logger.LogInformation("flow : " + flow.Title + " for " + uname); + LiveCastHandler liveHandler = null; if (Casters.ContainsKey(uname)) { _logger.LogWarning($"Casters.ContainsKey({uname})"); liveHandler = Casters[uname]; - if (liveHandler.Socket.State == WebSocketState.Open || liveHandler.Socket.State == WebSocketState.Connecting ) + if (liveHandler.Socket.State == WebSocketState.Open || liveHandler.Socket.State == WebSocketState.Connecting) { - _logger.LogWarning($"Closing cx"); + _logger.LogWarning($"Closing cx"); // FIXME loosed connexion should be detected & disposed else where - await liveHandler.Socket.CloseAsync( WebSocketCloseStatus.EndpointUnavailable, "one by user", CancellationToken.None); - + await liveHandler.Socket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "one by user", CancellationToken.None); + } - if (!liveHandler.TokenSource.IsCancellationRequested) { + if (!liveHandler.TokenSource.IsCancellationRequested) + { liveHandler.TokenSource.Cancel(); } liveHandler.Socket.Dispose(); @@ -81,7 +83,7 @@ namespace Yavsc.Services } _logger.LogInformation("Accepted web socket"); // Dispatch the flow - + try { if (liveHandler.Socket != null && liveHandler.Socket.State == WebSocketState.Open) @@ -90,33 +92,33 @@ namespace Yavsc.Services // TODO: Handle the socket here. // Find receivers: others in the chat room // send them the flow - var buffer = new byte[Constants.WebSocketsMaxBufLen+16]; + var buffer = new byte[Constants.WebSocketsMaxBufLen]; var sBuffer = new ArraySegment(buffer); _logger.LogInformation("Receiving bytes..."); WebSocketReceiveResult received = await liveHandler.Socket.ReceiveAsync(sBuffer, liveHandler.TokenSource.Token); - int count = (received.Count<4)? 0 : buffer[0]*256*1024 +buffer[1]*1024+buffer[2]*256 + buffer[3]; - _logger.LogInformation($"Received bytes : {count}"); + _logger.LogInformation($"Received bytes : {received.Count}"); _logger.LogInformation($"Is the end : {received.EndOfMessage}"); const string livePath = "live"; string destDir = context.User.InitPostToFileSystem(livePath); _logger.LogInformation($"Saving flow to {destDir}"); - - string fileName = flow.GetFileName(); + + string fileName = flow.GetFileName(); FileInfo destFileInfo = new FileInfo(Path.Combine(destDir, fileName)); // this should end :-) - while (destFileInfo.Exists) { + while (destFileInfo.Exists) + { flow.SequenceNumber++; - fileName = flow.GetFileName(); + fileName = flow.GetFileName(); destFileInfo = new FileInfo(Path.Combine(destDir, fileName)); } var fsInputQueue = new Queue>(); - - bool endOfInput=false; + + bool endOfInput = false; fsInputQueue.Enqueue(sBuffer); - var taskWritingToFs = liveHandler.ReceiveUserFile(user, _logger, destDir, fsInputQueue, fileName, flow.MediaType, ()=> endOfInput); + var taskWritingToFs = liveHandler.ReceiveUserFile(user, _logger, destDir, fsInputQueue, fileName, flow.MediaType, () => endOfInput); var hubContext = GlobalHost.ConnectionManager.GetHubContext(); hubContext.Clients.All.addPublicStream(new PublicStreamInfo @@ -132,15 +134,18 @@ namespace Yavsc.Services try { - do { - + do + { + _logger.LogInformation($"Echoing {received.Count} bytes received in a {received.MessageType} message; Fin={received.EndOfMessage}"); // Echo anything we receive // and send to all listner found + _logger.LogInformation($"{liveHandler.Listeners.Count} listeners"); foreach (var cliItem in liveHandler.Listeners) { var listenningSocket = cliItem.Value; - if (listenningSocket.State == WebSocketState.Open) { + if (listenningSocket.State == WebSocketState.Open) + { _logger.LogInformation(cliItem.Key); await listenningSocket.SendAsync( sBuffer, received.MessageType, received.EndOfMessage, liveHandler.TokenSource.Token); @@ -150,43 +155,47 @@ namespace Yavsc.Services ToClose.Push(cliItem.Key); } } - buffer = new byte[Constants.WebSocketsMaxBufLen+16]; + + if (!received.CloseStatus.HasValue) + { + _logger.LogInformation("try and receive new bytes"); + + buffer = new byte[Constants.WebSocketsMaxBufLen]; sBuffer = new ArraySegment(buffer); received = await liveHandler.Socket.ReceiveAsync(sBuffer, liveHandler.TokenSource.Token); - count = (received.Count<4)? 0 : buffer[0]*256*1024 +buffer[1]*1024+buffer[2]*256 + buffer[3]; - _logger.LogInformation($"Received bytes : {count}"); + + _logger.LogInformation($"Received bytes : {received.Count}"); _logger.LogInformation($"Is the end : {received.EndOfMessage}"); - if (received.Count<=4 || count > Constants.WebSocketsMaxBufLen) { - if (received.CloseStatus.HasValue) { - _logger.LogInformation($"received a close status: {received.CloseStatus.Value.ToString()}: {received.CloseStatusDescription}"); - } - else { - _logger.LogError("Wrong packet size: "+count.ToString()); - _logger.LogError(JsonConvert.SerializeObject(received)); - } + fsInputQueue.Enqueue(sBuffer); + if (received.CloseStatus.HasValue) + { + endOfInput=true; + _logger.LogInformation($"received a close status: {received.CloseStatus.Value}: {received.CloseStatusDescription}"); + } } - else fsInputQueue.Enqueue(sBuffer); - while (ToClose.Count >0) + else endOfInput=true; + while (ToClose.Count > 0) { string no = ToClose.Pop(); _logger.LogInformation("Closing follower connection"); WebSocket listenningSocket; - if (liveHandler.Listeners.TryRemove(no, out listenningSocket)) { + if (liveHandler.Listeners.TryRemove(no, out listenningSocket)) + { await listenningSocket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "State != WebSocketState.Open", CancellationToken.None); listenningSocket.Dispose(); } } } - while (!received.CloseStatus.HasValue); + while (liveHandler.Socket.State == WebSocketState.Open); + _logger.LogInformation("Closing connection"); - endOfInput=true; taskWritingToFs.Wait(); - await liveHandler.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, received.CloseStatusDescription,liveHandler.TokenSource.Token ); - + await liveHandler.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, received.CloseStatusDescription, liveHandler.TokenSource.Token); + liveHandler.TokenSource.Cancel(); liveHandler.Dispose(); - _logger.LogInformation("Resulting file : " +JsonConvert.SerializeObject(taskWritingToFs.Result)); + _logger.LogInformation("Resulting file : " + JsonConvert.SerializeObject(taskWritingToFs.Result)); } catch (Exception ex) { @@ -200,16 +209,16 @@ namespace Yavsc.Services else { // Socket was not accepted open ... - // not (meta.Socket != null && meta.Socket.State == WebSocketState.Open) + // not (meta.Socket != null && meta.Socket.State == WebSocketState.Open) if (liveHandler.Socket != null) { - _logger.LogError($"meta.Socket.State not Open: {liveHandler.Socket.State.ToString()} "); + _logger.LogError($"meta.Socket.State not Open: {liveHandler.Socket.State} "); liveHandler.Socket.Dispose(); } else _logger.LogError("socket object is null"); } - + RemoveLiveInfo(uname); } catch (IOException ex) @@ -231,11 +240,11 @@ namespace Yavsc.Services void RemoveLiveInfo(string userName) { LiveCastHandler caster; - if (Casters.TryRemove(userName, out caster)) + if (Casters.TryRemove(userName, out caster)) _logger.LogInformation("removed live info"); - else + else _logger.LogError("could not remove live info"); } } -} \ No newline at end of file +} diff --git a/src/Yavsc/Services/MailSender.cs b/src/Yavsc/Services/MailSender.cs index d4700eb0..f16fe236 100644 --- a/src/Yavsc/Services/MailSender.cs +++ b/src/Yavsc/Services/MailSender.cs @@ -12,18 +12,14 @@ namespace Yavsc.Services { public class MailSender : IEmailSender { - private ILogger _logger; - SiteSettings siteSettings; - SmtpSettings smtpSettings; + readonly SiteSettings siteSettings; + readonly SmtpSettings smtpSettings; public MailSender( - ILoggerFactory loggerFactory, IOptions sitesOptions, - IOptions smtpOptions, - IOptions googleOptions + IOptions smtpOptions ) { - _logger = loggerFactory.CreateLogger(); siteSettings = sitesOptions?.Value; smtpSettings = smtpOptions?.Value; } diff --git a/src/Yavsc/Services/SIRENCheker.cs b/src/Yavsc/Services/SIRENCheker.cs index 83a096e9..0843e946 100644 --- a/src/Yavsc/Services/SIRENCheker.cs +++ b/src/Yavsc/Services/SIRENCheker.cs @@ -7,7 +7,7 @@ namespace Yavsc.Services using Models.societe.com; public class SIRENChecker { - private CompanyInfoSettings _settings; + private readonly CompanyInfoSettings _settings; public SIRENChecker(CompanyInfoSettings settings) { _settings = settings; diff --git a/src/Yavsc/Services/YavscMessageSender.cs b/src/Yavsc/Services/YavscMessageSender.cs index 88e8c94f..b5c52d6c 100644 --- a/src/Yavsc/Services/YavscMessageSender.cs +++ b/src/Yavsc/Services/YavscMessageSender.cs @@ -16,18 +16,16 @@ namespace Yavsc.Services { public class YavscMessageSender : IYavscMessageSender { - private ILogger _logger; - IEmailSender _emailSender; - SiteSettings siteSettings; - private IHubContext hubContext; - ApplicationDbContext _dbContext; - - IConnexionManager _cxManager; + private readonly ILogger _logger; + readonly IEmailSender _emailSender; + readonly SiteSettings siteSettings; + private readonly IHubContext hubContext; + readonly ApplicationDbContext _dbContext; + readonly IConnexionManager _cxManager; public YavscMessageSender( ILoggerFactory loggerFactory, IOptions sitesOptions, - IOptions smtpOptions, IEmailSender emailSender, ApplicationDbContext dbContext, IConnexionManager cxManager @@ -67,8 +65,10 @@ namespace Yavsc.Services foreach (var userId in raa) { _logger.LogDebug($"For performer id : {userId}"); - MessageWithPayloadResponse.Result result = new MessageWithPayloadResponse.Result(); - result.registration_id = userId; + MessageWithPayloadResponse.Result result = new MessageWithPayloadResponse.Result + { + registration_id = userId + }; var user = _dbContext.Users.FirstOrDefault(u => u.Id == userId); if (user == null) @@ -125,8 +125,10 @@ namespace Yavsc.Services { // from usr asp.net Id : var hubClient = hubContext.Clients.User(userId); var hubClient = hubContext.Clients.Client(cxid); - var data = new Dictionary(); - data["event"] = JsonConvert.SerializeObject(ev); + var data = new Dictionary + { + ["event"] = JsonConvert.SerializeObject(ev) + }; hubClient.push(ev.Topic, JsonConvert.SerializeObject(data)); } diff --git a/src/Yavsc/Startup/Startup.OAuth.cs b/src/Yavsc/Startup/Startup.OAuth.cs index 1961ef3b..f603be93 100644 --- a/src/Yavsc/Startup/Startup.OAuth.cs +++ b/src/Yavsc/Startup/Startup.OAuth.cs @@ -91,8 +91,7 @@ namespace Yavsc // ; } - private void ConfigureOAuthApp(IApplicationBuilder app, - SiteSettings settingsOptions, ILogger logger) + private void ConfigureOAuthApp(IApplicationBuilder app) { app.UseIdentity(); diff --git a/src/Yavsc/Startup/Startup.SanityChecks.cs b/src/Yavsc/Startup/Startup.SanityChecks.cs index 1615efcb..9f44fbd3 100644 --- a/src/Yavsc/Startup/Startup.SanityChecks.cs +++ b/src/Yavsc/Startup/Startup.SanityChecks.cs @@ -13,15 +13,9 @@ namespace Yavsc // * an AppData folder public partial class Startup { - public void CheckServices(IServiceCollection services) - { - - } - public void CheckApp(IApplicationBuilder app, - SiteSettings siteSettings, IHostingEnvironment env, - ILoggerFactory loggerFactory - ) + public void CheckApp(IHostingEnvironment env, + ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger(); diff --git a/src/Yavsc/Startup/Startup.WebSockets.cs b/src/Yavsc/Startup/Startup.WebSockets.cs index 187c7c19..60abe721 100644 --- a/src/Yavsc/Startup/Startup.WebSockets.cs +++ b/src/Yavsc/Startup/Startup.WebSockets.cs @@ -11,8 +11,7 @@ namespace Yavsc { public partial class Startup { - public void ConfigureWebSocketsApp(IApplicationBuilder app, - SiteSettings siteSettings, IHostingEnvironment env) + public void ConfigureWebSocketsApp(IApplicationBuilder app) { var webSocketOptions = new WebSocketOptions() { @@ -25,7 +24,7 @@ namespace Yavsc app.UseSignalR(PathString.FromUriComponent(Constants.SignalRPath)); } - private async Task Echo(HttpContext context, WebSocket webSocket) + private async Task Echo(WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); diff --git a/src/Yavsc/Startup/Startup.Workflow.cs b/src/Yavsc/Startup/Startup.Workflow.cs index 98ede09f..75456e8f 100644 --- a/src/Yavsc/Startup/Startup.Workflow.cs +++ b/src/Yavsc/Startup/Startup.Workflow.cs @@ -30,7 +30,7 @@ namespace Yavsc /// public static readonly string[] Forms = new string[] { "Profiles", "HairCut" }; - private void ConfigureWorkflow(IApplicationBuilder app, SiteSettings settings, ILogger logger) + private void ConfigureWorkflow() { // System.AppDomain.CurrentDomain.ResourceResolve += OnYavscResourceResolve; @@ -50,7 +50,7 @@ namespace Yavsc } catch (Exception ex) { - logger.LogError(ex.TargetSite.Name); + _logger.LogError(ex.TargetSite.Name); } @@ -64,7 +64,7 @@ namespace Yavsc // TODO swith () case {} if (typeof(IQueryable).IsAssignableFrom(propinfo.PropertyType)) {// double-bingo - logger.LogVerbose($"Pro: {propinfo.Name}"); + _logger.LogVerbose($"Pro: {propinfo.Name}"); BillingService.UserSettings.Add(propinfo); } else @@ -75,7 +75,7 @@ namespace Yavsc base de donnée porte l'attribut [ActivitySetting], mais n'implemente pas l'interface IQueryable ({propinfo.MemberType.GetType()})"; - logger.LogCritical(msg); + _logger.LogCritical(msg); } } } diff --git a/src/Yavsc/Startup/Startup.cs b/src/Yavsc/Startup/Startup.cs index 81f085b6..dc6df702 100755 --- a/src/Yavsc/Startup/Startup.cs +++ b/src/Yavsc/Startup/Startup.cs @@ -278,7 +278,6 @@ namespace Yavsc { options.ResourcesPath = "Resources"; }); - CheckServices(services); } static ApplicationDbContext _dbContext; public static IServiceProvider Services { get; private set; } @@ -288,7 +287,6 @@ namespace Yavsc IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext dbContext, IOptions siteSettings, IOptions localizationOptions, - IOptions oauth2SettingsContainer, IAuthorizationService authorizationService, IOptions payPalSettings, IOptions googleSettings, @@ -355,8 +353,10 @@ namespace Yavsc app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); - var epo = new ErrorPageOptions(); - epo.SourceCodeLineCount = 20; + var epo = new ErrorPageOptions + { + SourceCodeLineCount = 20 + }; app.UseDeveloperExceptionPage(epo); app.UseDatabaseErrorPage( x => @@ -404,19 +404,22 @@ namespace Yavsc }); app.UseSession(); - ConfigureOAuthApp(app, SiteSetup, _logger); + ConfigureOAuthApp(app); ConfigureFileServerApp(app, SiteSetup, env, authorizationService); app.UseRequestLocalization(localizationOptions.Value, (RequestCulture)new RequestCulture((string)"en-US")); - ConfigureWorkflow(app, SiteSetup, _logger); + ConfigureWorkflow(); + // Empty this odd chat user list from db + /* foreach (var p in dbContext.ChatConnection) { dbContext.Entry(p).State = EntityState.Deleted; } dbContext.SaveChanges(); + FIXME */ - ConfigureWebSocketsApp(app, SiteSetup, env); + ConfigureWebSocketsApp(app); app.UseMvc(routes => { @@ -451,7 +454,7 @@ namespace Yavsc } }); - CheckApp(app, SiteSetup, env, loggerFactory); + CheckApp( env, loggerFactory); } // Entry point for the application. diff --git a/src/Yavsc/ViewComponents/BillViewComponent.cs b/src/Yavsc/ViewComponents/BillViewComponent.cs index fce17e1b..5fb0c7da 100644 --- a/src/Yavsc/ViewComponents/BillViewComponent.cs +++ b/src/Yavsc/ViewComponents/BillViewComponent.cs @@ -16,20 +16,17 @@ namespace Yavsc.ViewComponents { public class BillViewComponent : ViewComponent { - ApplicationDbContext dbContext; - IBillingService billing; - IStringLocalizer localizer; - ILogger logger ; + readonly ApplicationDbContext dbContext; + readonly IBillingService billing; + readonly IStringLocalizer localizer; public BillViewComponent(ApplicationDbContext dbContext, IStringLocalizer localizer, - IBillingService billing, - ILoggerFactory loggerFactory) + IBillingService billing) { this.billing = billing; this.dbContext = dbContext; this.localizer = localizer; - logger = loggerFactory.CreateLogger(); } public async Task InvokeAsync(string code, IBillable billable, OutputFormat format, bool asBill) diff --git a/src/Yavsc/ViewComponents/BlogIndexViewComponent.cs b/src/Yavsc/ViewComponents/BlogIndexViewComponent.cs index 07af5325..04901b64 100644 --- a/src/Yavsc/ViewComponents/BlogIndexViewComponent.cs +++ b/src/Yavsc/ViewComponents/BlogIndexViewComponent.cs @@ -13,19 +13,11 @@ namespace Yavsc.ViewComponents { public class BlogIndexViewComponent: ViewComponent { - ILogger _logger; - private ApplicationDbContext _context; - private IAuthorizationService _authorizationService; + private readonly ApplicationDbContext _context; public BlogIndexViewComponent( - ApplicationDbContext context, - UserManager userManager, - ILoggerFactory loggerFactory, - IAuthorizationService authorizationService, - IOptions siteSettings) + ApplicationDbContext context) { _context = context; - _logger = loggerFactory.CreateLogger(); - _authorizationService = authorizationService; } // Renders blog index ofr the specified user by name diff --git a/src/Yavsc/ViewComponents/CalendarViewComponent.cs b/src/Yavsc/ViewComponents/CalendarViewComponent.cs index 74385fe9..519d01b4 100644 --- a/src/Yavsc/ViewComponents/CalendarViewComponent.cs +++ b/src/Yavsc/ViewComponents/CalendarViewComponent.cs @@ -8,8 +8,8 @@ namespace Yavsc.ViewComponents { public class CalendarViewComponent : ViewComponent { - ApplicationDbContext _dbContext; - ICalendarManager _manager; + readonly ApplicationDbContext _dbContext; + readonly ICalendarManager _manager; public CalendarViewComponent ( ApplicationDbContext dbContext, @@ -47,4 +47,4 @@ namespace Yavsc.ViewComponents return View(model); } } -} \ No newline at end of file +} diff --git a/src/Yavsc/ViewComponents/TaggerComponent.cs b/src/Yavsc/ViewComponents/TaggerComponent.cs index c8580d85..0d0f02e0 100644 --- a/src/Yavsc/ViewComponents/TaggerComponent.cs +++ b/src/Yavsc/ViewComponents/TaggerComponent.cs @@ -9,17 +9,14 @@ namespace Yavsc.ViewComponents public class TaggerViewComponent : ViewComponent { - ApplicationDbContext dbContext; - IStringLocalizer localizer; - ILogger logger ; + readonly ApplicationDbContext dbContext; + readonly IStringLocalizer localizer; public TaggerViewComponent( ApplicationDbContext pdbContext, - IStringLocalizer pLocalizer, - ILoggerFactory loggerFactory) + IStringLocalizer pLocalizer) { dbContext = pdbContext; this.localizer = pLocalizer; - this.logger = loggerFactory.CreateLogger(); } public IViewComponentResult Invoke(ITaggable longTaggable) { @@ -29,4 +26,4 @@ namespace Yavsc.ViewComponents return View(longTaggable); } } -} \ No newline at end of file +} diff --git a/src/Yavsc/ViewModels/Streaming/LiveCastHandler.cs b/src/Yavsc/ViewModels/Streaming/LiveCastHandler.cs index d959263d..cffaf87b 100644 --- a/src/Yavsc/ViewModels/Streaming/LiveCastHandler.cs +++ b/src/Yavsc/ViewModels/Streaming/LiveCastHandler.cs @@ -41,10 +41,12 @@ namespace Yavsc.ViewModels.Streaming // this process is not safe at concurrent access. long usage = user.DiskUsage; - var item = new FileRecievedInfo(); - item.FileName = AbstractFileSystemHelpers.FilterFileName (destFileName); - item.MimeType = contentType; - item.DestDir = root; + var item = new FileRecievedInfo + { + FileName = AbstractFileSystemHelpers.FilterFileName(destFileName), + MimeType = contentType, + DestDir = root + }; var fi = new FileInfo(Path.Combine(root, item.FileName)); if (fi.Exists) { @@ -59,26 +61,17 @@ namespace Yavsc.ViewModels.Streaming { if (queue.Count>0) { var buffer = queue.Dequeue(); - int count = buffer.Array[0]*256*1024 +buffer.Array[1]*1024+buffer.Array[2]*256 + buffer.Array[3]; - if (count >0 && count <= Constants.WebSocketsMaxBufLen - && buffer.Array.Length >= count+4) { - logger.LogInformation($"writing {count} bytes from {buffer.Array.Length}."); + logger.LogInformation($"writing {buffer.Array.Length} bytes..."); - await dest.WriteAsync(buffer.Array, 4, count); - logger.LogInformation($"wrote {count} bytes."); - usage += count; - } - else { - var packetInfo = JsonConvert.SerializeObject(buffer); - logger.LogError($"didn´t wrote {count} bytes from {buffer.Array.Length}!\n{packetInfo}"); - } + await dest.WriteAsync(buffer.Array, 0, buffer.Array.Length); + logger.LogInformation($"done."); + usage += buffer.Array.Length; + } if (usage >= user.DiskQuota) break; if (queue.Count==0 && !isEndOfInput()) { - logger.LogInformation($"Waitting 200ms."); await Task.Delay(100); - logger.LogInformation($"Done waiting"); } } user.DiskUsage = usage; @@ -93,4 +86,4 @@ namespace Yavsc.ViewModels.Streaming } -} \ No newline at end of file +} diff --git a/src/cli/Commands/AuthCommander.cs b/src/cli/Commands/AuthCommander.cs index 0c2d7574..69429263 100644 --- a/src/cli/Commands/AuthCommander.cs +++ b/src/cli/Commands/AuthCommander.cs @@ -16,13 +16,12 @@ namespace cli.Commands private CommandOption _secret; private CommandOption _scope; private CommandOption _save; - - ILogger _logger; + readonly ILogger _logger; public AuthCommander(ILoggerFactory loggerFactory) - { - _logger = loggerFactory.CreateLogger(); - } + { + _logger = loggerFactory.CreateLogger(); + } public CommandLineApplication Integrate(CommandLineApplication rootApp) { @@ -32,37 +31,41 @@ namespace cli.Commands target.FullName = "Authentication methods"; target.Description = "Login, save credentials and get authorized."; target.HelpOption("-? | -h | --help"); - var loginCommand = target.Command("login", app => { + var loginCommand = target.Command("login", app => + { _login = app.Argument("login", "login to use", true); _apiKey = app.Option("-a | --api", "API key to use against authorization server", CommandOptionType.SingleValue); - _secret = app.Option( "-e | --secret", "Secret phrase associated to API key", CommandOptionType.SingleValue); - _scope = app.Option( "-c | --scope", "invoked scope asking for a security token", CommandOptionType.SingleValue); - _save = app.Option( "-s | --save", "Save authentication token to given file", CommandOptionType.SingleValue); + _secret = app.Option("-e | --secret", "Secret phrase associated to API key", CommandOptionType.SingleValue); + _scope = app.Option("-c | --scope", "invoked scope asking for a security token", CommandOptionType.SingleValue); + _save = app.Option("-s | --save", "Save authentication token to given file", CommandOptionType.SingleValue); app.HelpOption("-? | -h | --help"); - } ); - loginCommand.OnExecute(async ()=> + }); + loginCommand.OnExecute(async () => { - var authUrl = Startup.ConnectionSettings.AuthorizeUrl; - var redirect = Startup.ConnectionSettings.RedirectUrl; - var tokenUrl = Startup.ConnectionSettings.AccessTokenUrl; + string authUrl = Startup.ConnectionSettings.AuthorizeUrl; + string redirect = Startup.ConnectionSettings.RedirectUrl; + string tokenUrl = Startup.ConnectionSettings.AccessTokenUrl; - var oauthor = new OAuthenticator(_apiKey.HasValue() ? _apiKey.Value() : Startup.ConnectionSettings.ClientId, - _secret.HasValue() ? _secret.Value() : Startup.ConnectionSettings.ClientSecret, - _scope.HasValue() ? _scope.Value() : Startup.ConnectionSettings.Scope, - new Uri(authUrl), new Uri(redirect), new Uri(tokenUrl)); - var query = new Dictionary(); - query["username"] = _login.Value; - query["password"] = GetPassword(_login.Value); - query["grant_type"] = "password"; - try { + OAuthenticator oauthor = new OAuthenticator(_apiKey.HasValue() ? _apiKey.Value() : Startup.ConnectionSettings.ClientId, + _secret.HasValue() ? _secret.Value() : Startup.ConnectionSettings.ClientSecret, + _scope.HasValue() ? _scope.Value() : Startup.ConnectionSettings.Scope, + new Uri(authUrl), new Uri(redirect), new Uri(tokenUrl)); + Dictionary query = new Dictionary + { + ["username"] = _login.Value, + ["password"] = GetPassword(_login.Value), + ["grant_type"] = "password" + }; + try + { var result = await oauthor.RequestAccessTokenAsync(query); Startup.UserConnectionSettings.AccessToken = result["access_token"]; Startup.UserConnectionSettings.ExpiresIn = result["expires_in"]; Startup.UserConnectionSettings.RefreshToken = result["refresh_token"]; Startup.UserConnectionSettings.TokenType = result["token_type"]; Startup.UserConnectionSettings.UserName = _login.Value; - Startup.SaveCredentials(_save.HasValue() ? _save.Value() : Startup.UserConnectionsettingsFileName); - + Startup.SaveCredentials(_save.HasValue() ? _save.Value() : Startup.UserConnectionsettingsFileName); + } catch (Exception ex) { @@ -112,6 +115,6 @@ namespace cli.Commands Console.WriteLine(); return pwd.ToString(); } - + } -} \ No newline at end of file +} diff --git a/src/cli/Commands/Builder.cs b/src/cli/Commands/Builder.cs index 66e59e9e..319ddc73 100644 --- a/src/cli/Commands/Builder.cs +++ b/src/cli/Commands/Builder.cs @@ -2,9 +2,10 @@ using System.IO; using Yavsc.Server.Models.IT; using Yavsc.Server.Models.IT.SourceCode; -public class Builder { - string _gitRepository; - private Project _projectInfo; +public class Builder +{ + readonly string _gitRepository; + private readonly Project _projectInfo; public Builder() { @@ -21,4 +22,4 @@ public class Builder { clone.Launch(_projectInfo); } -} \ No newline at end of file +} diff --git a/src/cli/Commands/GenerationCommander.cs b/src/cli/Commands/GenerationCommander.cs index 7d7581b1..c30d26c9 100644 --- a/src/cli/Commands/GenerationCommander.cs +++ b/src/cli/Commands/GenerationCommander.cs @@ -58,7 +58,6 @@ namespace cli.Commands logger.LogInformation($"Using parameters : modelFullName:{modelFullName} nameSpace:{nameSpace} dbContext:{dbContext} controllerName:{controllerName} relativePath:{relativePath}"); generator.Generate(modelFullName, - nameSpace, dbContext, controllerName, relativePath); @@ -70,4 +69,4 @@ namespace cli.Commands return cmd; } } -} \ No newline at end of file +} diff --git a/src/cli/Commands/Streamer.cs b/src/cli/Commands/Streamer.cs index bd22e548..406e62ed 100644 --- a/src/cli/Commands/Streamer.cs +++ b/src/cli/Commands/Streamer.cs @@ -12,10 +12,10 @@ using Yavsc.Abstract; namespace cli { public class Streamer: ICommander { - private ClientWebSocket _client; - private ILogger _logger; - private ConnectionSettings _cxSettings; - private UserConnectionSettings _userCxSettings; + private readonly ClientWebSocket _client; + private readonly ILogger _logger; + private readonly ConnectionSettings _cxSettings; + private readonly UserConnectionSettings _userCxSettings; private CommandOption _fileOption; private CommandArgument _flowIdArg; private CancellationTokenSource _tokenSource; @@ -83,42 +83,22 @@ namespace cli { await _client.ConnectAsync(new Uri(url), _tokenSource.Token); _logger.LogInformation("Connected"); const int bufLen = Yavsc.Constants.WebSocketsMaxBufLen; - byte [] buffer = new byte[bufLen+4*sizeof(int)]; + byte [] buffer = new byte[bufLen]; const int offset=0; - int read = 0; - /* - var reciving = Task.Run(async ()=> { - byte [] readbuffer = new byte[bufLen]; - var rb = new ArraySegment(readbuffer, 0, bufLen); - bool continueReading = false; - do { - var result = await _client.ReceiveAsync(rb, _tokenSource.Token); - _logger.LogInformation($"received {result.Count} bytes"); - continueReading = !result.CloseStatus.HasValue; - } while (continueReading); - } ); */ + int read; + bool lastFrame; - do { - read = await stream.ReadAsync(buffer, offset + sizeof(int), bufLen); - if (read>0) { - // assert sizeof(int)==4 - buffer[3]= (byte) (read % 256); - var left = read / 256; - buffer[2]= (byte) (left % 256); - left = left / 256; - buffer[1] = (byte) (left % 256); - left = left /256; - buffer[0]=(byte) (byte) (left % 256); - var segment = new ArraySegment(buffer, offset, read+4); - - - await _client.SendAsync(new ArraySegment(buffer), WebSocketMessageType.Binary, false, _tokenSource.Token); - _logger.LogInformation($"sent {segment.Count} "); - } - - } while (read>0); - // reciving.Wait(); - await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, "EOF", _tokenSource.Token); + WebSocketMessageType pckType = WebSocketMessageType.Binary; + do + { + read = await stream.ReadAsync(buffer, offset, bufLen); + lastFrame = read < Yavsc.Constants.WebSocketsMaxBufLen; + ArraySegment segment = new ArraySegment(buffer, offset, read); + await _client.SendAsync(new ArraySegment(buffer), pckType, lastFrame, _tokenSource.Token); + _logger.LogInformation($"sent {segment.Count} "); + } while (!lastFrame); + _logger.LogInformation($"Closing socket"); + await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, "EOF", _tokenSource.Token); } - } + } } diff --git a/src/cli/Helpers/ConsoleHelpers.cs b/src/cli/Helpers/ConsoleHelpers.cs index b17cdea8..dc2f5fe8 100644 --- a/src/cli/Helpers/ConsoleHelpers.cs +++ b/src/cli/Helpers/ConsoleHelpers.cs @@ -13,15 +13,9 @@ namespace cli.Helpers return commander.Integrate(rootApp); } - static OAuthenticator OAuthorInstance { get; set; } + public static OAuthenticator OAuthorInstance { get; private set; } public static OAuthenticator InitAuthor( - this ConnectionSettings settings, - string clientId, - string clientSecret, - string scope, - string authorizeUrl, - string redirectUrl, - string accessTokenUrl) + this ConnectionSettings settings) { return OAuthorInstance = new OAuthenticator(settings.ClientId, settings.ClientSecret, @@ -71,4 +65,4 @@ namespace cli.Helpers } -} \ No newline at end of file +} diff --git a/src/cli/Misc/YavscServerFactory.cs b/src/cli/Misc/YavscServerFactory.cs index 8ee6e044..0a5ccc92 100644 --- a/src/cli/Misc/YavscServerFactory.cs +++ b/src/cli/Misc/YavscServerFactory.cs @@ -6,7 +6,7 @@ using Microsoft.Extensions.Configuration; namespace Yavsc.Server { - public class cliServerFactory : IServerFactory + public class CliServerFactory : IServerFactory { public IFeatureCollection Initialize(IConfiguration configuration) { diff --git a/src/cli/Program.cs b/src/cli/Program.cs index 2228812c..f6e9270f 100644 --- a/src/cli/Program.cs +++ b/src/cli/Program.cs @@ -65,23 +65,27 @@ namespace cli var services = new ServiceCollection(); // create a service provider with the HostEnvironment. - HostingEnvironment = new HostingEnvironment(); - HostingEnvironment.EnvironmentName = appEnv.Configuration; + HostingEnvironment = new HostingEnvironment + { + EnvironmentName = appEnv.Configuration + }; var startup = new Startup(HostingEnvironment, appEnv); startup.ConfigureServices(services); services.AddInstance(HostingEnvironment); var serviceProvider = services.BuildServiceProvider(); - var app = new ApplicationBuilder(serviceProvider); - app.ApplicationServices = serviceProvider; - + var app = new ApplicationBuilder(serviceProvider) + { + ApplicationServices = serviceProvider + }; + var siteSettings = serviceProvider.GetRequiredService>(); var cxSettings = serviceProvider.GetRequiredService>(); var userCxSettings = serviceProvider.GetRequiredService>(); var loggerFactory = serviceProvider.GetRequiredService(); - startup.Configure(app, HostingEnvironment, siteSettings, cxSettings, userCxSettings, loggerFactory); + startup.Configure(cxSettings, userCxSettings, loggerFactory); return app; } @@ -95,12 +99,14 @@ namespace cli [STAThread] public static int Main(string[] args) { - CommandLineApplication cliapp = new CommandLineApplication(false); - cliapp.Name = "cli"; - cliapp.FullName = "Yavsc command line interface"; - cliapp.Description = "Dnx console app for yavsc server side"; - cliapp.ShortVersionGetter = () => "v1.0"; - cliapp.LongVersionGetter = () => "version 1.0 (stable)"; + CommandLineApplication cliapp = new CommandLineApplication(false) + { + Name = "cli", + FullName = "Yavsc command line interface", + Description = "Dnx console app for yavsc server side", + ShortVersionGetter = () => "v1.0", + LongVersionGetter = () => "version 1.0 (stable)" + }; // calling a Startup sequence var appBuilder = ConfigureApplication(); diff --git a/src/cli/Services/EMailer.cs b/src/cli/Services/EMailer.cs index 47030185..e2063994 100644 --- a/src/cli/Services/EMailer.cs +++ b/src/cli/Services/EMailer.cs @@ -26,13 +26,12 @@ namespace cli.Services const string DefaultBaseClassName = "ATemplate"; const string DefaultBaseClass = nameof(UserOrientedTemplate); const string DefaultNamespace = "CompiledRazorTemplates"; - - RazorTemplateEngine razorEngine; - IStringLocalizer stringLocalizer; - ILogger logger; - ApplicationDbContext dbContext; - IEmailSender mailSender; - RazorEngineHost host; + readonly RazorTemplateEngine razorEngine; + readonly IStringLocalizer stringLocalizer; + readonly ILogger logger; + readonly ApplicationDbContext dbContext; + readonly IEmailSender mailSender; + readonly RazorEngineHost host; public EMailer(ApplicationDbContext context, IEmailSender sender, IStringLocalizer localizer, ILoggerFactory loggerFactory) { diff --git a/src/cli/Services/MvcGenerator.cs b/src/cli/Services/MvcGenerator.cs index 8413086d..8895bca2 100644 --- a/src/cli/Services/MvcGenerator.cs +++ b/src/cli/Services/MvcGenerator.cs @@ -7,9 +7,9 @@ namespace cli.Services public class MvcGenerator : CommandLineGenerator { - CommandLineGeneratorModel _model; - ILogger _logger; - public MvcGenerator (IServiceProvider services, ILoggerFactory loggerFactory): base (services) + readonly CommandLineGeneratorModel _model; + readonly ILogger _logger; + public MvcGenerator(IServiceProvider services, ILoggerFactory loggerFactory) : base(services) { _model = new CommandLineGeneratorModel(); _logger = loggerFactory.CreateLogger(); @@ -17,7 +17,6 @@ namespace cli.Services public async void Generate( string modelClass, - string ns, string dbContextFullName, string controllerName, string relativeFolderPath @@ -33,4 +32,4 @@ namespace cli.Services await GenerateCode(_model); } } -} \ No newline at end of file +} diff --git a/src/cli/Startup.cs b/src/cli/Startup.cs index 94459ce6..7562247a 100644 --- a/src/cli/Startup.cs +++ b/src/cli/Startup.cs @@ -250,8 +250,7 @@ Microsoft.Extensions.CodeGeneration.ICodeGeneratorActionsService), Services = services; } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, - IOptions siteSettings, + public void Configure( IOptions cxSettings, IOptions useCxSettings, ILoggerFactory loggerFactory) diff --git a/src/cli/project.json b/src/cli/project.json index 5f526656..d3660ef3 100644 --- a/src/cli/project.json +++ b/src/cli/project.json @@ -45,7 +45,7 @@ "Microsoft.Extensions.WebEncoders.Core": "1.0.0-rc1-final", "Microsoft.Framework.Configuration.Json": "1.0.0-beta8", "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4", - "Newtonsoft.Json": "6.0.1-beta1", + "Newtonsoft.Json": "7.0.1", "NJsonSchema.CodeGeneration.CSharp": "10.0.27", "Yavsc": { "target": "project" diff --git a/src/sampleWebAsWebApiClient/Controllers/HomeController.cs b/src/sampleWebAsWebApiClient/Controllers/HomeController.cs index 7db37add..977d1bdd 100755 --- a/src/sampleWebAsWebApiClient/Controllers/HomeController.cs +++ b/src/sampleWebAsWebApiClient/Controllers/HomeController.cs @@ -15,25 +15,26 @@ namespace testOauthClient.Controllers public class HomeController : Controller { readonly ILogger _logger; - - public class GCMRegistrationRecord { - public string GCMRegistrationId { get; set; } = "testGoogleRegistrationIdValue"; - public string DeviceId { get; set; }= "TestDeviceId"; - public string Model { get; set; }= "TestModel"; - public string Platform { get; set; }= "External Web"; - public string Version { get; set; }= "0.0.1-rc1"; - } - + + public class GCMRegistrationRecord + { + public string GCMRegistrationId { get; set; } = "testGoogleRegistrationIdValue"; + public string DeviceId { get; set; } = "TestDeviceId"; + public string Model { get; set; } = "TestModel"; + public string Platform { get; set; } = "External Web"; + public string Version { get; set; } = "0.0.1-rc1"; + } + public HomeController(ILoggerFactory loggerFactory) { - _logger=loggerFactory.CreateLogger(); + _logger = loggerFactory.CreateLogger(); } [HttpGet] public IActionResult Index() { return View(); } - + [HttpPost] public async Task GetUserInfo(CancellationToken cancellationToken) { @@ -54,38 +55,41 @@ namespace testOauthClient.Controllers [HttpPost] public async Task PostFiles(string subdir) { - string results = null; + string results; _logger.LogInformation($"{Request.Form.Files.Count} file(s) to send"); - - // TODO better uri construction in production environment - List args = new List(); - foreach (var formFile in Request.Form.Files) + + // TODO better uri construction in production environment + List args = new List(); + foreach (var formFile in Request.Form.Files) + { + _logger.LogWarning($"Treating {formFile.ContentDisposition}"); + MemoryStream memStream = new MemoryStream(); + const int sz = 1024 * 64; + byte[] buffer = new byte[sz]; + using (var innerStream = formFile.OpenReadStream()) + { + int szRead = 0; + do { - _logger.LogWarning($"Treating {formFile.ContentDisposition}"); - var memStream = new MemoryStream(); - const int sz = 1024*64; - byte [] buffer = new byte[sz]; - using (var innerStream = formFile.OpenReadStream()) { - int szRead = 0; - do { - szRead = innerStream.Read(buffer,0,sz); - memStream.Write(buffer,0,szRead); - } while (szRead>0); - } - memStream.Seek(0,SeekOrigin.Begin); - args.Add( - new FormFile { - ContentDisposition = formFile.ContentDisposition, - ContentType = formFile.ContentType, - Stream = memStream - }); - } - string uri = "http://dev.pschneider.fr/api/fs/"+System.Uri.EscapeDataString(subdir); - _logger.LogInformation($"Posting data to '{uri}'..."); - - results = await RequestHelper.PostMultipart(uri, args.ToArray(), AccessToken); - _logger.LogInformation("Data posted."); - + szRead = innerStream.Read(buffer, 0, sz); + memStream.Write(buffer, 0, szRead); + } while (szRead > 0); + } + memStream.Seek(0, SeekOrigin.Begin); + args.Add( + new FormFile + { + ContentDisposition = formFile.ContentDisposition, + ContentType = formFile.ContentType, + Stream = memStream + }); + } + string uri = "http://dev.pschneider.fr/api/fs/" + System.Uri.EscapeDataString(subdir); + _logger.LogInformation($"Posting data to '{uri}'..."); + + results = await RequestHelper.PostMultipart(uri, args.ToArray(), AccessToken); + _logger.LogInformation("Data posted."); + return View("Index", model: results); } @@ -109,14 +113,16 @@ namespace testOauthClient.Controllers GCMRegistrationRecord result = null; var authHeader = $"Bearer {AccessToken}"; _logger.LogWarning($"using authorization Header {authHeader}"); - try { + try + { + - using (var request = new SimpleJsonPostMethod( "http://dev.pschneider.fr/api/gcm/register", authHeader)) { result = await request.Invoke(new - GCMRegistrationRecord { + GCMRegistrationRecord + { GCMRegistrationId = "testGoogleRegistrationIdValue", DeviceId = "TestDeviceId", Model = "TestModel", @@ -125,8 +131,9 @@ namespace testOauthClient.Controllers }); } } - catch (Exception ex) { - return View("Index", model: new { error = ex.Message }); + catch (Exception ex) + { + return View("Index", model: new { error = ex.Message }); } return View("Index", model: result?.ToString()); } diff --git a/src/sampleWebAsWebApiClient/project.json b/src/sampleWebAsWebApiClient/project.json index a58f6345..731c76e7 100755 --- a/src/sampleWebAsWebApiClient/project.json +++ b/src/sampleWebAsWebApiClient/project.json @@ -29,7 +29,7 @@ "Microsoft.Extensions.Logging": "1.0.0-rc1-final", "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final", "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final", - "Newtonsoft.Json": "6.0.1-beta1" + "Newtonsoft.Json": "7.0.1" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://*:5002" diff --git a/src/test/Mandatory/AbstractTests.cs b/src/test/Mandatory/AbstractTests.cs index aa236879..6c953645 100644 --- a/src/test/Mandatory/AbstractTests.cs +++ b/src/test/Mandatory/AbstractTests.cs @@ -9,7 +9,7 @@ namespace test [Trait("regres", "no")] public class AbstractTests { - ITestOutputHelper output; + readonly ITestOutputHelper output; public AbstractTests(ITestOutputHelper output) { this.output = output; diff --git a/src/test/Mandatory/BatchTests.cs b/src/test/Mandatory/BatchTests.cs index 110440c4..27c6c72f 100644 --- a/src/test/Mandatory/BatchTests.cs +++ b/src/test/Mandatory/BatchTests.cs @@ -60,10 +60,12 @@ namespace test [Fact] void AnsiToHtml() { - var procStart = new ProcessStartInfo("ls", "-l --color=always"); - procStart.UseShellExecute = false; - procStart.RedirectStandardInput = false; - procStart.RedirectStandardOutput = true; + var procStart = new ProcessStartInfo("ls", "-l --color=always") + { + UseShellExecute = false, + RedirectStandardInput = false, + RedirectStandardOutput = true + }; var proc = Process.Start(procStart); var encoded = AnsiToHtmlEncoder.GetStream(proc.StandardOutput); using (var reader = new StreamReader(encoded)) @@ -99,12 +101,14 @@ namespace test internal static BeforeCompileContext CreateYavscCompilationContext() { - var projectContext = new ProjectContext(); - projectContext.Name = "Yavsc"; - projectContext.ProjectDirectory = "../Yavsc"; - projectContext.ProjectFilePath = "../Yavsc/project.json"; - projectContext.TargetFramework = new FrameworkName("DNX", new Version(4, 5, 1)); - projectContext.Configuration = Environment.GetEnvironmentVariable("ASPNET_ENV"); + var projectContext = new ProjectContext + { + Name = "Yavsc", + ProjectDirectory = "../Yavsc", + ProjectFilePath = "../Yavsc/project.json", + TargetFramework = new FrameworkName("DNX", new Version(4, 5, 1)), + Configuration = Environment.GetEnvironmentVariable("ASPNET_ENV") + }; return new BeforeCompileContext( null, projectContext, () => null, () => null, () => null); diff --git a/src/test/Mandatory/Database.cs b/src/test/Mandatory/Database.cs index 7d76ef6d..a7950998 100644 --- a/src/test/Mandatory/Database.cs +++ b/src/test/Mandatory/Database.cs @@ -9,8 +9,8 @@ namespace test.Mandatory [Trait("dev", "wip")] public class Database: IClassFixture, IDisposable { - ServerSideFixture _serverFixture; - ITestOutputHelper output; + readonly ServerSideFixture _serverFixture; + readonly ITestOutputHelper output; public Database(ServerSideFixture serverFixture, ITestOutputHelper output) { this.output = output; diff --git a/src/test/Mandatory/EMailling.cs b/src/test/Mandatory/EMailling.cs index d5410f9e..1013da78 100644 --- a/src/test/Mandatory/EMailling.cs +++ b/src/test/Mandatory/EMailling.cs @@ -11,9 +11,9 @@ namespace test public class EMaillingTests : IClassFixture { - ServerSideFixture _serverFixture; - ITestOutputHelper output; - ILogger _logger; + readonly ServerSideFixture _serverFixture; + readonly ITestOutputHelper output; + readonly ILogger _logger; public EMaillingTests(ServerSideFixture serverFixture, ITestOutputHelper output) { this.output = output; diff --git a/src/test/Mandatory/NodeTests.cs b/src/test/Mandatory/NodeTests.cs index e6e5c96c..5863e4b3 100755 --- a/src/test/Mandatory/NodeTests.cs +++ b/src/test/Mandatory/NodeTests.cs @@ -12,12 +12,14 @@ namespace test [Fact] void TestNodeJsForAnsitohtml () { - var procStart = new ProcessStartInfo("node", "node_modules/ansi-to-html/bin/ansi-to-html"); - procStart.UseShellExecute = false; - procStart.RedirectStandardInput = true; - procStart.RedirectStandardOutput = true; - procStart.RedirectStandardError = true; - var proc = Process.Start(procStart); + var procStart = new ProcessStartInfo("node", "node_modules/ansi-to-html/bin/ansi-to-html") + { + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + var proc = Process.Start(procStart); proc.StandardInput.WriteLine("\x001b[30mblack\x1b[37mwhite"); proc.StandardInput.Close(); while (!proc.StandardOutput.EndOfStream) @@ -29,10 +31,12 @@ namespace test [Fact] void AnsiToHtml() { - var procStart = new ProcessStartInfo("ls", "-l --color=always"); - procStart.UseShellExecute = false; - procStart.RedirectStandardInput = false; - procStart.RedirectStandardOutput = true; + var procStart = new ProcessStartInfo("ls", "-l --color=always") + { + UseShellExecute = false, + RedirectStandardInput = false, + RedirectStandardOutput = true + }; var proc = Process.Start(procStart); var encoded = GetStream(proc.StandardOutput); var reader = new StreamReader(encoded); diff --git a/src/test/project.json b/src/test/project.json index 56a893fa..c85b7dac 100644 --- a/src/test/project.json +++ b/src/test/project.json @@ -39,7 +39,7 @@ "EntityFramework.Commands": "7.0.0-rc1-final", "EntityFramework7.Npgsql": "3.1.0-rc1-3", "EntityFramework7.Npgsql.Design": "3.1.0-rc1-5", - "Newtonsoft.Json": "6.0.1-beta1", + "Newtonsoft.Json": "7.0.1", "xunit": "2.1.0", "xunit.analyzers": "0.9.0", "xunit.assert": "2.1.0",