예제 #1
0
        private void Can_Publish_Mixed_Branch(out IContent iRoot, out IContent ii1, out IContent iv11)
        {
            // invariant root -> variant -> invariant
            // variant root -> variant -> invariant
            // variant root -> invariant -> variant
            CreateTypes(out IContentType iContentType, out IContentType vContentType);

            // invariant root -> invariant -> variant
            iRoot = new Content("iroot", -1, iContentType);
            iRoot.SetValue("ip", "iroot");
            ContentService.SaveAndPublish(iRoot);
            ii1 = new Content("ii1", iRoot, iContentType);
            ii1.SetValue("ip", "vii1");
            ContentService.SaveAndPublish(ii1);
            ii1.SetValue("ip", "changed");
            ContentService.Save(ii1);
            iv11 = new Content("iv11.de", ii1, vContentType, "de");
            iv11.SetValue("ip", "iv11");
            iv11.SetValue("vp", "iv11.de", "de");
            iv11.SetValue("vp", "iv11.ru", "ru");
            iv11.SetValue("vp", "iv11.es", "es");
            ContentService.Save(iv11);

            iv11.SetCultureName("iv11.ru", "ru");
            PublishResult xxx = ContentService.SaveAndPublish(iv11, new[] { "de", "ru" });

            Assert.AreEqual("iv11.de", iv11.GetValue("vp", "de", published: true));
            Assert.AreEqual("iv11.ru", iv11.GetValue("vp", "ru", published: true));

            iv11.SetValue("ip", "changed");
            iv11.SetValue("vp", "changed.de", "de");
            iv11.SetValue("vp", "changed.ru", "ru");
            ContentService.Save(iv11);
        }
예제 #2
0
        PublishResult PublishEventsIfAnyNew(long initialPosition, int count)
        {
            var records         = _store.EnumerateAllItems(initialPosition, count);
            var currentPosition = initialPosition;
            var publishedCount  = 0;

            foreach (var e in records)
            {
                if (e.StoreVersion < currentPosition)
                {
                    throw new InvalidOperationException(string.Format("Retrieved record with position less than current. Store versions {0} <= current position {1}", e.StoreVersion, currentPosition));
                }
                if (_recordShouldBePublished(e))
                {
                    for (int i = 0; i < e.Items.Length; i++)
                    {
                        // predetermined id to kick in event deduplication
                        // if server crashes somehow
                        var envelopeId = "esp-" + e.StoreVersion + "-" + i;
                        var item       = e.Items[i];

                        publishedCount += 1;
                        _sender.Send(item, envelopeId);
                    }
                }
                currentPosition = e.StoreVersion;
            }
            var result = new PublishResult(initialPosition, currentPosition, count);

            if (result.Changed)
            {
                SystemObserver.Notify("{0}\t[sys] Message store pointer moved to {1} ({2} published)", _name, result.FinalPosition, publishedCount);
            }
            return(result);
        }
        public async Task <PublishResult> PublishAsync()
        {
            if (!_feedsValid)
            {
                return(new PublishResult {
                    Success = false, Error = "Feeds not yet successfully validated"
                });
            }

            var publishManager = new PublishManager(_accessKey, _secretKey, _region);
            var publishResult  = new PublishResult();

            if (!_productsPushed && _productCollection.GetCollectionState().ItemCount != 0)
            {
                publishResult.PublishProductFeedResult = await publishManager.PublishProductFeed(_productCollection.GetItems(), _accountPriceCollection.GetItems());

                _productsPushed = true;
            }

            if (_categoryCollection.GetCollectionState().ItemCount != 0)
            {
                publishResult.PublishCategoryFeedResult = await publishManager.PublishCategoryFeed(_categoryCollection.GetItems());
            }

            if (_userCollection.GetCollectionState().ItemCount != 0)
            {
                publishResult.PublishUserFeedResult = await publishManager.PublishUserFeed(_userCollection.GetItems());
            }

            publishResult.Success = (publishResult.PublishProductFeedResult?.Success ?? true) &&
                                    (publishResult.PublishCategoryFeedResult?.Success ?? true) &&
                                    (publishResult.PublishUserFeedResult?.Success ?? true);

            return(publishResult);
        }
        /// <summary>
        /// Validates and makes the request
        /// </summary>
        /// <param name="result"> PushNotification's result</param>
        /// <param name="log"> Object of type DynamoLog to be inserted as attributes</param>
        public async Task <OperationResult> SendAsync <T>(PublishResult result, T log) where T : DynamoLog, new()
        {
            try
            {
                Validate(result);
                await logger.LogNotificationAsync(result, log);

                return(new OperationResult());
            }
            catch (AWSMobilePushNotificationServiceException ex)
            {
                return(new OperationResult(ex));
            }
            catch (Exception ex)
            {
                if (Provider.CatchAllExceptions)
                {
                    return(new OperationResult(ex.Message));
                }
                else
                {
                    throw ex;
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Проводит операции с полученным списком презентаций по публикации на сайте soft
        /// </summary>
        /// <param name="lst">Список презентаций, которые были получены с nnmclub</param>
        /// <returns>Если все презентации выложены успешно, то true, инчае false</returns>
        async Task <bool> FlowNnmclub(IList <NnmclubListItem> lst)
        {
            foreach (NnmclubListItem item in lst)
            {
                //Парсим
                NnmclubParseItemInput paramParseInp =
                    _context.NnmclubParseItemInputs
                    .Single(el => el.Active);
                paramParseInp.ListItemId = item.Id;
                NnmclubItem nnmclubItem = await _nnmclubService.ParseItem(paramParseInp);

                if (nnmclubItem == null)
                {
                    _logger.LogError("Не удалось распарсить пост. NnmclubListItem.Id = " + item.Id);
                    return(false);
                }

                //Выкладываем
                PublishResult result = await Send(nameof(NnmclubItem), nnmclubItem.Id);

                if (result == PublishResult.Error)
                {
                    _logger.LogError("Ошибка при отправке поста");
                    return(false);
                }
                if (result == PublishResult.FileExist)
                {
                    _logger.LogError("Пост уже существует, переходим к следующему");
                    continue;
                }
            }
            return(true);
        }
        private void Validate(PublishResult result)
        {
            if (!result.IsSuccessful)
            {
                return;
            }
            string error = string.Empty;

            if (result is PublishToSNSSuccessfulResult)
            {
                if (string.IsNullOrEmpty(result.MessageId))
                {
                    error = error + "MessageId of response is empty \n";
                }
            }
            if (result is PublishToSNSTopicTagResult)
            {
                if (string.IsNullOrEmpty(result.MessageId))
                {
                    error = error + "MessageId of response is empty \n";
                }
            }

            if (!string.IsNullOrEmpty(error))
            {
                throw new ModelInvalidException(error);
            }
        }
예제 #7
0
 private void btnF10_Click(object sender, EventArgs e)
 {
     this.FunctionCalled(10, btnF10);
     Result = PublishResult.Cancel;
     Exit();
     Close();
 }
예제 #8
0
        /// <summary>
        /// Проводит операции с полученным списком презентаций по публикации на сайте soft
        /// </summary>
        /// <param name="lst">Список презентаций, которые были получены с rutor</param>
        /// <returns>Если операция выполнена успешно - true, инчае false</returns>
        async Task <bool> FlowRutor(IList <RutorListItem> lst)
        {
            foreach (RutorListItem item in lst)
            {
                //Парсим
                RutorParseItemInput paramRutorItem =
                    _context.RutorParseItemInputs
                    .Single(el => el.Active);
                paramRutorItem.ListItemId = item.Id;
                RutorItem rutorItem = await _rutorService.ParseItem(paramRutorItem);

                if (rutorItem == null)
                {
                    _logger.LogError("Не удалось распарсить пост. ListItemId = " + item.Id);
                    return(false);
                }

                //Выкладываем
                PublishResult result = await Send(nameof(RutorItem), rutorItem.Id);

                if (result == PublishResult.Error)
                {
                    _logger.LogError("Ошибка при отправке поста");
                    return(false);
                }
                if (result == PublishResult.FileExist)
                {
                    _logger.LogError("Пост уже существует, переходим к следующему");
                    continue;
                }
            }
            return(true);
        }
예제 #9
0
        public override void Execute()
        {
            DacPackage     dacpac         = DacPackage.Load(this.Parameters.PackageFilePath);
            PublishOptions publishOptions = new PublishOptions();

            publishOptions.GenerateDeploymentReport = this.Parameters.GenerateDeploymentReport;
            publishOptions.CancelToken   = this.CancellationToken;
            publishOptions.DeployOptions = this.GetDefaultDeployOptions();

            this.Result = this.DacServices.Script(dacpac, this.Parameters.DatabaseName, publishOptions);

            // tests don't create a SqlTask, so only add the script when the SqlTask isn't null
            if (this.SqlTask != null)
            {
                this.SqlTask.AddScript(SqlTaskStatus.Succeeded, Result.DatabaseScript);
                if (!string.IsNullOrEmpty(this.Result.MasterDbScript))
                {
                    // master script is only used if the target is Azure SQL db and the script contains all operations that must be done against the master database
                    this.SqlTask.AddScript(SqlTaskStatus.Succeeded, this.Result.MasterDbScript);
                }
            }

            if (this.Parameters.GenerateDeploymentReport && !string.IsNullOrEmpty(this.Parameters.DeploymentReportFilePath))
            {
                File.WriteAllText(this.Parameters.DeploymentReportFilePath, this.Result.DeploymentReport);
            }
        }
        PublishResult PublishEventsIfAnyNew(long initialPosition, int count)
        {
            var records = _store.EnumerateAllItems(initialPosition, count);
            var currentPosition = initialPosition;
            var publishedCount = 0;
            foreach (var e in records)
            {
                if (e.StoreVersion < currentPosition)
                {
                    throw new InvalidOperationException(string.Format("Retrieved record with position less than current. Store versions {0} <= current position {1}", e.StoreVersion, currentPosition));
                }
                if (_recordShouldBePublished(e))
                {
                    for (int i = 0; i < e.Items.Length; i++)
                    {
                        // predetermined id to kick in event deduplication
                        // if server crashes somehow
                        var envelopeId = "esp-" + e.StoreVersion + "-" + i;
                        var item = e.Items[i];

                        publishedCount += 1;
                        _sender.Send(item, envelopeId);
                    }
                }
                currentPosition = e.StoreVersion;
            }
            var result = new PublishResult(initialPosition, currentPosition, count);
            if (result.Changed)
            {
                SystemObserver.Notify("[sys ] Message store pointer moved to {0} ({1} published)", result.FinalPosition, publishedCount);
            }
            return result;
        }
 public async Task LogNotificationAsync <T>(PublishResult publishResult, T log) where T : DynamoLog, new()
 {
     if (!publishResult.IsSuccessful)
     {
         return;
     }
     if (publishResult is PublishToIterativeTagResult)
     {
         PublishToIterativeTagResult iterativeResult = (PublishToIterativeTagResult)publishResult;
         foreach (var resultTuple in iterativeResult.EndpointResults)
         {
             var result = resultTuple.Item1;
             if (result is PublishToSNSSuccessfulResult)
             {
                 LogSuccessfulNotification((PublishToSNSSuccessfulResult)result, log).Wait();
             }
         }
     }
     else if (publishResult is PublishToSNSTopicTagResult)
     {
         await LogSuccessfulNotification((PublishToSNSTopicTagResult)publishResult, log);
     }
     else
     {
         if (publishResult is PublishToSNSSuccessfulResult)
         {
             await LogSuccessfulNotification((PublishToSNSSuccessfulResult)publishResult, log);
         }
     }
 }
예제 #12
0
        internal override async void Execute(ExportData data)
        {
            var modDirectory = Path.Combine(ExportSettings.outputDirectory, ExportSettings.name);
            var di           = new DirectoryInfo(modDirectory);

            if (!di.Exists)
            {
                Debug.LogError("Failed to upload to the Steam Workshop, directory doesn't exist: " + modDirectory);
                return;
            }

            var modSizeBytes = DirSize(new DirectoryInfo(modDirectory));
            var sizeString   = BytesToString(modSizeBytes);

            if (!EditorUtility.DisplayDialog("Really Upload?", "You're about to upload this to the Steam Workshop.  The file size is: " + sizeString, "Yes", "Cancel!"))
            {
                Debug.LogError("Upload cancelled!");
                return;
            }

            var editor = ExportSettings.WorkshopId == 0
                ? Steamworks.Ugc.Editor.NewCommunityFile
                : new Steamworks.Ugc.Editor(ExportSettings.WorkshopId);

            editor = editor.WithTitle(ExportSettings.name)
                     .WithDescription(ExportSettings.description)
                     .WithContent(modDirectory);

            PublishResult result = default;

            try
            {
                result = await Upload(editor);
            }
            catch (Exception e)
            {
                Debug.Log("Failed to upload: " + e.Message);
            }

            EditorUtility.ClearProgressBar();

            if (!result.Success)
            {
                Debug.LogError("Uploading to Steam Workshop failed!");
                return;
            }

            ExportSettings.WorkshopId = result.FileId;

            if (result.NeedsWorkshopAgreement)
            {
                if (EditorUtility.DisplayDialog("Workshop Agreement", "Before your item is visible you need to agree to Steam's Workshop Agreement", "Visit Workshop"))
                {
                    Application.OpenURL(ExportSettings.WorkshopUrl);
                }
            }

            EditorUtility.DisplayDialog("Upload Complete", $"{ExportSettings.name} v{ExportSettings.version} has been uploaded to the Steam Workshop!", "Close");
        }
 /// <summary>
 /// Validates and makes the request
 /// </summary>
 /// <param name="result"> PushNotification's result</param>
 /// <param name="log"> Object of type DynamoLog to be inserted as attributes</param>
 public static async Task <OperationResult> LogAsync <T>(PublishResult result, T log) where T : DynamoLog, new()
 {
     if (_loggingRequest == null)
     {
         throw new ModelInvalidException("PushNotificationLogger is not configured");
     }
     return(await _loggingRequest.Value.SendAsync(result, log));
 }
예제 #14
0
 protected override void SetMeasuredActionResult <T>(T value)
 {
     if (value is PublishResult)
     {
         PublishResult result = value as PublishResult;
         FileCount = result.FileCount;
     }
 }
예제 #15
0
        // Upload from target path to Azure DevOps BlobStore service through DedupManifestArtifactClient, then associate it with the build
        internal async Task UploadAsync(
            AgentTaskPluginExecutionContext context,
            Guid projectId,
            int pipelineId,
            string name,
            string source,
            CancellationToken cancellationToken)
        {
            VssConnection connection = context.VssConnection;

            BlobStoreClientTelemetry    clientTelemetry;
            DedupManifestArtifactClient dedupManifestClient = DedupManifestArtifactClientFactory.Instance.CreateDedupManifestClient(context, connection, cancellationToken, out clientTelemetry);

            using (clientTelemetry)
            {
                //Upload the pipeline artifact.
                PipelineArtifactActionRecord uploadRecord = clientTelemetry.CreateRecord <PipelineArtifactActionRecord>((level, uri, type) =>
                                                                                                                        new PipelineArtifactActionRecord(level, uri, type, nameof(UploadAsync), context));

                PublishResult result = await clientTelemetry.MeasureActionAsync(
                    record : uploadRecord,
                    actionAsync : async() =>
                {
                    return(await dedupManifestClient.PublishAsync(source, cancellationToken));
                }
                    );

                // Send results to CustomerIntelligence
                context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineArtifact, record: uploadRecord);

                // 2) associate the pipeline artifact with an build artifact
                BuildServer buildHelper = new BuildServer(connection);
                Dictionary <string, string> propertiesDictionary = new Dictionary <string, string>();
                propertiesDictionary.Add(PipelineArtifactConstants.RootId, result.RootId.ValueString);
                propertiesDictionary.Add(PipelineArtifactConstants.ProofNodes, StringUtil.ConvertToJson(result.ProofNodes.ToArray()));
                propertiesDictionary.Add(PipelineArtifactConstants.ArtifactSize, result.ContentSize.ToString());

                BuildArtifact buildArtifact = await AsyncHttpRetryHelper.InvokeAsync(
                    async() =>
                {
                    return(await buildHelper.AssociateArtifactAsync(projectId,
                                                                    pipelineId,
                                                                    name,
                                                                    context.Variables.GetValueOrDefault(WellKnownDistributedTaskVariables.JobId)?.Value ?? string.Empty,
                                                                    ArtifactResourceTypes.PipelineArtifact,
                                                                    result.ManifestId.ValueString,
                                                                    propertiesDictionary,
                                                                    cancellationToken));
                },
                    maxRetries : 3,
                    tracer : tracer,
                    canRetryDelegate : e => e is TimeoutException || e.InnerException is TimeoutException,
                    cancellationToken : cancellationToken,
                    continueOnCapturedContext : false);

                context.Output(StringUtil.Loc("AssociateArtifactWithBuild", buildArtifact.Id, pipelineId));
            }
        }
예제 #16
0
 public static PublishResult ToPublishResult(this PublishRequest.Result data)
 {
     var res = new PublishResult
     {
         IsSuccess = data.status == 200,
         Url = data.body
     };
     return res;
 }
예제 #17
0
        /// <summary>
        /// Добавляет пост на сайт
        /// </summary>
        /// <param name="inputParam"></param>
        /// <returns>Если отработал успешно, то true, инчае false</returns>
        public async Task <PublishResult> AddPost(SoftPostInput inputParam)
        {
            SoftPost post =
                _context.SoftPosts
                .Include(el => el.Imgs)
                .SingleOrDefault(el => el.Id == inputParam.SoftPostId);

            if (post == null)
            {
                _logger.LogError("Не удалось найти указанный подготовленный пост в базе. SoftPost.Id = " + inputParam.SoftPostId);
                return(PublishResult.Error);
            }

            string userHash = await Authorize(inputParam);

            //Загружаем файл
            PublishResult torrentUploadResult = await UploadFile(inputParam,
                                                                 Path.GetFileName(post.TorrentFile),
                                                                 post.TorrentFile,
                                                                 userHash,
                                                                 inputParam.TorrentUploadQueryString);

            if (torrentUploadResult == PublishResult.Error)
            {
                _logger.LogError("Не удалось загрузить торрент файл на сайт");
                return(PublishResult.Error);
            }
            if (torrentUploadResult == PublishResult.FileExist)
            {
                _logger.LogError("Такой торрент файл уже загружен");
                return(PublishResult.FileExist);
            }

            //Загружаем постер
            SoftFileUploadResult imgUploadResult = await UploadPoster(inputParam,
                                                                      Path.GetFileName(post.PosterImg),
                                                                      post.PosterImg,
                                                                      userHash,
                                                                      inputParam.PosterUploadQueryString);

            if (imgUploadResult == null)
            {
                _logger.LogError("Не удалось загрузить постер на сайт");
                return(PublishResult.Error);
            }

            //Выкладываем
            bool sendPostResult = await SendPost(inputParam, imgUploadResult, userHash, post);

            if (!sendPostResult)
            {
                _logger.LogError("Не удалось отправить пост на сайт");
                return(PublishResult.Error);
            }
            return(PublishResult.Success);
        }
예제 #18
0
        internal async Task UploadAsync(
            AgentTaskPluginExecutionContext context,
            Fingerprint fingerprint,
            string path,
            CancellationToken cancellationToken)
        {
            VssConnection               connection = context.VssConnection;
            BlobStoreClientTelemetry    clientTelemetry;
            DedupManifestArtifactClient dedupManifestClient = DedupManifestArtifactClientFactory.CreateDedupManifestClient(context, connection, cancellationToken, out clientTelemetry);
            PipelineCacheClient         pipelineCacheClient = this.CreateClient(clientTelemetry, context, connection);

            using (clientTelemetry)
            {
                // Check if the key exists.
                PipelineCacheActionRecord cacheRecordGet = clientTelemetry.CreateRecord <PipelineCacheActionRecord>((level, uri, type) =>
                                                                                                                    new PipelineCacheActionRecord(level, uri, type, PipelineArtifactConstants.RestoreCache, context));
                PipelineCacheArtifact getResult = await pipelineCacheClient.GetPipelineCacheArtifactAsync(new [] { fingerprint }, cancellationToken, cacheRecordGet);

                // Send results to CustomerIntelligence
                context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: cacheRecordGet);
                //If cache exists, return.
                if (getResult != null)
                {
                    context.Output($"Cache with fingerprint `{getResult.Fingerprint}` already exists.");
                    return;
                }

                //Upload the pipeline artifact.
                PipelineCacheActionRecord uploadRecord = clientTelemetry.CreateRecord <PipelineCacheActionRecord>((level, uri, type) =>
                                                                                                                  new PipelineCacheActionRecord(level, uri, type, nameof(dedupManifestClient.PublishAsync), context));
                PublishResult result = await clientTelemetry.MeasureActionAsync(
                    record : uploadRecord,
                    actionAsync : async() =>
                {
                    return(await dedupManifestClient.PublishAsync(path, cancellationToken));
                });

                CreatePipelineCacheArtifactOptions options = new CreatePipelineCacheArtifactOptions
                {
                    Fingerprint = fingerprint,
                    RootId      = result.RootId,
                    ManifestId  = result.ManifestId,
                    ProofNodes  = result.ProofNodes.ToArray(),
                };

                // Cache the artifact
                PipelineCacheActionRecord cacheRecord = clientTelemetry.CreateRecord <PipelineCacheActionRecord>((level, uri, type) =>
                                                                                                                 new PipelineCacheActionRecord(level, uri, type, PipelineArtifactConstants.SaveCache, context));
                CreateStatus status = await pipelineCacheClient.CreatePipelineCacheArtifactAsync(options, cancellationToken, cacheRecord);

                // Send results to CustomerIntelligence
                context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: uploadRecord);
                context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: cacheRecord);
                context.Output("Saved item.");
            }
        }
예제 #19
0
        /// <summary>
        /// 发布流程模板
        /// </summary>
        public JsonResult PublishWorkflow(WorkflowTemplateViewModel model)
        {
            return(ExecuteFunctionRun(() =>
            {
                DraftWorkflowTemplate DraftWorkflowTemplate = ReadRequestWorkflowTemplate(model);
                if (DraftWorkflowTemplate == null)
                {
                    return Json(new { Result = false, Errors = new List <string>()
                                      {
                                          "Designer.WorkflowHandler_Msg1"
                                      } });
                }

                string WorkflowCode = DraftWorkflowTemplate.WorkflowCode;
                WorkflowClause Clause = this.Engine.WorkflowManager.GetClause(WorkflowCode);
                if (Clause == null)
                {
                    return Json(new { Result = false, Errors = new List <string>()
                                      {
                                          "Designer.WorkflowHandler_Msg2"
                                      } });
                }
                DraftWorkflowTemplate.BizObjectSchemaCode = Clause.BizSchemaCode;

                // 先保存流程模板
                if (!this.Engine.WorkflowManager.SaveDraftTemplate(this.UserValidator.UserID, DraftWorkflowTemplate))
                {
                    return Json(new { Result = false, Errors = new List <string>()
                                      {
                                          "Designer.WorkflowHandler_Msg3"
                                      } });
                }

                OThinker.H3.DataModel.BizObjectSchema schema = this.Engine.BizObjectManager.GetPublishedSchema(Clause.BizSchemaCode);
                OThinker.H3.ValidationResult ValidationResult = DraftWorkflowTemplate.Validate(schema);

                if (!ValidationResult.Valid)
                {
                    return Json(ValidationResult);
                }

                PublishResult PublishResult = this.Engine.WorkflowManager.RegisterWorkflow(this.UserValidator.UserID, DraftWorkflowTemplate.WorkflowCode, true);

                if (PublishResult.Result == (long)OThinker.H3.ErrorCode.SUCCESS)
                {
                    return Json(new { Result = true, Message = new List <string>()
                                      {
                                          "流程发布成功:当前版本号: " + PublishResult.RegisteredVersion.ToString()
                                      } });
                }
                else
                {
                    return Json(new { Result = false, Errors = PublishResult.Errors });
                }
            }));
        }
예제 #20
0
        public static PublishResult ToPublishResult(this YadResponseModel <YadPublishRequestData, YadPublishRequestParams> data)
        {
            var res = new PublishResult
            {
                IsSuccess = !string.IsNullOrEmpty(data.Data.ShortUrl),
                Url       = data.Data.ShortUrl
            };

            return(res);
        }
예제 #21
0
        public static PublishResult ToPublishResult(this CommonOperationResult <string> data)
        {
            var res = new PublishResult
            {
                IsSuccess = data.Status == 200,
                Url       = data.Body
            };

            return(res);
        }
예제 #22
0
        /// <summary>
        ///  turns a PublishResult into an Attempt
        /// </summary>
        public static Attempt <string> ToAttempt(this PublishResult result)
        {
            if (result.Success)
            {
                return(Attempt.Succeed("Published"));
            }

            var errorMessage = result.EventMessages.FormatMessages(":");

            return(Attempt.Fail($"Publish failed: {result.Result} {errorMessage}"));
        }
        public async Task <ActionResult <string> > AddPost([FromBody] SoftPostInput inputParam)
        {
            PublishResult result = await _softService.AddPost(inputParam);

            if (result == PublishResult.Success)
            {
                return(Ok("Пост успешно добавлен"));
            }

            return(BadRequest("Не удалось добавить пост"));
        }
예제 #24
0
        /// <summary>
        /// Подготавливаем и выкладываем пост
        /// </summary>
        /// <param name="itemType">Тип поста</param>
        /// <param name="itemId">Id поста</param>
        /// <returns>Если метод выполнен успешно - true, инчае false</returns>
        async Task <PublishResult> Send(string itemType, int itemId)
        {
            //Подготавливаем
            DriverToSoftInput driverInput =
                _context.DriverToSoftInputs
                .Single(el => el.Active && el.Type == itemType);

            driverInput.ParseItemId = itemId;
            SoftPost post = await _driverService.Convert(driverInput);

            if (post == null)
            {
                _logger.LogError($"Не удалось подготовить пост к публикации. {itemType}.Id = " + itemId);
                return(PublishResult.Error);
            }

            //Выкладываем
            SoftPostInput softPostInput =
                _context.SoftPostInputs
                .Single(el => el.Active);

            softPostInput.SoftPostId = post.Id;
            softPostInput.PosterUploadQueryString =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.PosterUploadQueryStringId)
                .ToDictionary(k => k.Key, v => v.Value);
            softPostInput.TorrentUploadQueryString =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.TorrentUploadQueryStringId)
                .ToDictionary(k => k.Key, v => v.Value);
            softPostInput.FormData =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.FormDataId)
                .ToDictionary(k => k.Key, v => v.Value);
            softPostInput.AuthData =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.AuthDataId)
                .ToDictionary(k => k.Key, v => v.Value);
            PublishResult result = await _softService.AddPost(softPostInput);

            if (result == PublishResult.Error)
            {
                _logger.LogError("Не удалось выложить пост на сайт. SoftPost.Id = " + post.Id);
                return(PublishResult.Error);
            }
            if (result == PublishResult.FileExist)
            {
                _logger.LogError("Не удалось выложить пост на сайт. Такой файл уже загружен.");
                return(PublishResult.FileExist);
            }
            return(PublishResult.Success);
        }
예제 #25
0
        public async Task <IActionResult> PostPublish([FromBody] MessagePublishDto message)
        {
            this.logger.LogTrace("Call publis message fro topic: {0}", message.Topic);

            PublishResult result = await this.messageRepository.Publish(message.Topic, message.Message).ConfigureAwait(false);

            foreach (PublishPair storedMessage in result.CratedMessages)
            {
                await this.notificationSender.SendNotificationAsync(storedMessage.QueuId, storedMessage.MessageId).ConfigureAwait(false);
            }

            return(this.CreatedAtAction(nameof(this.GetMessages), null, result));
        }
예제 #26
0
 private void btnF03_Click(object sender, EventArgs e)
 {
     this.FunctionCalled(10, btnF03);
     if (rdoPrintPossible.Checked)
     {
         Result = PublishResult.Print;
     }
     else
     {
         Result = PublishResult.CSV;
     }
     Exit();
     Close();
 }
        public PublishResult Publish(byte[] message)
        {
            PublishResult pr = new PublishResult();

            try
            {
                _channel.BasicPublish(exchange: "", routingKey: _args.Queue, basicProperties: null, body: message);
                pr.Result = true;
            }
            catch (Exception ex)
            {
                pr.Result = false;
            }
            return(pr);
        }
        public PublishResult Publish(byte[] message)
        {
            PublishResult pr = new PublishResult();

            try
            {
                var asbMessage = new Message(message);
                queueClient.SendAsync(asbMessage);
            }
            catch (Exception ex)
            {
                pr.Result = false;
            }
            return(pr);
        }
예제 #29
0
        private async Task PublishToSteam(string folder)
        {
            Steamworks.Ugc.Editor editor = new Steamworks.Ugc.Editor();
            editor = (this.ItemId != 0 ? new Steamworks.Ugc.Editor(this.ItemId) : Steamworks.Ugc.Editor.NewMicrotransactionFile);
            Steamworks.Ugc.Editor editor1 = editor.WithContent(folder);
            editor1 = editor1.WithPreviewFile(string.Concat(folder, "/icon_background.png"));
            editor1 = editor1.WithTitle(this.Title);
            editor1 = editor1.WithTag("Version3");
            editor1 = editor1.WithTag(this.Skinnable.Name);
            editor1 = editor1.WithTag("Skin");
            editor  = editor1.WithPublicVisibility();
            if (!string.IsNullOrEmpty(this.ChangeLog.text))
            {
                editor = editor.WithChangeLog(this.ChangeLog.text);
            }
            WorkshopItemEditor.Loading(true, "Publishing To Steam", "", 0f);
            PublishResult publishResult = await editor.SubmitAsync(null);

            if (publishResult.Success)
            {
                UnityEngine.Debug.Log(string.Concat("Published File: ", publishResult.FileId));
            }
            else
            {
                UnityEngine.Debug.Log(string.Concat("Error: ", publishResult.Result));
            }
            Item?nullable = await SteamUGC.QueryFileAsync(publishResult.FileId);

            if (nullable.HasValue)
            {
                WorkshopItemEditor id = this.Editor;
                Item value            = nullable.Value;
                id.ItemId = value.Id;
                WorkshopItemEditor title = this.Editor;
                value               = nullable.Value;
                title.ItemTitle     = value.Title;
                this.ChangeLog.text = "";
                value               = nullable.Value;
                UnityEngine.Application.OpenURL(value.Url);
                WorkshopItemList.RefreshAll();
            }
            else
            {
                UnityEngine.Debug.Log("Error Retrieving item information!");
                WorkshopItemList.RefreshAll();
            }
        }
예제 #30
0
        public async Task <WorkshopItemPublishResult> PublishNewWorkshopItemAsync(IWorkshopItemChangeSet settings)
        {
            Editor editor = Editor.NewCommunityFile;

            editor = EditorWithVisibility(settings.Visibility, ref editor)
                     .ForAppId(AppId)
                     .WithTitle(settings.Title)
                     .WithDescription(settings.GetDescriptionTextFromFile())
                     .WithContent(new DirectoryInfo(settings.ItemFolderPath))
                     .InLanguage(settings.Language);
            WithTags(settings, ref editor);

            Steamworks.Ugc.PublishResult submitResult = await editor.SubmitAsync();

            PublishResult publishResult = submitResult.Success ? PublishResult.Ok : PublishResult.Failed;

            return(new WorkshopItemPublishResult(submitResult.FileId, publishResult));
        }
        internal async Task UploadAsync(
            AgentTaskPluginExecutionContext context,
            IEnumerable <string> key,
            string path,
            string salt,
            CancellationToken cancellationToken)
        {
            VssConnection               connection = context.VssConnection;
            BlobStoreClientTelemetry    clientTelemetry;
            DedupManifestArtifactClient dedupManifestClient = DedupManifestArtifactClientFactory.CreateDedupManifestClient(context, connection, out clientTelemetry);
            PipelineCacheClient         pipelineCacheClient = this.CreateClient(clientTelemetry, context, connection);

            using (clientTelemetry)
            {
                //Upload the pipeline artifact.
                PipelineCacheActionRecord uploadRecord = clientTelemetry.CreateRecord <PipelineCacheActionRecord>((level, uri, type) =>
                                                                                                                  new PipelineCacheActionRecord(level, uri, type, nameof(dedupManifestClient.PublishAsync), context));
                PublishResult result = await clientTelemetry.MeasureActionAsync(
                    record : uploadRecord,
                    actionAsync : async() =>
                {
                    return(await dedupManifestClient.PublishAsync(path, cancellationToken));
                });

                CreatePipelineCacheArtifactOptions options = new CreatePipelineCacheArtifactOptions
                {
                    Key        = key,
                    RootId     = result.RootId,
                    ManifestId = result.ManifestId,
                    ProofNodes = result.ProofNodes.ToArray(),
                    Salt       = salt
                };

                // Cache the artifact
                PipelineCacheActionRecord cacheRecord = clientTelemetry.CreateRecord <PipelineCacheActionRecord>((level, uri, type) =>
                                                                                                                 new PipelineCacheActionRecord(level, uri, type, PipelineArtifactConstants.SaveCache, context));
                CreateStatus status = await pipelineCacheClient.CreatePipelineCacheArtifactAsync(options, cancellationToken, cacheRecord);

                // Send results to CustomerIntelligence
                context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: uploadRecord);
                context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: cacheRecord);
                context.Output("Saved item.");
            }
        }