コード例 #1
0
        public void DeleteDocument(string parentSubPath, ProjectItemType type, string documentName)
        {
            var fileName = "";

            if (type == ProjectItemType.Page)
            {
                fileName = $"{documentName}.{Constants.ProjectItemFileExtensions.Page}";
            }
            if (type == ProjectItemType.Workflow)
            {
                fileName = $"{documentName}.{Constants.ProjectItemFileExtensions.Workflow}";
            }
            var filePath = Path.Combine(Path.GetDirectoryName(_projectFilePath), parentSubPath, fileName);

            if (!File.Exists(filePath))
            {
                throw new ArgumentException($"A {type.ToString()} named '{fileName}' does not exist in this directory and cannot be deleted!");
            }

            _cmdProcessor.Execute(DeleteDocumentCommand.Create(_outputService, _projectFilePath, parentSubPath, fileName));

            ProjectItemChanged?.Invoke(new ProjectItemChangedArgs
            {
                ItemType      = type,
                Change        = ProjectItemChange.Delete,
                ItemName      = documentName,
                ParentSubPath = parentSubPath
            });
        }
コード例 #2
0
        public void SerializeAndDeserialize_DeleteDocumentCommandTest()
        {
            using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context))
            {
                //Arrange
                var expected = new DeleteDocumentCommand("Some Id", "Some Change Vector", null);

                //Action
                var jsonSerializer = GetJsonSerializer();
                BlittableJsonReaderObject blitCommand;
                using (var writer = new BlittableJsonWriter(context))
                {
                    var dto = expected.ToDto(context);
                    jsonSerializer.Serialize(writer, dto);
                    writer.FinalizeDocument();

                    blitCommand = writer.CreateReader();
                }
                var fromStream = SerializeTestHelper.SimulateSavingToFileAndLoading(context, blitCommand);
                DeleteDocumentCommand actual;
                using (var reader = new BlittableJsonReader(context))
                {
                    reader.Init(fromStream);

                    var dto = jsonSerializer.Deserialize <DeleteDocumentCommandDto>(reader);
                    actual = dto.ToCommand(null, null);
                }

                //Assert
                Assert.Equal(expected, actual, new CustomComparer <DeleteDocumentCommand>(context));
            }
        }
コード例 #3
0
        public void Delete(string id)
        {
            var session = store.OpenSession();
            var command = new DeleteDocumentCommand(id, null);

            session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
        }
コード例 #4
0
    /// <inheritdoc />
    public Task DeleteDocumentAsync(Guid id)
    {
        this._logger.LogDebug(nameof(this.DeleteDocumentAsync), id);
        var command = new DeleteDocumentCommand(id);

        return(this._mediator.Send(command));
    }
コード例 #5
0
 public async Task ShouldThrowErrorForInvalidInput()
 {
     var command = new DeleteDocumentCommand
     {
         RowKey = Guid.Empty
     };
     await Assert.ThrowsAsync <ValidationException>(() => SendAsync(command));
 }
コード例 #6
0
ファイル: Documents.cs プロジェクト: RhysC/mycouch
        protected virtual HttpRequestMessage CreateRequest(DeleteDocumentCommand cmd)
        {
            var req = new HttpRequest(HttpMethod.Delete, GenerateRequestUrl(cmd.Id, cmd.Rev));

            req.SetIfMatch(cmd.Rev);

            return(req);
        }
コード例 #7
0
        public async Task ExecuteAsync(AnonymizeBookingsCommand command, IExecutionContext executionContext)
        {
            PermissionValidationService.EnforceCustomEntityPermission <CustomEntityDeletePermission>(BookingCustomEntityDefinition.DefinitionCode, executionContext.UserContext);

            var query = new SearchBookingSummariesQuery
            {
                BookingState = new BookingDataModel.BookingStateType[] { BookingDataModel.BookingStateType.Closed },
                Start        = new DateTime(2000, 1, 1),
                End          = DateTime.Now.AddYears(-3)
            };

            command.AnonymizedCount = 0;

            foreach (KeyValuePair <int, BookingDataModel> bookingEntry in (await BookingProvider.FindBookingDataInInterval(query)).ToList())
            {
                BookingDataModel booking = bookingEntry.Value;

                // Protected agains mistakes in the query by checking values again
                if (!booking.IsArchived &&
                    booking.BookingState == BookingDataModel.BookingStateType.Closed &&
                    booking.DepartureDate.Value.AddYears(3) < DateTime.Now)
                {
                    booking.TenantName     = "---";
                    booking.Purpose        = "---";
                    booking.ContactName    = "---";
                    booking.ContactEMail   = "ukendt@ukendte-mailmodtagere";
                    booking.ContactPhone   = "---";
                    booking.ContactAddress = "---";
                    booking.ContactCity    = "---";
                    booking.Comments       = "---";

                    foreach (var document in booking.Documents)
                    {
                        var deleteDocumentCommand = new DeleteDocumentCommand {
                            Id = document.DocumentId
                        };
                        await CommandExecutor.ExecuteAsync(deleteDocumentCommand);
                    }

                    booking.LogEntries.Clear();
                    booking.Documents.Clear();

                    booking.IsArchived = true;
                    command.AnonymizedCount++;

                    UpdateCustomEntityDraftVersionCommand updateCmd = new UpdateCustomEntityDraftVersionCommand
                    {
                        CustomEntityDefinitionCode = BookingCustomEntityDefinition.DefinitionCode,
                        CustomEntityId             = bookingEntry.Key,
                        Title   = booking.MakeTitle(),
                        Publish = true,
                        Model   = booking
                    };

                    await DomainRepository.CustomEntities().Versions().UpdateDraftAsync(updateCmd);
                }
            }
        }
コード例 #8
0
 public async Task <IActionResult> Delete([FromQuery(Name = "id"), MaxLength(200)] IEnumerable <long> ids, CancellationToken token)
 {
     foreach (var id in ids)
     {
         var command = new DeleteDocumentCommand(id);
         await _commandBus.DispatchAsync(command, token);
     }
     return(Ok());
 }
コード例 #9
0
ファイル: Documents.cs プロジェクト: RhysC/mycouch
        public virtual async Task <DocumentHeaderResponse> DeleteAsync(DeleteDocumentCommand cmd)
        {
            Ensure.That(cmd, "cmd").IsNotNull();

            var req = CreateRequest(cmd);
            var res = SendAsync(req);

            return(ProcessDocumentHeaderResponse(await res.ForAwait()));
        }
コード例 #10
0
        public async Task <IActionResult> DeleteAsync([FromRoute] string id)
        {
            var command = new DeleteDocumentCommand
            {
                Id = id
            };

            var response = await _mediator.Send(command);

            return(JsonResult(response));
        }
コード例 #11
0
        public async Task <bool> Handle(DeleteDocumentCommand request, CancellationToken cancellationToken)
        {
            var document = await _documentRepository.GetDocument(request.Id);

            if (document == null)
            {
                throw new Exception($"Document with id {request.Id} does not exist");
            }

            return(await _documentRepository.Delete(request.Id));
        }
コード例 #12
0
 public void Foo()
 {
     using (var store = new DocumentStore())
         using (var session = store.OpenSession())
         {
             #region delete_sample
             var command = new DeleteDocumentCommand("employees/1-A", null);
             session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
             #endregion
         }
 }
コード例 #13
0
            public async Task DeleteAsync(string id, string changeVector)
            {
                if (id == null)
                {
                    throw new ArgumentNullException(nameof(id));
                }

                var command = new DeleteDocumentCommand(id, changeVector);

                await RequestExecutor.ExecuteAsync(command, Context);
            }
コード例 #14
0
 /// <summary>
 /// Handles a deletion request of a Document record.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns></returns>
 public async Task <Unit> Handle(DeleteDocumentCommand request, CancellationToken cancellationToken)
 {
     try
     {
         await this._repository.DeleteDocumentAsync(request.Id);
     }
     catch (Exception exception)
     {
         this._logger.LogError(exception, exception.Message, request);
     }
     return(Unit.Value);
 }
コード例 #15
0
        protected Task <IOperationResult> ExecuteDelete(IndexQueryServerSide query, Index index, QueryOperationOptions options, DocumentsOperationContext context, Action <DeterminateProgress> onProgress, OperationCancelToken token)
        {
            return(ExecuteOperation(query, index, options, context, onProgress, (key, retrieveDetails) =>
            {
                var command = new DeleteDocumentCommand(key, null, Database);

                return new BulkOperationCommand <DeleteDocumentCommand>(command, retrieveDetails, x => new BulkOperationResult.DeleteDetails
                {
                    Id = key,
                    Etag = x.DeleteResult?.Etag
                });
            }, token));
        }
コード例 #16
0
        public async Task <IActionResult> Delete(Guid documentId, CancellationToken cancellationToken)
        {
            var documentQuery = new DocumentQuery(documentId);
            var document      = await Mediator.Send(documentQuery, cancellationToken);

            if (document == null)
            {
                return(NotFound("Document not found"));
            }

            var deleteDocumentCommand = DeleteDocumentCommand.Create(document);
            await Mediator.Send(deleteDocumentCommand, cancellationToken);

            return(NoContent());
        }
コード例 #17
0
        public async Task ShouldDeleteNewDocument()
        {
            var rowKey = await CreateTestData();

            var command = new DeleteDocumentCommand
            {
                RowKey = rowKey
            };

            await SendAsync(command);

            await Assert.ThrowsAsync <CustomException>(() => SendAsync(new FetchDocumentLocationQuery {
                RowKey = rowKey
            }));
        }
コード例 #18
0
        public async Task Handler_GivenValidParameters_ReturnsTrue()
        {
            var filename          = "example.pdf";
            var cancellationToken = new CancellationToken();

            var repository = new Mock <IDocumentRepository>();

            repository.Setup(x => x.Delete(filename, cancellationToken)).ReturnsAsync(true);

            var request = new DeleteDocumentCommand(filename);
            var handler = new DeleteDocumentCommandHandler(repository.Object);

            var result = await handler.Handle(request, cancellationToken);

            result.IsSuccessful.ShouldBeTrue();
        }
コード例 #19
0
        public async Task Handler_GivenNonExistentFilenameParameters_ReturnsEmptyValue()
        {
            var filename          = "doesntexist.pdf";
            var cancellationToken = new CancellationToken();

            var repository = new Mock <IDocumentRepository>();

            repository.Setup(x => x.Delete(filename, cancellationToken)).ReturnsAsync(false);

            var request = new DeleteDocumentCommand(filename);
            var handler = new DeleteDocumentCommandHandler(repository.Object);

            var result = await handler.Handle(request, cancellationToken);

            result.IsSuccessful.ShouldBeFalse();
        }
コード例 #20
0
        public async Task <IActionResult> DeleteDocumentAsync([FromRoute] DeleteDocumentRequest model, CancellationToken token)
        {
            try
            {
                var command = new DeleteDocumentCommand(model.Id, _userManager.GetLongUserId(User));
                await _commandBus.DispatchAsync(command, token);

                return(Ok());
            }
            catch (NotFoundException)
            {
                return(NotFound());
            }
            catch (InvalidOperationException)
            {
                ModelState.AddModelError("error", _localizer["SomeOnePurchased"]);
                return(BadRequest(ModelState));
            }
        }
コード例 #21
0
        public async Task ExecuteAsync(DeleteBookingCommand command, IExecutionContext executionContext)
        {
            PermissionValidationService.EnforceCustomEntityPermission <CustomEntityDeletePermission>(BookingCustomEntityDefinition.DefinitionCode, executionContext.UserContext);

            using (var scope = DomainRepository.Transactions().CreateScope())
            {
                var booking = await BookingProvider.GetBookingById(command.Id);

                foreach (var document in booking.Documents)
                {
                    var deleteDocumentCommand = new DeleteDocumentCommand {
                        Id = document.DocumentId
                    };
                    await CommandExecutor.ExecuteAsync(deleteDocumentCommand);
                }

                await DomainRepository.CustomEntities().DeleteAsync(command.Id);

                await scope.CompleteAsync();
            }
        }
コード例 #22
0
        protected void top_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            ImageButton action       = (ImageButton)e.CommandSource;
            string      actionString = action.ID;

            if (action.ID.Equals("delete"))
            {
                try
                {
                    Document document = new Document();
                    string   id       = ((Label)document_list.Items[e.Item.ItemIndex].FindControl("Id")).Text;
                    document.Id = Int32.Parse(id);
                    DeleteDocumentCommand cmd = new DeleteDocumentCommand(document);
                    cmd.Execute();
                    if (document.Code == 200)
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "random", "alertme()", true);
                    }
                    else
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "random", "alertmeErr()", true);
                    }
                }
                catch (Exception ex)
                {
                }
            }
            else if (action.ID.Equals("modify"))
            {
                try
                {
                    string id = ((Label)document_list.Items[e.Item.ItemIndex].FindControl("Id")).Text;
                    Session["Id_doc"] = id;
                    Response.Redirect("/site/admin/adm_content/edit_doc.aspx");
                }
                catch (Exception ex)
                {
                }
            }
        }
コード例 #23
0
        public async Task Examples()
        {
            using (var documentStore = new DocumentStore())
            {
                #region commands_1
                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("orders/1-A", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var order = (BlittableJsonReaderObject)command.Result.Results[0];
                }
                #endregion

                #region commands_1_async
                using (var session = documentStore.OpenAsyncSession())
                {
                    var command = new GetDocumentsCommand("orders/1-A", null, false);
                    await session.Advanced.RequestExecutor.ExecuteAsync(command, session.Advanced.Context);

                    var order = (BlittableJsonReaderObject)command.Result.Results[0];
                }
                #endregion

                #region commands_2
                using (var session = documentStore.OpenSession())
                {
                    var command = new DeleteDocumentCommand("employees/1-A", null);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                }
                #endregion

                #region commands_2_async
                using (var session = documentStore.OpenAsyncSession())
                {
                    var command = new DeleteDocumentCommand("employees/1-A", null);
                    await session.Advanced.RequestExecutor.ExecuteAsync(command, session.Advanced.Context);
                }
                #endregion
            }
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: uk-gov-mirror/jncc.topcat
        static int RunDelete(DeleteOptions options)
        {
            InitDatabase();

            string luceneQuery = "Keywords:\"http://vocab.jncc.gov.uk/metadata-admin/Delete\"";

            using (var db = DocumentStore.OpenSession())
            {
                // this loads all the records into memory because i can't figure out how to do it better
                // https://groups.google.com/forum/#!topic/ravendb/ELqhzCs2amY

                var records = db.Advanced.DocumentQuery <Record>("RecordIndex").WhereLucene("Keywords", luceneQuery).ToList();
                Logger.Info($"Deleting {records.Count} records:");
                foreach (var record in records)
                {
                    Logger.Info($"{record.Id} ({record.Gemini.Title})");
                }
                Logger.Info("If this said 128 then it could be more!");

                if (!options.WhatIf)
                {
                    foreach (var record in records)
                    {
                        var command = new DeleteDocumentCommand(record.Id, null);
                        db.Advanced.RequestExecutor.Execute(command, db.Advanced.Context);
                    }
                }

                Logger.Info("Delete requests sent to database.");
            }

            if (options.WhatIf)
            {
                Logger.Info("Ran in 'what-if' mode. Nothing was really done.");
            }

            return(1);
        }
コード例 #25
0
ファイル: FilesController.cs プロジェクト: team-itp/docms
        public async Task <IActionResult> Delete(
            [FromQuery] string path,
            [FromServices] IMediator mediator)
        {
            if (!FilePath.TryParse(path, out var filepath))
            {
                return(BadRequest("invalid path name."));
            }

            try
            {
                var command = new DeleteDocumentCommand
                {
                    Path = filepath
                };
                var response = await mediator.Send(command);

                return(Ok());
            }
            catch (InvalidOperationException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
コード例 #26
0
 private void PatientDocumentDtosCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
     ImportC32DocumentCommand.RaiseCanExecuteChanged();
     DeleteDocumentCommand.RaiseCanExecuteChanged();
 }
コード例 #27
0
 public static Task <DocumentHeaderResponse> ExecuteAsync(this IClient client, DeleteDocumentCommand cmd)
 {
     return(client.Documents.DeleteAsync(cmd));
 }
コード例 #28
0
        public static async Task Read()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token2.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    _scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                //Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = _applicationName,
            });

            // Define request parameters.
            string spreadsheetId = "1hEET4d0YKmHBWQhbwkxPifcXVB5zqgs2Tcs2NiXLnlc";
            string range         = "Ram Sheet!A1:C";

            SpreadsheetsResource.ValuesResource.GetRequest request =
                service.Spreadsheets.Values.Get(spreadsheetId, range);

            // Prints the names and majors of students in a sample spreadsheet:
            // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
            ValueRange response = request.Execute();
            var        values   = response.Values;

            var session = Program.Container.Resolve <IStatelessSession>();
            var bus     = Program.Container.Resolve <ICommandBus>();

            if (values != null && values.Count > 0)
            {
                for (int i = 0; i < values.Count; i++)
                {
                    var row = values[i];
                    //foreach (var row in values)
                    //{

                    var deleteRow = row.Count > 2 ? row[2].ToString() : null;

                    if (string.Equals(deleteRow, "DELETE", StringComparison.OrdinalIgnoreCase))
                    {
                        var courseName = row[0].ToString();
                        //if (courseName.ToUpperInvariant()[0] <= 'U')
                        //{
                        //     continue;
                        //}

                        Console.WriteLine($"Processing {courseName}");
                        var result = await session.Query <Course>()
                                     .Where(w => w.Id == courseName).SingleOrDefaultAsync();

                        if (result is null)
                        {
                            string range2      = $"Ram Sheet!E{i + 1}";
                            var    requestBody = new ValueRange();
                            requestBody.Values = new List <IList <object> >()
                            {
                                new List <object>()
                                {
                                    "Done"
                                }
                            };
                            var update = service.Spreadsheets.Values.Update(requestBody, spreadsheetId, range2);
                            update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest
                                                      .ValueInputOptionEnum.RAW;
                            update.Execute();
                            continue;
                        }

                        var documents = await session.Query <Document>().Fetch(f => f.University)
                                        .Where(w => w.Course.Id == courseName).ToListAsync();


                        foreach (var document in documents.Where(w => w.Status.State == ItemState.Deleted))
                        {
                            await session.CreateSQLQuery("delete from sb.DocumentsTags where DocumentId = :id")
                            .SetInt64("id", document.Id).ExecuteUpdateAsync();

                            await session.Query <Document>().Where(w => w.Id == document.Id)
                            .DeleteAsync(CancellationToken.None);
                        }

                        var goodCountries = new[] { "US", "IL" };
                        if (documents.Any(a => goodCountries.Contains(a.University.Country, StringComparer.OrdinalIgnoreCase)))
                        {
                            var x = string.Join(",", documents.Select(a => a.University.Country)); Console.WriteLine(x);


                            Console.WriteLine("Cant delete because of document");

                            await session.Query <UserCourse>()
                            .Where(w => w.Course.Id == courseName && session.Query <User>().Where(w2 => w2.Country == "IN").Contains(w.User))
                            .DeleteAsync(CancellationToken.None);

                            continue;
                        }
                        //var canDelete = true;
                        foreach (var document in documents)
                        {
                            var deleteDocumentCommand = new DeleteDocumentCommand(document.Id);
                            await bus.DispatchAsync(deleteDocumentCommand, default);

                            await session.CreateSQLQuery("delete from sb.DocumentsTags where DocumentId = :id")
                            .SetInt64("id", document.Id).ExecuteUpdateAsync();

                            await session.Query <Document>().Where(w => w.Id == document.Id)
                            .DeleteAsync(CancellationToken.None);
                        }


                        var questions = await session.Query <Question>().FetchMany(f => f.Answers).Where(w => w.Course.Id == courseName).ToListAsync();

                        //if (questions.Any())
                        //{
                        //    //var deleteQuestionCommand =
                        //    //    new Cloudents.Command.Command.Admin.DeleteQuestionCommand(question.Id);
                        //    //await bus.DispatchAsync(deleteQuestionCommand, default);
                        //    //Console.WriteLine("Cant delete question");
                        //    //continue;
                        //}
                        foreach (var question in questions)
                        {
                            //    var response2 = ConsoleKey.Y;
                            //    if (question.Status.State == ItemState.Ok)
                            //    {
                            //        Console.WriteLine($"Delete document id : {question.Id} text {question.Text}");
                            //        response2 = Console.ReadKey(false).Key;
                            //    }


                            //    if (response2 == ConsoleKey.Y)
                            //    {
                            //var deleteQuestionCommand =
                            //    new Cloudents.Command.Command.Admin.DeleteQuestionCommand(question.Id);
                            //await bus.DispatchAsync(deleteQuestionCommand, default);
                            await session.CreateSQLQuery("delete from sb.[transaction] where questionId=:id")
                            .SetInt64("id", question.Id).ExecuteUpdateAsync();

                            //await session.Query<QuestionTransaction>().Where(w => w.Question.Id == question.Id)
                            //    .DeleteAsync(CancellationToken.None);

                            //await session.Query<AwardsTransaction>().Where(w => w.Question.Id == question.Id)
                            //    .DeleteAsync(CancellationToken.None);

                            foreach (var answer in question.Answers)
                            {
                                await session.Query <QuestionTransaction>().Where(w => w.Answer.Id == answer.Id)
                                .DeleteAsync(CancellationToken.None);
                            }
                            await session.CreateSQLQuery("delete from sb.vote where questionid = :id")
                            .SetInt64("id", question.Id).ExecuteUpdateAsync();

                            await session.CreateSQLQuery("update sb.question set correctanswer_id = null where id = :id")
                            .SetInt64("id", question.Id).ExecuteUpdateAsync();



                            await session.Query <Answer>().Where(w => w.Question.Id == question.Id)
                            .DeleteAsync(CancellationToken.None);

                            await session.Query <Question>().Where(w => w.Id == question.Id)
                            .DeleteAsync(CancellationToken.None);
                        }

                        try
                        {
                            await session.Query <UserCourse>().Where(w => w.Course.Id == courseName)
                            .DeleteAsync(CancellationToken.None);

                            //await session.Query<Lead>().Where(w => w.Course.Id == courseName)
                            //    .DeleteAsync(CancellationToken.None);

                            await session.Query <Course>().Where(w => w.Id == courseName)
                            .DeleteAsync(CancellationToken.None);

                            string range2      = $"Ram Sheet!E{i}";
                            var    requestBody = new ValueRange();
                            requestBody.Values = new List <IList <object> >()
                            {
                                new List <object>()
                                {
                                    "Done"
                                }
                            };
                            var update = service.Spreadsheets.Values.Update(requestBody, spreadsheetId, range2);
                            update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest
                                                      .ValueInputOptionEnum.RAW;
                            update.Execute();
                        }
                        catch (Exception)
                        {
                        }
                        //    }
                        //    else
                        //    {
                        //        canDelete = false;
                        //    }

                        //}

                        //if (canDelete)
                        //{
                        //using (var beginLifetimeScope = Program._container.BeginLifetimeScope())
                        //{


                        //    using (var session2 = beginLifetimeScope.Resolve<ISession>())
                        //    {
                        //        using (var uc = session2.BeginTransaction())
                        //        {
                        //            //using (var uc = Program._container.Resolve<IUnitOfWork>())
                        //            //{
                        //            var course = await session2.LoadAsync<Course>(courseName);
                        //            await session2.DeleteAsync(course);

                        //            //await session.Query<Course>().Where(w => w.Id == courseName).DeleteAsync(CancellationToken.None);

                        //            await uc.CommitAsync(CancellationToken.None);
                        //        }

                        //        //}
                        //    }
                        //}
                        //}
                    }
                }
            }
        }
コード例 #29
0
        public static async Task DocumentProcessFunctionAsync(
            [QueueTrigger("generate-search-preview")] string id,
            [Blob("spitball-files/files/{QueueTrigger}")] CloudBlobDirectory dir,
            [Blob("spitball-files/files/{QueueTrigger}/text.txt")] CloudBlockBlob blob,
            [AzureSearchSync(DocumentSearchWrite.IndexName)]  IAsyncCollector <AzureSearchSyncOutput> indexInstance,
            [Inject] ICommandBus commandBus,
            ILogger log,
            CancellationToken token)
        {
            log.LogInformation($"Processing {id}");
            var x = await dir.ListBlobsSegmentedAsync(null);

            var longId = Convert.ToInt64(id);

            if (!x.Results.Any())
            {
                //There is no file - deleting it.
                var command = new DeleteDocumentCommand(longId);
                await commandBus.DispatchAsync(command, token);

                return;
            }
            try
            {
                var text = await blob.DownloadTextAsync();

                await blob.FetchAttributesAsync();

                var metadata = blob.Metadata;

                int?pageCount = null;
                if (metadata.TryGetValue("PageCount", out var pageCountStr) &&
                    int.TryParse(pageCountStr, out var pageCount2))
                {
                    pageCount = pageCount2;
                }


                var snippet = text.Truncate(200, true);
                var command = UpdateDocumentMetaCommand.Document(longId, pageCount, snippet);
                await commandBus.DispatchAsync(command, token);

                await indexInstance.AddAsync(new AzureSearchSyncOutput()
                {
                    Item = new Search.Entities.Document
                    {
                        Id      = id,
                        Content = text.Truncate(6000)
                    },
                    Insert = true
                }, token);
            }
            catch (ObjectNotFoundException)
            {
                await indexInstance.AddAsync(new AzureSearchSyncOutput()
                {
                    Item = new Search.Entities.Document
                    {
                        Id = id,
                    },
                    Insert = false
                }, token);
            }
            catch (StorageException ex) when(ex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
            {
                //Text blob was not found - somehow
                //Do nothing
            }
        }
コード例 #30
0
 public Document CreateFromCommand(DeleteDocumentCommand command)
 {
     return(new Document(command.Id));
 }