/// <summary> /// Returns publisher object /// </summary> /// <param name="publisherType">filepublisher, logicapppublisher, blobpublisher</param> /// <param name="fileType"> Expected or Actual</param> private IPublisher GetMessagePublisher(string fileType) { IPublisher publisher = null; Dictionary <string, string> publisherSettings = JsonConvert.DeserializeObject <Dictionary <string, string> >(testSuite[fileType].ToString()); if (publisherSettings[AppConstants.PublisherType].ToString().ToLower() == AppConstants.BlobPublisher) { Uri sasUriOfBlobContainer = new Uri(publisherSettings[AppConstants.BlobUri].ToString()); publisher = new BlobPublisher(sasUriOfBlobContainer, adapterSettings["ContentType"]); TraceProvider.WriteLine("Executing test suit run id {0}, selected publisher is {1} with uri {2}", testSuiteRunId, AppConstants.BlobPublisher, sasUriOfBlobContainer.AbsoluteUri); } else if (publisherSettings[AppConstants.PublisherType].ToString().ToLower() == AppConstants.FilePublisher) { publisher = new FilePublisher(HttpUtility.UrlDecode(publisherSettings[AppConstants.FilePath]), adapterSettings["ContentType"]); TraceProvider.WriteLine("Executing test suit run id {0}, selected publisher is {1} with path {2}", testSuiteRunId, AppConstants.FilePublisher, HttpUtility.UrlDecode(publisherSettings[AppConstants.FilePath])); } else if (publisherSettings[AppConstants.PublisherType].ToString().ToLower() == AppConstants.LogicAppPublisher) { publisher = new LogicAppPublisher(testSuite, adapterSettings["ContentType"]); TraceProvider.WriteLine("Executing test suit run id {0}, selected publisher is {1}", testSuiteRunId, AppConstants.LogicAppPublisher); } else { TraceProvider.WriteLine("Executing test suit run id {0}, Publisher type is not configured in test suit for {1}", testSuiteRunId, fileType); } return(publisher); }
public void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token) { var assemblyLocalDir = Path.GetDirectoryName(GetType().Assembly.Location); var assemblyRemoteDir = Path.Combine(server.GetServerInfo().TempFolderDos, "Assemblies"); var publisher = new FilePublisher(); publisher.PublishDirectory(assemblyLocalDir, assemblyRemoteDir, server, settings); var remoteAssemblyFileName = Path.Combine(Path.Combine(server.GetServerInfo().TempFolderPowerShell, "Assemblies"), Path.GetFileName(GetType().Assembly.Location)); var remoteJsonAssembly = Path.Combine(Path.Combine(server.GetServerInfo().TempFolderPowerShell, "Assemblies"), "Newtonsoft.Json.dll"); var typeName = GetType().FullName; var loggerTypeName = typeof(RemotePowerShellLogger).FullName; var parameters = GetPowerShellParameters(ConstructorArguments, GetType()).ToList(); var scriptParams = string.Join(",", parameters.Select(x => "$" + x.Name)); var argumentList = string.Join(",", GetType().GetConstructor(ConstructorArguments.Select(x => x.GetType()).ToArray()).GetParameters().Select(x => "$" + x.Name)); var deserializeScript = GetDeserializationScript(GetType().GetConstructor(ConstructorArguments.Select(x => x.GetType()).ToArray())); var psExecutor = new PowerShellExecutor(server); var script = string.Format(@" Param({3}) add-type -path {0} add-type -path {5} {4} $operation = new-object -typename {1} -ArgumentList {6} $logger = new-object -typename {2} -ArgumentList (Get-Host).UI $operation.Execute($logger) ", remoteAssemblyFileName, typeName, loggerTypeName, scriptParams, deserializeScript, remoteJsonAssembly, argumentList); psExecutor.Execute(script, parameters); }
public void ShouldThrowExceptionIfSomething() { _ioUtilsMock.Setup(io => io.OpenFile(SomeTargetLocation, FileMode.Create, FileAccess.Write)) .Throws(new Exception("XYZ")); var uut = new FilePublisher(() => SomeTargetLocation); uut.Publish(_userProfileEvent, TestEventSource(1), () => { }); }
public void ShouldOpenFileForWriting() { var uut = new FilePublisher(() => SomeTargetLocation); uut.Publish(_userProfileEvent, TestEventSource(1), () => { }); _ioUtilsMock.Verify(m => m.OpenFile(SomeTargetLocation, FileMode.Create, FileAccess.Write)); }
private static bool PublishFile(string combinedMarkdown) { if (!_programArgs.PublishToFile) { return(true); } return(FilePublisher.PublishMarkdownReleaseHistoryFile(combinedMarkdown, _programArgs)); }
public void ProgressCallsArePassedThrough() { const int expected = 8; var count = 0; var uut = new FilePublisher(() => SomeTargetLocation); uut.Publish(null, TestEventSource(expected), () => count++); // +upe Assert.AreEqual(expected + 1, count); }
private IPublisher CreatePublisher() { IPublisher publisher; if (_exportType == UploadWizardControl.ExportType.ZipFile) { publisher = new FilePublisher(AskForExportLocation); } else { publisher = new HttpPublisher(GetUploadUrl()); } return(publisher); }
public void AllSourceEventsArePublishedTogetherWithProfile() { var upe = new UserProfileEvent(); var testEvents = TestEventSource(10).ToList(); var uut = new FilePublisher(() => SomeTargetLocation); uut.Publish(upe, testEvents, () => { }); Assert.AreEqual(1, _exportedPackages.Count); var exported = _exportedPackages.SelectMany(e => e).ToList(); CollectionAssert.AreEqual(testEvents.Prepend(upe), exported); }
private static int PublishFile(string combinedMarkdown, int exitCode) { if (!_programArgs.PublishToFile) { return(exitCode); } if (FilePublisher.PublishMarkdownReleaseHistoryFile(combinedMarkdown, _programArgs)) { exitCode = SuccessExitCode; } else { exitCode = FailureExitCode; } return(exitCode); }
static async Task Main(string[] args) { var publisher = new FilePublisher(); var consumer = new FilesConsumer(); publisher.StartMonitoring(); do { await consumer.ConsumeAsync(); if (FileStorage.ProcessedFiles.Count == maxNumberOfProcessedFiles) { tokenSource.Cancel(); waitHandle.Set(); } } while (!tokenSource.Token.IsCancellationRequested); PrintResults(); waitHandle.WaitOne(); }
protected void handleOutput(Publisher publisher) { Stream strm = dataModel.Value.Stream; strm.Seek(0, SeekOrigin.Begin); MemoryStream ms = strm as MemoryStream; if (ms == null) { ms = new MemoryStream(); strm.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); strm.Seek(0, SeekOrigin.Begin); } publisher.output(ms.GetBuffer(), (int)ms.Position, (int)ms.Length); if (publisher is FilePublisher) { FilePublisher filePublisher = (FilePublisher)publisher; dataModel.GenerateBoundaryFile(filePublisher.FileName + ".chunks"); if ((int)ms.Length < fileLengthBytes) { Console.WriteLine("error {0}", (100 * ((float)ms.Length / fileLengthBytes)).ToString("n2")); } else if ((int)ms.Length == fileLengthBytes) { Console.WriteLine("ok"); } else { //XXX. Should not be here } } }
public void Run(RunContext context) { logger.Trace("Run({0}): {1}", name, type); if (when != null) { Dictionary <string, object> state = new Dictionary <string, object>(); state["context"] = context; state["Context"] = context; state["action"] = this; state["Action"] = this; state["state"] = this.parent; state["State"] = this.parent; state["StateModel"] = this.parent.parent; state["Test"] = this.parent.parent.parent; state["self"] = this; object value = Scripting.EvalExpression(when, state); if (!(value is bool)) { logger.Debug("Run: action '{0}' when return is not boolean, returned: {1}", name, value); return; } if (!(bool)value) { logger.Debug("Run: action '{0}' when returned false", name); return; } } try { Publisher publisher = null; if (this.publisher != null && this.publisher != "Peach.Agent") { if (!context.test.publishers.ContainsKey(this.publisher)) { logger.Debug("Run: Publisher '" + this.publisher + "' not found!"); throw new PeachException("Error, Action '" + name + "' publisher value '" + this.publisher + "' was not found!"); } publisher = context.test.publishers[this.publisher]; } else { publisher = context.test.publishers[0]; } if (context.controlIteration && context.controlRecordingIteration) { logger.Debug("Run: Adding action to controlRecordingActionsExecuted"); context.controlRecordingActionsExecuted.Add(this); } else if (context.controlIteration) { logger.Debug("Run: Adding action to controlActionsExecuted"); context.controlActionsExecuted.Add(this); } started = true; finished = false; error = false; OnStarting(); logger.Debug("ActionType.{0}", type.ToString()); switch (type) { case ActionType.Start: publisher.start(); break; case ActionType.Stop: publisher.close(); publisher.stop(); break; case ActionType.Open: case ActionType.Connect: publisher.start(); publisher.open(); break; case ActionType.Close: publisher.start(); publisher.close(); break; case ActionType.Accept: publisher.start(); publisher.open(); publisher.accept(); break; case ActionType.Input: publisher.start(); publisher.open(); publisher.input(); handleInput(publisher); parent.parent.dataActions.Add(this); break; case ActionType.Output: publisher.start(); if (publisher is FilePublisher) { if (context.config.outputFilePath != null) { FilePublisher filePublisher = (FilePublisher)publisher; filePublisher.FileName = context.config.outputFilePath; } if (context.config.inputFilePath != null) { if (File.Exists(context.config.inputFilePath)) { fileLengthBytes = (int)new FileInfo(context.config.inputFilePath).Length; } } } publisher.open(); handleOutput(publisher); parent.parent.dataActions.Add(this); break; case ActionType.Call: publisher.start(); handleCall(publisher, context); parent.parent.dataActions.Add(this); break; case ActionType.GetProperty: publisher.start(); handleGetProperty(publisher); parent.parent.dataActions.Add(this); break; case ActionType.SetProperty: publisher.start(); handleSetProperty(publisher); parent.parent.dataActions.Add(this); break; case ActionType.ChangeState: handleChangeState(); break; case ActionType.Slurp: handleSlurp(context); break; default: throw new ApplicationException("Error, Action.Run fell into unknown Action type handler!"); } finished = true; } catch { error = true; finished = true; throw; } finally { OnFinished(); } }
public void RegisterWithServer(EnhancedImageServer server) { // This is just for storing the user preference of method // If we had a couple of these, we could just have a generic preferences api // that browser-side code could use. server.RegisterEndpointHandler(kApiUrlPart + "method", request => { if (request.HttpMethod == HttpMethods.Get) { var method = Settings.Default.PublishAndroidMethod; if (!new string[] { "wifi", "usb", "file" }.Contains(method)) { method = "wifi"; } request.ReplyWithText(method); } else // post { Settings.Default.PublishAndroidMethod = request.RequiredPostString(); #if __MonoCS__ if (Settings.Default.PublishAndroidMethod == "usb") { _progress.MessageWithoutLocalizing("Sorry, this method is not available on Linux yet."); } #endif request.PostSucceeded(); } }, true); server.RegisterEndpointHandler(kApiUrlPart + "backColor", request => { if (request.HttpMethod == HttpMethods.Get) { if (request.CurrentBook != _coverColorSourceBook) { _coverColorSourceBook = request.CurrentBook; TryCssColorFromString(request.CurrentBook?.GetCoverColor() ?? "", out _thumbnailBackgroundColor); } request.ReplyWithText(ToCssColorString(_thumbnailBackgroundColor)); } else // post { // ignore invalid colors (very common while user is editing hex) Color newColor; var newColorAsString = request.RequiredPostString(); if (TryCssColorFromString(newColorAsString, out newColor)) { _thumbnailBackgroundColor = newColor; request.CurrentBook.SetCoverColor(newColorAsString); } request.PostSucceeded(); } }, true); server.RegisterEndpointHandler(kApiUrlPart + "photoStoryMode", request => { if (request.HttpMethod == HttpMethods.Get) { // this is temporary, just trying to get support for full screen pan & zoom out quickly in 4.2 request.ReplyWithText(request.CurrentBook.UsePhotoStoryModeInBloomReader.ToString() .ToLowerInvariant()); // "false", not "False" } else // post { request.CurrentBook.UsePhotoStoryModeInBloomReader = bool.Parse(request.RequiredPostString()); request.PostSucceeded(); } }, true); server.RegisterEndpointHandler(kApiUrlPart + "thumbnail", request => { var coverImage = request.CurrentBook.GetCoverImagePath(); if (coverImage == null) { request.Failed("no cover image"); } else { // We don't care as much about making it resized as making its background transparent. using (var thumbnail = TempFile.CreateAndGetPathButDontMakeTheFile()) { if (_thumbnailBackgroundColor == Color.Transparent) { TryCssColorFromString(request.CurrentBook?.GetCoverColor(), out _thumbnailBackgroundColor); } RuntimeImageProcessor.GenerateEBookThumbnail(coverImage, thumbnail.Path, 256, 256, _thumbnailBackgroundColor); request.ReplyWithImage(thumbnail.Path); } } }, true); server.RegisterEndpointHandler(kApiUrlPart + "usb/start", request => { #if !__MonoCS__ SetState("UsbStarted"); _usbPublisher.Connect(request.CurrentBook, _thumbnailBackgroundColor); #endif request.PostSucceeded(); }, true); server.RegisterEndpointHandler(kApiUrlPart + "usb/stop", request => { #if !__MonoCS__ _usbPublisher.Stop(); SetState("stopped"); #endif request.PostSucceeded(); }, true); server.RegisterEndpointHandler(kApiUrlPart + "wifi/start", request => { _wifiPublisher.Start(request.CurrentBook, request.CurrentCollectionSettings, _thumbnailBackgroundColor); SetState("ServingOnWifi"); request.PostSucceeded(); }, true); server.RegisterEndpointHandler(kApiUrlPart + "wifi/stop", request => { _wifiPublisher.Stop(); SetState("stopped"); request.PostSucceeded(); }, true); server.RegisterEndpointHandler(kApiUrlPart + "file/save", request => { FilePublisher.Save(request.CurrentBook, _bookServer, _thumbnailBackgroundColor, _progress); SetState("stopped"); request.PostSucceeded(); }, true); server.RegisterEndpointHandler(kApiUrlPart + "cleanup", request => { Stop(); request.PostSucceeded(); }, true); server.RegisterEndpointHandler(kApiUrlPart + "textToClipboard", request => { PortableClipboard.SetText(request.RequiredPostString()); request.PostSucceeded(); }, true); }
public void ShouldThrowExceptionOnEmptyArgument() { var uut = new FilePublisher(() => ""); uut.Publish(_userProfileEvent, TestEventSource(1), () => { }); }
public void RegisterWithApiHandler(BloomApiHandler apiHandler) { // This is just for storing the user preference of method // If we had a couple of these, we could just have a generic preferences api // that browser-side code could use. apiHandler.RegisterEndpointHandler(kApiUrlPart + "method", request => { if (request.HttpMethod == HttpMethods.Get) { var method = Settings.Default.PublishAndroidMethod; if (!new string[] { "wifi", "usb", "file" }.Contains(method)) { method = "wifi"; } request.ReplyWithText(method); } else // post { Settings.Default.PublishAndroidMethod = request.RequiredPostString(); #if __MonoCS__ if (Settings.Default.PublishAndroidMethod == "usb") { _progress.MessageWithoutLocalizing("Sorry, this method is not available on Linux yet."); } #endif request.PostSucceeded(); } }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "backColor", request => { if (request.HttpMethod == HttpMethods.Get) { if (request.CurrentBook != _coverColorSourceBook) { _coverColorSourceBook = request.CurrentBook; ImageUtils.TryCssColorFromString(request.CurrentBook?.GetCoverColor() ?? "", out _thumbnailBackgroundColor); } request.ReplyWithText(ToCssColorString(_thumbnailBackgroundColor)); } else // post { // ignore invalid colors (very common while user is editing hex) Color newColor; var newColorAsString = request.RequiredPostString(); if (ImageUtils.TryCssColorFromString(newColorAsString, out newColor)) { _thumbnailBackgroundColor = newColor; request.CurrentBook.SetCoverColor(newColorAsString); } request.PostSucceeded(); } }, true); apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "motionBookMode", readRequest => { // If the user has taken off all possible motion, force not having motion in the // Bloom Reader book. See https://issues.bloomlibrary.org/youtrack/issue/BL-7680. if (!readRequest.CurrentBook.HasMotionPages) { readRequest.CurrentBook.MotionMode = false; } return(readRequest.CurrentBook.MotionMode); }, (writeRequest, value) => { writeRequest.CurrentBook.MotionMode = value; } , true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "updatePreview", request => { if (request.HttpMethod == HttpMethods.Post) { // This is already running on a server thread, so there doesn't seem to be any need to kick off // another background one and return before the preview is ready. But in case something in C# // might one day kick of a new preview, or we find we do need a background thread, // I've made it a websocket broadcast when it is ready. // If we've already left the publish tab...we can get a few of these requests queued up when // a tester rapidly toggles between views...abandon the attempt if (!PublishHelper.InPublishTab) { request.Failed("aborted, no longer in publish tab"); return; } try { UpdatePreview(request); request.PostSucceeded(); } catch (Exception e) { request.Failed("Error while updating preview. Message: " + e.Message); NonFatalProblem.Report(ModalIf.Alpha, PassiveIf.All, "Error while updating preview.", null, e, true); } } }, false); apiHandler.RegisterEndpointHandler(kApiUrlPart + "thumbnail", request => { var coverImage = request.CurrentBook.GetCoverImagePath(); if (coverImage == null) { request.Failed("no cover image"); } else { // We don't care as much about making it resized as making its background transparent. using (var thumbnail = TempFile.CreateAndGetPathButDontMakeTheFile()) { if (_thumbnailBackgroundColor == Color.Transparent) { ImageUtils.TryCssColorFromString(request.CurrentBook?.GetCoverColor(), out _thumbnailBackgroundColor); } RuntimeImageProcessor.GenerateEBookThumbnail(coverImage, thumbnail.Path, 256, 256, _thumbnailBackgroundColor); request.ReplyWithImage(thumbnail.Path); } } }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "usb/start", request => { #if !__MonoCS__ SetState("UsbStarted"); UpdatePreviewIfNeeded(request); _usbPublisher.Connect(request.CurrentBook, _thumbnailBackgroundColor, GetSettings()); #endif request.PostSucceeded(); }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "usb/stop", request => { #if !__MonoCS__ _usbPublisher.Stop(); SetState("stopped"); #endif request.PostSucceeded(); }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "wifi/start", request => { SetState("ServingOnWifi"); UpdatePreviewIfNeeded(request); _wifiPublisher.Start(request.CurrentBook, request.CurrentCollectionSettings, _thumbnailBackgroundColor, GetSettings()); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "wifi/stop", request => { _wifiPublisher.Stop(); SetState("stopped"); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "file/save", request => { UpdatePreviewIfNeeded(request); FilePublisher.Save(request.CurrentBook, _bookServer, _thumbnailBackgroundColor, _progress, GetSettings()); SetState("stopped"); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "cleanup", request => { Stop(); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "textToClipboard", request => { PortableClipboard.SetText(request.RequiredPostString()); request.PostSucceeded(); }, true); apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "canHaveMotionMode", request => { return(request.CurrentBook.HasMotionPages); }, null, // no write action false, true); // we don't really know, just safe default apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "canRotate", request => { return(request.CurrentBook.MotionMode && request.CurrentBook.HasMotionPages); }, null, // no write action false, true); // we don't really know, just safe default apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "defaultLandscape", request => { return(request.CurrentBook.GetLayout().SizeAndOrientation.IsLandScape); }, null, // no write action false, true); // we don't really know, just safe default apiHandler.RegisterEndpointHandler(kApiUrlPart + "languagesInBook", request => { try { InitializeLanguagesInBook(request); Dictionary <string, InclusionSetting> textLangsToPublish = request.CurrentBook.BookInfo.MetaData.TextLangsToPublish.ForBloomPUB; Dictionary <string, InclusionSetting> audioLangsToPublish = request.CurrentBook.BookInfo.MetaData.AudioLangsToPublish.ForBloomPUB; var result = "[" + string.Join(",", _allLanguages.Select(kvp => { string langCode = kvp.Key; bool includeText = false; if (textLangsToPublish != null && textLangsToPublish.TryGetValue(langCode, out InclusionSetting includeTextSetting)) { includeText = includeTextSetting.IsIncluded(); } bool includeAudio = false; if (audioLangsToPublish != null && audioLangsToPublish.TryGetValue(langCode, out InclusionSetting includeAudioSetting)) { includeAudio = includeAudioSetting.IsIncluded(); } var value = new LanguagePublishInfo() { code = kvp.Key, name = request.CurrentBook.PrettyPrintLanguage(langCode), complete = kvp.Value, includeText = includeText, containsAnyAudio = _languagesWithAudio.Contains(langCode), includeAudio = includeAudio }; var json = JsonConvert.SerializeObject(value); return(json); })) + "]"; request.ReplyWithText(result); }
public void RegisterWithApiHandler(BloomApiHandler apiHandler) { // This is just for storing the user preference of method // If we had a couple of these, we could just have a generic preferences api // that browser-side code could use. apiHandler.RegisterEndpointLegacy(kApiUrlPart + "method", request => { if (request.HttpMethod == HttpMethods.Get) { var method = Settings.Default.PublishAndroidMethod; if (!new string[] { "wifi", "usb", "file" }.Contains(method)) { method = "wifi"; } request.ReplyWithText(method); } else // post { Settings.Default.PublishAndroidMethod = request.RequiredPostString(); #if __MonoCS__ if (Settings.Default.PublishAndroidMethod == "usb") { _progress.MessageWithoutLocalizing("Sorry, this method is not available on Linux yet."); } #endif request.PostSucceeded(); } }, true); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "backColor", request => { if (request.HttpMethod == HttpMethods.Get) { if (request.CurrentBook != _coverColorSourceBook) { _coverColorSourceBook = request.CurrentBook; ImageUtils.TryCssColorFromString(request.CurrentBook?.GetCoverColor() ?? "", out _thumbnailBackgroundColor); } request.ReplyWithText(ToCssColorString(_thumbnailBackgroundColor)); } else // post { // ignore invalid colors (very common while user is editing hex) Color newColor; var newColorAsString = request.RequiredPostString(); if (ImageUtils.TryCssColorFromString(newColorAsString, out newColor)) { _thumbnailBackgroundColor = newColor; request.CurrentBook.SetCoverColor(newColorAsString); } request.PostSucceeded(); } }, true); apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "motionBookMode", readRequest => { // If the user has taken off all possible motion, force not having motion in the // Bloom Reader book. See https://issues.bloomlibrary.org/youtrack/issue/BL-7680. if (!readRequest.CurrentBook.HasMotionPages) { readRequest.CurrentBook.BookInfo.PublishSettings.BloomPub.Motion = false; } return(readRequest.CurrentBook.BookInfo.PublishSettings.BloomPub.Motion); }, (writeRequest, value) => { writeRequest.CurrentBook.BookInfo.PublishSettings.BloomPub.Motion = value; writeRequest.CurrentBook.BookInfo.SavePublishSettings(); _webSocketServer.SendEvent("publish", "motionChanged"); } , true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "updatePreview", request => { MakeBloompubPreview(request, false); }, false); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "thumbnail", request => { var coverImage = request.CurrentBook.GetCoverImagePath(); if (coverImage == null) { request.Failed("no cover image"); } else { // We don't care as much about making it resized as making its background transparent. using (var thumbnail = TempFile.CreateAndGetPathButDontMakeTheFile()) { if (_thumbnailBackgroundColor == Color.Transparent) { ImageUtils.TryCssColorFromString(request.CurrentBook?.GetCoverColor(), out _thumbnailBackgroundColor); } RuntimeImageProcessor.GenerateEBookThumbnail(coverImage, thumbnail.Path, 256, 256, _thumbnailBackgroundColor); request.ReplyWithImage(thumbnail.Path); } } }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "usb/start", request => { #if !__MonoCS__ SetState("UsbStarted"); UpdatePreviewIfNeeded(request); _usbPublisher.Connect(request.CurrentBook, _thumbnailBackgroundColor, GetSettings()); #endif request.PostSucceeded(); }, true); apiHandler.RegisterEndpointHandler(kApiUrlPart + "usb/stop", request => { #if !__MonoCS__ _usbPublisher.Stop(disposing: false); SetState("stopped"); #endif request.PostSucceeded(); }, true); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "wifi/start", request => { SetState("ServingOnWifi"); UpdatePreviewIfNeeded(request); _wifiPublisher.Start(request.CurrentBook, request.CurrentCollectionSettings, _thumbnailBackgroundColor, GetSettings()); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "wifi/stop", request => { _wifiPublisher.Stop(); SetState("stopped"); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "file/save", request => { UpdatePreviewIfNeeded(request); FilePublisher.Save(request.CurrentBook, _bookServer, _thumbnailBackgroundColor, _progress, GetSettings()); SetState("stopped"); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "file/bulkSaveBloomPubsParams", request => { request.ReplyWithJson(JsonConvert.SerializeObject(_collectionSettings.BulkPublishBloomPubSettings)); }, true); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "file/bulkSaveBloomPubs", request => { // update what's in the collection so that we remember for next time _collectionSettings.BulkPublishBloomPubSettings = request.RequiredPostObject <BulkBloomPubPublishSettings>(); _collectionSettings.Save(); _bulkBloomPubCreator.PublishAllBooks(_collectionSettings.BulkPublishBloomPubSettings); SetState("stopped"); request.PostSucceeded(); }, true); apiHandler.RegisterEndpointLegacy(kApiUrlPart + "textToClipboard", request => { PortableClipboard.SetText(request.RequiredPostString()); request.PostSucceeded(); }, true); apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "canHaveMotionMode", request => { return(request.CurrentBook.HasMotionPages); }, null, // no write action false, true); // we don't really know, just safe default apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "canRotate", request => { return(request.CurrentBook.BookInfo.PublishSettings.BloomPub.Motion && request.CurrentBook.HasMotionPages); }, null, // no write action false, true); // we don't really know, just safe default apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "defaultLandscape", request => { return(request.CurrentBook.GetLayout().SizeAndOrientation.IsLandScape); }, null, // no write action false, true); // we don't really know, just safe default apiHandler.RegisterEndpointLegacy(kApiUrlPart + "languagesInBook", request => { try { InitializeLanguagesInBook(request); Dictionary <string, InclusionSetting> textLangsToPublish = request.CurrentBook.BookInfo.PublishSettings.BloomPub.TextLangs; Dictionary <string, InclusionSetting> audioLangsToPublish = request.CurrentBook.BookInfo.PublishSettings.BloomPub.AudioLangs; var result = "[" + string.Join(",", _allLanguages.Select(kvp => { string langCode = kvp.Key; bool includeText = false; if (textLangsToPublish != null && textLangsToPublish.TryGetValue(langCode, out InclusionSetting includeTextSetting)) { includeText = includeTextSetting.IsIncluded(); } bool includeAudio = false; if (audioLangsToPublish != null && audioLangsToPublish.TryGetValue(langCode, out InclusionSetting includeAudioSetting)) { includeAudio = includeAudioSetting.IsIncluded(); } var value = new LanguagePublishInfo() { code = kvp.Key, name = request.CurrentBook.PrettyPrintLanguage(langCode), complete = kvp.Value, includeText = includeText, containsAnyAudio = _languagesWithAudio.Contains(langCode), includeAudio = includeAudio }; var json = JsonConvert.SerializeObject(value); return(json); })) + "]"; request.ReplyWithText(result); }
private static void PeselValidationChoice() { int licznik = 0; string p; //tworzenie listy numerów PESEL List <string> pesels = new List <string>(); do { Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Proszę, podaj " + (licznik + 1) + " numer PESEL lub STOP aby zakończyć:"); p = Console.ReadLine(); if (String.Compare(p, "stop", true) != 0) { pesels.Add(p); } licznik++; }while (String.Compare(p, "stop", true) != 0); //tworzenie listy wyników "walidacji" List <PeselValidationResult> peselValidations = new List <PeselValidationResult>(); for (int i = 0; i < pesels.Count; i++) { PeselValidator validator = new PeselValidator(pesels[i]); PeselValidationResult peselValidation = validator.SprawdzPesel(); peselValidations.Add(peselValidation); } //agregacja danych z listy z rezultatami walidacji... zliczanie błędnych i wyświetlanie błędnych oraz zawartości listy bool choiceReportParsed; int choiceReport; do { Console.Clear(); Console.WriteLine("Wybierz typ raportu: (1) na konsolę, (2) do pliku TXT"); Console.WriteLine(); var choiceReportKey = Console.ReadKey(); choiceReportParsed = int.TryParse(choiceReportKey.KeyChar.ToString(), out choiceReport); }while (!choiceReportParsed); IPublisher publisher = null; switch (choiceReport) { case 1: publisher = new ConsolePublisher(); break; case 2: publisher = new FilePublisher(); break; default: publisher = new PublisherKtoryNicNieRobieZebySieNieWysypalo(); break; } Generator generator = new Generator(); Reporter validationsReporter = new Reporter(generator, new IPublisher[] { publisher }); validationsReporter.Report(peselValidations); Console.ReadKey(); }