Esempio n. 1
0
        protected void PageLoad()
        {
            var file = new File();

            try
            {
                ShareLink = Request[UrlConstant.DocUrlKey] ?? "";
                WithLink  = !string.IsNullOrEmpty(ShareLink);

                var fileId = WithLink ? (object)-1 : Request[UrlConstant.FileId];
                FileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                file = DocumentUtils.EditIframeSrc(fileId, FileNew, ShareLink, out SrcIframe);

                if (SecurityContext.IsAuthenticated)
                {
                    var parent = Global.DaoFactory.GetFolderDao().GetFolder(file.FolderID);
                    if (file.RootFolderType == FolderType.USER &&
                        file.RootFolderCreator != SecurityContext.CurrentAccount.ID &&
                        !Global.GetFilesSecurity().CanRead(parent))
                    {
                        FolderUrl = PathProvider.GetFolderUrl(Global.FolderShare, false, null);
                    }
                    else
                    {
                        FolderUrl = PathProvider.GetFolderUrl(parent);

                        if (string.IsNullOrEmpty(FolderUrl))
                        {
                            FolderUrl = Request.UrlReferrer == null
                                            ? VirtualPathUtility.ToAbsolute(PathProvider.StartURL)
                                            : Request.UrlReferrer.ToString();
                        }

                        if (Global.EnableShare)
                        {
                            CommonContainerHolder.Controls.Add(LoadControl(AccessRights.Location));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Redirect(PathProvider.BaseVirtualPath + "docviewer.aspx" + "?" + Request.QueryString + "#" + UrlConstant.Error + "/" + HttpUtility.UrlEncode(ex.Message));
            }

            Title       = file.Title;
            FileId      = file.ID;
            FileTitle   = file.Title;
            FileVersion = file.Version;

            DocKeyForTrack = DocumentUtils.GetDocKey(file.ID, -1, DateTime.MinValue);

            using (var tagDao = Global.DaoFactory.GetTagDao())
            {
                tagDao.RemoveTags(Tag.New(SecurityContext.CurrentAccount.ID, file));
            }

            FileLocker.Add(file.ID);
        }
Esempio n. 2
0
        /// <summary>
        /// This node will copy the given elements from the given document into the active document.
        /// </summary>
        /// <param name="sourceDocument">The background opened document object, (preferably this is the title as obtained with Applications.OpenDocumentFile from Rhythm).</param>
        /// <param name="elements">The elements to copy.</param>
        /// <returns name="newElements">The copied elements.</returns>
        /// <search>
        /// copy
        /// </search>
        public static List <global::Revit.Elements.Element> CopyElementsFromDocument(object sourceDocument, List <global::Revit.Elements.Element> elements)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            Document sourceDoc             = DocumentUtils.RetrieveDocument(sourceDocument);
            //converts elements to ids in a collection
            ICollection <ElementId> idCollection = new List <ElementId>();

            foreach (global::Revit.Elements.Element element in elements)
            {
                idCollection.Add(element.InternalElement.Id);
            }
            //creates blank copy paste options
            CopyPasteOptions copyOpts = new CopyPasteOptions();
            //creates blank transform.
            Transform transform = Transform.CreateTranslation(Vector.XAxis().ToRevitType());

            //commits the transaction
            TransactionManager.Instance.EnsureInTransaction(doc);
            ICollection <ElementId> newElementIds = ElementTransformUtils.CopyElements(sourceDoc, idCollection, doc, transform, copyOpts);

            TransactionManager.Instance.TransactionTaskDone();
            //create a new list for the new elements
            List <global::Revit.Elements.Element> newElements = new List <global::Revit.Elements.Element>();

            //gets the new elements
            foreach (ElementId id in newElementIds)
            {
                newElements.Add(doc.GetElement(id).ToDSType(true));
            }

            return(newElements);
        }
Esempio n. 3
0
        /*
        **
        ** Download
        **
        */

        public virtual HttpResponseMessage Get(Document entity, HttpRequestMessage Request, object adds, String extensionName = null, Client currentClient = null, int?idHome = null)
        {
            if (!((DocumentValidation)validation).DownloadValidation(validationDictionnary, currentClient, entity))
            {
                throw new ManahostValidationException(validationDictionnary);
            }
            if (extensionName != null)
            {
                entity.Url   = DocumentUtils.GetNewPathFileName(DocumentUtils.GetFullDocumentUrl(entity.Url), extensionName, true);
                entity.Title = Path.GetFileNameWithoutExtension(entity.Title) + "_" + extensionName + Path.GetExtension(entity.Title);
            }
            try
            {
                HttpResponseMessage response = new HttpResponseMessage();
                Stream result = DocumentUtils.GetDocumentStream((Boolean)entity.IsPrivate, entity.Url, DocumentUtils.GetEncryptionPassword(HomeRepository, currentClient));

                entity.MimeType     = DocumentUtils.GetMimeType(entity.Title);
                response.StatusCode = HttpStatusCode.OK;
                response.Content    = new StreamContent(result);
                response.Content.Headers.ContentType        = new MediaTypeHeaderValue(entity.MimeType);
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = entity.Title
                };
                return(response);
            }
            catch (IOException)
            {
                validationDictionnary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <Document>(), "Download"), GenericError.FILE_NOT_FOUND);
                throw new ManahostValidationException(validationDictionnary);
            }
        }
Esempio n. 4
0
        protected File PerformCrossDaoFileCopy(object fromFileId, object toFolderId, bool deleteSourceFile)
        {
            var fromSelector = GetSelector(fromFileId);
            var toSelector   = GetSelector(toFolderId);
            //Get File from first dao
            var fromFileDao = fromSelector.GetFileDao(fromFileId);
            var toFileDao   = toSelector.GetFileDao(toFolderId);

            var fromFile = fromFileDao.GetFile(fromSelector.ConvertId(fromFileId));

            fromFile.ID = fromSelector.ConvertId(fromFile.ID);
            using (var fromFileStream = fromFile.ConvertedType != null
                                            ? DocumentUtils.GetConvertedFile(fromFile).GetBuffered()
                                            : fromFileDao.GetFileStream(fromFile))
            {
                fromFile.ID       = null; //Reset id, so it can be created by apropriate provider
                fromFile.FolderID = toSelector.ConvertId(toFolderId);
                var toFile = toFileDao.SaveFile(fromFile, fromFileStream);

                if (deleteSourceFile)
                {
                    //Delete source file if needed
                    fromFileDao.DeleteFileStream(fromSelector.ConvertId(fromFileId));
                    fromFileDao.DeleteFile(fromSelector.ConvertId(fromFileId));
                }
                return(toFile);
            }
        }
Esempio n. 5
0
        public override void OnProcessRequest(HttpContext context)
        {
            var action = context.Request[UrlConstant.Action].ToLower();

            var securityActions = new[] { "upload", "view", "download", "bulk", "save" };
            var publicActions   = new[] { "download", "view", "bulk" };

            if (securityActions.Contains(action) && !SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                if (publicActions.Contains(action) && string.IsNullOrEmpty(context.Request[UrlConstant.DocUrlKey]))
                {
                    if (!CoreContext.TenantManager.GetCurrentTenant().Public)
                    {
                        context.Response.Redirect("~/auth.aspx");
                        return;
                    }
                }
                else
                {
                    if (DocumentUtils.ParseShareLink(context.Request[UrlConstant.DocUrlKey]) == null)
                    {
                        throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                    }
                }
            }

            switch (action)
            {
            case "upload":
                UploadFile(context);
                break;

            case "view":
                DownloadFile(context, true);
                break;

            case "download":
                DownloadFile(context, false);
                break;

            case "bulk":
                BulkDownloadFile(context);
                break;

            case "save":
                SaveFile(context);
                break;

            case "stream":
                StreamFile(context);
                break;

            case "create":
                CreateFile(context);
                break;

            default:
                throw new InvalidOperationException();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// This node will open the given file in the background.
        /// </summary>
        /// <param name="filePath">The file to obtain document from.</param>
        /// <param name="audit">Choose whether or not to audit the file upon opening. (Will run slower with this)</param>
        /// <param name="detachFromCentral">Choose whether or not to detach from central upon opening. Only for RVT files. </param>
        /// <returns name="document">The document object. Primarily for use with other Rhythm nodes.</returns>
        /// <search>
        /// Application.OpenDocumentFile, rhythm
        /// </search>
        public static string OpenDocumentFile(string filePath, bool audit = false, bool detachFromCentral = false)
        {
            var      uiapp = DocumentManager.Instance.CurrentUIApplication;
            var      app   = uiapp.Application;
            Document doc;
            string   docTitle = string.Empty;
            //instantiate open options for user to pick to audit or not
            OpenOptions openOpts = new OpenOptions();

            openOpts.Audit = audit;
            TransmittedModelOptions tOpt = TransmittedModelOptions.SaveAsNewCentral;

            if (detachFromCentral == false)
            {
                openOpts.DetachFromCentralOption = DetachFromCentralOption.DoNotDetach;
            }
            else
            {
                openOpts.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
            }

            //convert string to model path for open
            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            try
            {
                docTitle = DocumentUtils.OpenDocument(modelPath, openOpts);
            }
            catch (Exception)
            {
                //nothing
            }

            return(docTitle);
        }
Esempio n. 7
0
        /// <summary>
        /// This node provides access to all of the open documents in revit.
        /// </summary>
        /// <param name="runIt">Do you want to save?</param>
        /// <returns name="documents">The documents that are currently open.</returns>
        public static List <string> GetOpenDocuments(bool runIt)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;

            List <string> docNames = new List <string>();

            var uiApp = DocumentManager.Instance.CurrentUIApplication;
            var app   = uiApp.Application;

            foreach (Document d in app.Documents)
            {
                if (d.Title != doc.Title)
                {
                    try
                    {
                        docNames.Add(DocumentUtils.ConvertDocument(doc));
                    }
                    catch (Exception)
                    {
                        //nothing
                    }
                }
            }

            return(docNames);
        }
        public async Task ドキュメント作成のイベントが登録される()
        {
            var document = DocumentUtils.Create("path1/content1.txt", "testdata");
            var ev       = document.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev as DocumentCreatedEvent));

            Assert.AreEqual(1, await ctx.DocumentHistories.Where(f => f.Path == "path1/content1.txt" && f.Discriminator == DocumentHistoryDiscriminator.DocumentCreated).CountAsync());
        }
Esempio n. 9
0
        public async Task Initialize()
        {
            _driver = WebDriverUtils.InitializeChromeDriver();
            _client = new DocmsApiClient("docms-client", Constants.TestUrlBase);
            await DocumentUtils.ClearAllAsync(_client.CreateDocumentClient()).ConfigureAwait(false);

            WebDriverUtils.LoginAsAdmin(_driver);
        }
Esempio n. 10
0
        private void BatchVerifierThreadCallBack()
        {
            bool isRevisionsEnabled = false;

            try
            {
                // Check if revisions are visible, if so make them invisible and turn them back on in the end
                isRevisionsEnabled = DocumentUtils.IsRevisionsEnabled(m_verifier.Document);
                if (isRevisionsEnabled)
                {
                    DocumentUtils.ChangeShowingRevisions(m_verifier.Document, false);
                }

                int docPageCount = -1;
                foreach (RangeWrapper par in RangeWrapper.ReadParagraphs(m_verifier.Document))
                {
                    if (m_cancelationPending)
                    {
                        break;
                    }

                    if (docPageCount <= 0)
                    {
                        docPageCount = par.NumberOfPagesInDocument;
                    }

                    int curPage = par.PageNumber;

                    if (curPage > 0 && docPageCount > 0)
                    {
                        ShowPageNumberProgress(curPage, docPageCount);
                    }
                    //System.Diagnostics.Debug.WriteLine("Page: " + curPage + " of " + docPageCount);

                    SendParagraphForVerification(par);

                    if (m_cancelationPending)
                    {
                        break;
                    }
                } // end of foreach par
            }
            finally
            {
                // Check if revisions are visible, if so make them invisible and turn them back on in the end
                if (isRevisionsEnabled)
                {
                    DocumentUtils.ChangeShowingRevisions(m_verifier.Document, true);
                }

                m_eventVerifierThreadStoped.Set();
            }

            if (!m_isFormClosed)
            {
                StopThreadsAndClose();
            }
        }
        public async Task ドメインイベントから読み取りモデルのファイルを追加する()
        {
            var document = DocumentUtils.Create("path1/content1.txt", "Hello");
            var ev       = document.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev as DocumentCreatedEvent));

            Assert.IsTrue(await ctx.Blobs.AnyAsync(f => f.Path == "path1/content1.txt"));
            Assert.IsTrue(await ctx.BlobContainers.AnyAsync(f => f.Path == "path1"));
        }
Esempio n. 12
0
        /*
        **
        ** Upload
        **
        */

        public virtual HttpResponseMessage UploadFile(Client currentClient, Document entity, HttpRequestMessage Request, IHomeRepository homeRepo, IDocumentLogRepository logRepo)
        {
            MyMultipartFileStreamProvider provider;
            Boolean isImage = false;

            ValidateNull(entity);
            if (entity != null && ((IDocumentRepository)repo).GetDocumentById(entity.Id, currentClient.Id) == null)
            {
                validationDictionnary.AddModelError(TypeOfName.GetNameFromType <Document>(), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
            }
            if (!((DocumentValidation)validation).UploadValidationBeforeProvider(validationDictionnary, currentClient, entity, Request))
            {
                throw new ManahostValidationException(validationDictionnary);
            }
            provider = new MyMultipartFileStreamProvider(ManahostUploadFileSystem.GetUploadFolderPath(WebApiApplication.UPLOAD_FOLDER_ROOT, currentClient.Id, (Boolean)entity.IsPrivate));
            try
            {
                IEnumerable <HttpContent> parts = null;
                Task.Factory.StartNew(() => parts = Request.Content.ReadAsMultipartAsync(provider).Result.Contents,
                                      CancellationToken.None,
                                      TaskCreationOptions.LongRunning, // guarantees separate thread
                                      TaskScheduler.Default).Wait();
                MultipartFileData file = provider.FileData.First();

                if (!((DocumentValidation)validation).UploadValidationAfterProvider(validationDictionnary, currentClient, file))
                {
                    throw new ManahostValidationException(validationDictionnary);
                }
                if (isImage = ManahostUploadFileSystem.imageExtension.Any(s => entity.Title.EndsWith(s, StringComparison.OrdinalIgnoreCase)))
                {
                    ImageCompressAndThumbnail(file.LocalFileName);
                }
                if ((Boolean)entity.IsPrivate && currentClient != null)
                {
                    EncryptFileOnUpload(file.LocalFileName, DocumentUtils.GetEncryptionPassword(homeRepo, currentClient), isImage);
                }
                if (!UpdateEntitiesOnUpload(currentClient, entity, file.LocalFileName, isImage, logRepo))
                {
                    throw new ManahostValidationException(validationDictionnary);
                }
            }
            catch (Exception e)
            {
                if (validationDictionnary.IsValid)
                {
                    validationDictionnary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <Document>(), "Upload"), GenericError.INVALID_GIVEN_PARAMETER);
                }
                if (entity.Url != null)
                {
                    DocumentUtils.DeleteAllFile(entity.Url, isImage);
                }
                repo.Delete(entity);
                repo.Save();
                throw new ManahostValidationException(validationDictionnary, e.StackTrace);
            }
            return(BuildStringContent.BuildFromRequestOK(Request));
        }
Esempio n. 13
0
 private static void CreateFile(string folderid, string title, string content, string contentType, string extension)
 {
     using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
     {
         DocumentUtils.UploadFile(folderid,
                                  title.EndsWith(extension, StringComparison.OrdinalIgnoreCase) ? title : (title + extension),
                                  memStream.Length, contentType, memStream);
     }
 }
Esempio n. 14
0
        public static List <System.Net.Mail.Attachment> GetAttachments(List <Document> attachmentList, Home currentHome)
        {
            List <System.Net.Mail.Attachment> attachments = new List <System.Net.Mail.Attachment>();

            foreach (Document cur in attachmentList)
            {
                attachments.Add(new Attachment(DocumentUtils.GetDocumentStream((bool)cur.IsPrivate, (string)cur.Url, currentHome.EncryptionPassword), (string)cur.Title));
            }
            return(attachments);
        }
Esempio n. 15
0
        public async Task ルート直下のサブディレクトリをディレクトリとして認識すること()
        {
            var ctx = new MockDocmsContext("DocumentsRepositoryTests");
            var sut = new DocumentRepository(ctx);
            await sut.AddAsync(DocumentUtils.Create("dir1/test.txt", "Hello, world"));

            await sut.UnitOfWork.SaveEntitiesAsync();

            Assert.IsTrue(await sut.IsContainerPath("dir1"));
        }
Esempio n. 16
0
        public async Task コマンドを発行してドキュメントが削除されること()
        {
            await repository.AddAsync(DocumentUtils.Create("test1/document1.txt", "Hello, World"));

            await sut.Handle(new DeleteDocumentCommand()
            {
                Path = new FilePath("test1/document1.txt"),
            });

            Assert.IsNull(await repository.GetAsync("test1/document1.txt"));
        }
Esempio n. 17
0
        public override void ExtendedOneTimeSetUp()
        {
            driver.Navigate().GoToUrl("http://www.i.ua/");
            StartPage        startPage        = new StartPage(driver);
            EmailBox         emailBox         = startPage.Login();
            CreateLetterPage createLetterPage = new CreateLetterPage(driver);

            emailBox.CreateLetter();
            createLetterPage.AttachmentButton.Click();
            createLetterPage.ChooseFileButton.Click();
            DocumentUtils.Upload(driver, @"C:\Users\Sofiya\Documents\Visual Studio 2017\Projects\DOCUMENT_UTILS\Upload\Doc_to_Upload.txt");
        }
Esempio n. 18
0
        public async Task コマンドを発行してファイルが移動すること()
        {
            await repository.AddAsync(DocumentUtils.Create("test1/document1.txt", "Hello, world"));

            await sut.Handle(new MoveDocumentCommand()
            {
                OriginalPath    = new FilePath("test1/document1.txt"),
                DestinationPath = new FilePath("test2/document2.txt"),
            });

            Assert.AreEqual("test2/document2.txt", repository.Entities.First().Path);
        }
Esempio n. 19
0
        protected override void DoDelete(Client currentClient, int id, object param)
        {
            if (orig != null && orig.Title != null)
            {
                Boolean isImage = ManahostUploadFileSystem.imageExtension.Any(s => orig.Title.EndsWith(s, StringComparison.OrdinalIgnoreCase));

                if (orig.Url != null)
                {
                    DocumentUtils.DeleteAllFile(orig.Url, isImage);
                }
            }
        }
Esempio n. 20
0
        public async Task DocumentがPathで取得できること()
        {
            var ctx = new MockDocmsContext("DocumentsRepositoryTests");
            var sut = new DocumentRepository(ctx);
            await sut.AddAsync(DocumentUtils.Create("dir1/test.txt", "Hello, world"));

            await sut.UnitOfWork.SaveEntitiesAsync();

            var document = await sut.GetAsync("dir1/test.txt");

            Assert.AreEqual("dir1/test.txt", document.Path);
        }
        public async Task すでに存在するディレクトリのパスに対して読み取りモデルのファイルを追加する()
        {
            var document1 = DocumentUtils.Create("path1/subpath1/content1.txt", "path1/subpath1/content1.txt");
            var ev1       = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev1 as DocumentCreatedEvent));

            var document2 = DocumentUtils.Create("path1/subpath1/content2.txt", "path1/subpath1/content2.txt");
            var ev2       = document2.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev2 as DocumentCreatedEvent));

            Assert.IsTrue(await ctx.Blobs.AnyAsync(f => f.Path == "path1/subpath1/content2.txt"));
        }
        public JsonResult Update(string language, string type, string documents)
        {
            ViewBag.DocumentLanguageList = DocumentUtils.GetDocumentLanguageList();
            ViewBag.DocumentTypeList     = DocumentUtils.GetDocumentTypeList();
            string json = JsonConvert.SerializeObject(documents);

            //write string to file
            string path = Server.MapPath(string.Format(json_file_path, language, type));

            System.IO.File.WriteAllText(path, string.Empty);
            System.IO.File.WriteAllText(path, documents);
            return(Json(documents));
        }
        public async Task ドキュメント削除のイベントが登録される()
        {
            var document1 = DocumentUtils.Create("path1/subpath1/document1.txt", "Hello, World");
            var ev1       = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev1 as DocumentCreatedEvent));

            document1.ClearDomainEvents();
            document1.Delete();
            var ev2 = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentDeletedEvent>(ev2 as DocumentDeletedEvent));

            Assert.AreEqual(1, await ctx.DocumentHistories.Where(f => f.Path == "path1/subpath1/document1.txt" && f.Discriminator == DocumentHistoryDiscriminator.DocumentCreated).CountAsync());
            Assert.AreEqual(1, await ctx.DocumentHistories.Where(f => f.Path == "path1/subpath1/document1.txt" && f.Discriminator == DocumentHistoryDiscriminator.DocumentDeleted).CountAsync());
        }
Esempio n. 24
0
        private void ImageCompressAndThumbnail(String pathImage)
        {
            Image image = Image.FromFile(pathImage);

            foreach (ImageFormat format in ImagesFormats)
            {
                if (image.Height > format.Height || image.Width > format.Width)
                {
                    using (Image newQualityImage = DocumentUtils.ResizeImage(image, format.Width, format.Height))
                        newQualityImage.Save(DocumentUtils.GetNewPathFileName(pathImage, format.Name));
                }
            }
            image.Dispose();
        }
        public async Task ドキュメント更新のイベントが登録される()
        {
            var document1 = DocumentUtils.Create("path1/subpath1/content1.txt", "Hello, World");
            var ev1       = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev1 as DocumentCreatedEvent));

            document1.ClearDomainEvents();
            document1.Update("application/json", InMemoryData.Create("storagekey2", Encoding.UTF8.GetBytes("Hello, New World")));
            var ev2 = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentUpdatedEvent>(ev2 as DocumentUpdatedEvent));

            Assert.AreEqual(1, await ctx.DocumentHistories.Where(f => f.Path == "path1/subpath1/content1.txt" && f.Discriminator == DocumentHistoryDiscriminator.DocumentCreated).CountAsync());
            Assert.AreEqual(1, await ctx.DocumentHistories.Where(f => f.Path == "path1/subpath1/content1.txt" && f.Discriminator == DocumentHistoryDiscriminator.DocumentUpdated).CountAsync());
        }
        public async Task 親Containerに1件のみファイルが存在するパスを削除してDocumentとContainerが削除される()
        {
            var document1 = DocumentUtils.Create("path1/subpath1/content1.txt", "path1/subpath1/content1.txt");
            var ev1       = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev1 as DocumentCreatedEvent));

            document1.ClearDomainEvents();
            document1.Delete();
            var ev2 = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentDeletedEvent>(ev2 as DocumentDeletedEvent));

            Assert.IsFalse(await ctx.Blobs.AnyAsync(f => f.Path == "path1/subpath1/document1.txt"));
            Assert.IsFalse(await ctx.BlobContainers.AnyAsync(f => f.Path == "path1/subpath1"));
        }
Esempio n. 27
0
 private void EncryptFileOnUpload(String pathFile, String encryptionKey, Boolean isImage)
 {
     AES256.EncryptFile(pathFile, encryptionKey);
     if (isImage)
     {
         foreach (ImageFormat format in ImagesFormats)
         {
             String pathFileWithExtension = DocumentUtils.GetNewPathFileName(pathFile, format.Name);
             if (File.Exists(pathFileWithExtension))
             {
                 AES256.EncryptFile(pathFileWithExtension, encryptionKey);
             }
         }
     }
 }
Esempio n. 28
0
        public async Task コマンドを発行してドキュメントが更新されること()
        {
            await repository.AddAsync(DocumentUtils.Create("test1/document1.txt", "Hello, world"));

            await sut.Handle(new CreateOrUpdateDocumentCommand()
            {
                Path = new FilePath("test1/document1.txt"),
                Data = await dataStore.CreateAsync(Encoding.UTF8.GetBytes("Hello, new world")).ConfigureAwait(false)
            });

            var document = repository.Entities.Single();

            Assert.AreEqual("test1/document1.txt", document.Path.ToString());
            Assert.AreEqual("Hello, new world", await ReadTextAsync(document.StorageKey));
        }
        public async Task ファイルが更新された場合正しく更新されること()
        {
            var document1 = DocumentUtils.Create("path1/subpath1/content1.txt", "path1/subpath1/content1.txt");
            var ev1       = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentCreatedEvent>(ev1 as DocumentCreatedEvent));

            var bytes2 = Encoding.UTF8.GetBytes("path1/subpath1/content1.txt updated");

            document1.ClearDomainEvents();
            document1.Update("application/json", InMemoryData.Create("storagekey2", bytes2));
            var ev2 = document1.DomainEvents.First();
            await sut.Handle(new DomainEventNotification <DocumentUpdatedEvent>(ev2 as DocumentUpdatedEvent));

            Assert.AreEqual("application/json", (await ctx.Blobs.FirstAsync(f => f.Path == "path1/subpath1/content1.txt")).ContentType);
        }
Esempio n. 30
0
        private void ValidateData()
        {
            if (txtCNPJ.Text.Trim() == "")
            {
                MessageBox.Show("CNPJ/CPF do cliente é obrigatório", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                throw new Exception();
            }

            if (txtCNPJ.Text.Length == 11)
            {
                if (!DocumentUtils.IsCpf(txtCNPJ.Text))
                {
                    MessageBox.Show("CNPJ/CPF do cliente inválido", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new Exception();
                }
            }
            else if (txtCNPJ.Text.Length == 14)
            {
                if (!DocumentUtils.IsCnpj(txtCNPJ.Text))
                {
                    MessageBox.Show("CNPJ/CPF do cliente inválido", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new Exception();
                }
            }
            else
            {
                MessageBox.Show("CNPJ/CPF do cliente inválido", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                throw new Exception();
            }

            if (txtNome.Text.Trim() == "")
            {
                MessageBox.Show("Nome do cliente é obrigatório", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                throw new Exception();
            }

            if (txtTelefone.Text.Trim() == "")
            {
                MessageBox.Show("Telefone do cliente é obrigatório", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                throw new Exception();
            }

            if (!RegexUtilities.IsValidEmail(txtEmail.Text))
            {
                MessageBox.Show("Formato do e-mail é inválido", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                throw new Exception();
            }
        }