Beispiel #1
0
        public IActionResult SaveItem(string Id = null)
        {
            DocumentsModel data           = new DocumentsModel();
            string         ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            int            IdDC           = Int32.Parse(MyModels.Decode(Id, API.Models.Settings.SecretId + ControllerName).ToString());

            data.SearchData = new SearchDocuments()
            {
                CurrentPage = 0, ItemsPerPage = 10, Keyword = ""
            };
            data.ListDocumentsCategories = DocumentsCategoriesService.GetListSelectItems();
            data.ListDocumentsType       = DocumentsTypeService.GetListSelectItems();
            data.ListDocumentsField      = DocumentsFieldService.GetListSelectItems();
            data.ListDocumentsLevel      = DocumentsLevelService.GetListSelectItems();
            Documents Item = new Documents()
            {
                IssuedDateShow    = DateTime.Now.ToString("dd/MM/yyyy"),
                EffectiveDateShow = DateTime.Now.ToString("dd/MM/yyyy")
            };

            if (IdDC > 0)
            {
                Item = DocumentsService.GetItem(IdDC, API.Models.Settings.SecretId + ControllerName);
            }

            data.Item = Item;

            return(View(data));
        }
Beispiel #2
0
        public ActionResult UpdateStatus([FromQuery] string Ids, Boolean Status)
        {
            string    ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            Documents item           = new Documents()
            {
                Id = Int32.Parse(MyModels.Decode(Ids, API.Models.Settings.SecretId + ControllerName).ToString()), Status = Status
            };

            try
            {
                if (item.Id > 0)
                {
                    item.CreatedBy  = int.Parse(HttpContext.Request.Headers["Id"]);
                    item.ModifiedBy = int.Parse(HttpContext.Request.Headers["Id"]);
                    dynamic UpdateStatus = DocumentsService.UpdateStatus(item);
                    TempData["MessageSuccess"] = "Cập nhật Trạng Thái thành công";
                    return(Json(new MsgSuccess()));
                }
                else
                {
                    TempData["MessageError"] = "Cập nhật Trạng Thái Không thành công";
                    return(Json(new MsgError()));
                }
            }
            catch
            {
                TempData["MessageSuccess"] = "Cập nhật Trạng Thái không thành công";
                return(Json(new MsgError()));
            }
        }
Beispiel #3
0
    private void Start()
    {
        _currentDocuments    = new List <GameObject>();
        _characterGameObject = Instantiate(_characterPrefab);
        _characterAnimation  = _characterGameObject.GetComponent <Animation>();
        _charactersService   = new CharactersService(_visualPresets, _uniquePeople, _firstNames, _lastNames);
        _documentsService    = new DocumentsService(_documentPresets);
        _random        = new Random();
        CharacterState = CharacterState.Idle;
        MouseState     = MouseState.Idle;

        _backgroundAnimation = _backgroundGameObject.GetComponent <Animation>();

        _sceneryAnimation = _sceneryGameObject.GetComponent <Animation>();

        // Setup the rules
        var values  = Enum.GetValues(typeof(Country));
        var country = (Country)values.GetValue(_random.Next(values.Length));

        _privilegedCountry  = country;
        _minimumDateOfBirth = new DateTime(1993, 1, 1);

        // Write to the book
        _rulebookController.SetRules(_privilegedCountry, _minimumDateOfBirth);

        RandomCharacter();
    }
Beispiel #4
0
        public ActionResult DeleteItem(string Id)
        {
            string    ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            Documents model          = new Documents()
            {
                Id = Int32.Parse(MyModels.Decode(Id, API.Models.Settings.SecretId + ControllerName).ToString())
            };

            try
            {
                if (model.Id > 0)
                {
                    model.CreatedBy  = int.Parse(HttpContext.Request.Headers["Id"]);
                    model.ModifiedBy = int.Parse(HttpContext.Request.Headers["Id"]);
                    DocumentsService.DeleteItem(model);
                    TempData["MessageSuccess"] = "Xóa thành công";
                    return(Json(new MsgSuccess()));
                }
                else
                {
                    TempData["MessageError"] = "Xóa Không thành công";
                    return(Json(new MsgError()));
                }
            }
            catch
            {
                TempData["MessageSuccess"] = "Xóa không thành công";
                return(Json(new MsgError()));
            }
        }
Beispiel #5
0
        public async Task Can_Edit_Document_From_Template_MetaData()
        {
            var dbContextOptions = CreateNewContextOptions();
            var user             = await CreateUser(dbContextOptions);

            await CreateTemplate(dbContextOptions, user.Id);

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var service = new DocumentsService(context);
                var items   = new Dictionary <int, string> {
                    [0] = "Item 3", [1] = "Item 4"
                };

                await service.EditDocument(1, user.Id, items);

                await context.SaveChangesAsync();
            }

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var states = await context.DocumentStates.ToListAsync();

                Assert.Equal(2, states.Count);

                var oldState = states.First();
                var newState = states.Last();

                Assert.NotEqual(oldState.IdDocumentData, newState.IdDocumentData);
            }
        }
Beispiel #6
0
        public IActionResult Index([FromQuery] SearchDocuments dto)
        {
            int            TotalItems     = 0;
            string         ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            DocumentsModel data           = new DocumentsModel()
            {
                SearchData = dto
            };

            data.SearchData.Status = 0;
            data.ListItems         = DocumentsService.GetListPagination(data.SearchData, API.Models.Settings.SecretId + ControllerName);
            if (data.ListItems != null && data.ListItems.Count() > 0)
            {
                TotalItems = data.ListItems[0].TotalRows;
            }
            data.Pagination = new Areas.Admin.Models.Partial.PartialPagination()
            {
                CurrentPage = data.SearchData.CurrentPage, ItemsPerPage = data.SearchData.ItemsPerPage, TotalItems = TotalItems, QueryString = Request.QueryString.ToString()
            };
            data.ListDocumentsCategories = DocumentsCategoriesService.GetListSelectItems();
            data.ListDocumentsType       = DocumentsTypeService.GetListSelectItems();
            data.ListDocumentsField      = DocumentsFieldService.GetListSelectItems();
            data.ListDocumentsLevel      = DocumentsLevelService.GetListSelectItems();
            return(View(data));
        }
        private async void SaveFolder_Tapped(object sender, EventArgs e)
        {
            viewModel.VisibleLoad    = true;
            viewModel.LoadingMessage = "";

            Folder folder = new Folder();

            folder.Name             = txtName.Text;
            folder.ItemContainer_Id = containerId;
            ApiSaveResponse resp = await DocumentsService.AddFolder(folder);

            if (!resp.HasErrors)
            {
                MessagingCenter.Send(this, "FolderAdded", Guid.Empty);

                //for (var counter = 1; counter < 2; counter++)
                Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]);

                await Navigation.PopAsync();
            }
            else
            {
                Common.Instance.ShowToastMessage("Error creating new folder. Please try again", DoubleResources.DangerSnackBar);
            }
            viewModel.VisibleLoad = false;
        }
        static void Main(string[] args)
        {
            DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");
            // TODO: Instantiate an Authenticator object according to your authentication
            // mechanism (e.g. OAuth2Authenticator).
            // Authenticator authenticator =  ...
            // Instantiate a DocumentEntry object to be inserted.
            DocumentEntry entry = new DocumentEntry();

            // Set the document title
            entry.Title.Text = "Legal Contract";
            // Set the media source
            entry.MediaSource = new MediaFileSource("c:\\contract.txt", "text/plain");
            // Define the resumable upload link
            Uri      createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full");
            AtomLink link            = new AtomLink(createUploadUrl.AbsoluteUri);

            link.Rel = ResumableUploader.CreateMediaRelation;
            entry.Links.Add(link);
            // Set the service to be used to parse the returned entry
            entry.Service = service;
            // Instantiate the ResumableUploader component.
            ResumableUploader uploader = new ResumableUploader();

            // Set the handlers for the completion and progress events
            uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnDone);
            uploader.AsyncOperationProgress  += new AsyncOperationProgressEventHandler(OnProgress);
            // Start the upload process
            uploader.InsertAsync(authenticator, entry, new object());
        }
Beispiel #9
0
        /// <summary>
        /// Fetches list of documents in Google Drive.
        /// </summary>
        /// <returns></returns>
        public static DocumentsFeed GetGDriveDocList()
        {
            //Waiting for the service authentication to complete.
            _autoEvent.WaitOne();
            DocumentsFeed documents = null;

            try
            {
                //In case an error was encountered go back.
                if (_parameters == null || _exception != null)
                {
                    return(documents);
                }
                //Creating the request factory for the Drive service.
                GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, APPLICATION_NAME, _parameters);
                //Creating a service instance.
                DocumentsService service = new DocumentsService(APPLICATION_NAME);
                //Assigning the factory instance to the service.
                service.RequestFactory = requestFactory;
                DocumentsListQuery query = new DocumentsListQuery();
                //Sending a query to the service to fetch list of all documents on the drive.
                documents = service.Query(query);
            }
            catch (Exception Ex)
            {
                _exception = Ex;
            }
            finally
            {
                //Can now signal other threads to continue accessing/refreshing services.
                _autoEvent.Set();
            }
            return(documents);
        }
Beispiel #10
0
        public void GetSessionsStatistic_GoodCase_ReturnsCorrectStatistic()
        {
            var trainingDate = new DateTime(2021, 3, 1);
            var session      = new TrainingSession
            {
                Simulator = SimulatorName,
                StartDate = trainingDate,
                StartTime = new TimeSpan(8, 0, 0),
                EndDate   = trainingDate,
                EndTime   = new TimeSpan(12, 0, 0)
            };
            var simulators = new List <string> {
                SimulatorName
            };
            const string expectedSessionTime = "04:00";
            var          expectedStatistic   = new StatisticTableRow
            {
                Simulator        = SimulatorName,
                NumberOfSessions = 1,
                PlannedTime      = expectedSessionTime,
                AchievedTime     = expectedSessionTime
            };
            var docWriterMock    = new Mock <IDocumentsWriter>();
            var documentsService = new DocumentsService(docWriterMock.Object);

            var statistic = documentsService.GetSessionsStatistic(new[] { session }, simulators).ToArray();

            Assert.AreEqual(1, statistic.Length);
            Assert.AreEqual(expectedStatistic, statistic[0]);
        }
Beispiel #11
0
        /// <summary>
        /// Will clear the headers before any given request against GData API, and insert potential ETag's.
        /// Will also setup the proxy and services if they aren't initialized yet.
        /// </summary>
        /// <param name="userName">Username for Google services.</param>
        /// <param name="password">Password for Google services.</param>
        /// <param name="protocolMajor">ProtocolMajor to be used.</param>
        /// <param name="eTagType">If-Match / If-None-Match etc.</param>
        /// <param name="eTag">The actual ETag to be checked.</param>
        private static void SetupService(string userName, string password, int protocolMajor, string eTagType, string eTag)
        {
            // let's create our service if it's not already created
            if (_documentService == null)
            {
                _documentService = new DocumentsService("Nocs");
            }

            _documentService.ProtocolMajor = protocolMajor;
            var reqFactory = (GDataGAuthRequestFactory)_documentService.RequestFactory;

            reqFactory.ProtocolMajor = protocolMajor;
            reqFactory.KeepAlive     = false;

            // let's first clear all customHeaders regardless
            reqFactory.CustomHeaders.Clear();
            if (!string.IsNullOrEmpty(eTagType) && !string.IsNullOrEmpty(eTag))
            {
                reqFactory.CustomHeaders.Add(string.Format("{0}: {1}", eTagType, eTag));
            }

            // let's also set up the request settings for API v3.0 requests
            if (_settings == null)
            {
                _settings = new RequestSettings("Nocs", userName, password)
                {
                    AutoPaging = true
                };
            }

            // finally let's setup a potential proxy
            reqFactory.Proxy = GetProxy();
        }
        public void CreateTemplate()
        {
            DocumentsService service = new DocumentsService(applicationName);

            DocumentEntry entry = new DocumentEntry();

            // Set the document title
            entry.Title.Text    = spreadsheetName;
            entry.IsSpreadsheet = true;

            // Set the media source
            entry.MediaSource = new MediaFileSource(GetStreamWithTemplate(), applicationName, "text/csv");

            // Define the resumable upload link
            Uri      createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full");
            AtomLink link            = new AtomLink(createUploadUrl.AbsoluteUri);

            link.Rel = ResumableUploader.CreateMediaRelation;
            entry.Links.Add(link);

            // Set the service to be used to parse the returned entry
            entry.Service = service;

            // Instantiate the ResumableUploader component.
            ResumableUploader uploader = new ResumableUploader();


            // Start the upload process
            uploader.Insert(new ClientLoginAuthenticator(applicationName, ServiceNames.Documents, userName, password), entry);
        }
Beispiel #13
0
        private async Task <DocumentTemplate> CreateTemplate(DbContextOptions <ApplicationDbContext> dbContextOptions, string userId)
        {
            var template = new DocumentTemplate
            {
                DocumentTemplateItems = new List <DocumentTemplateItem>
                {
                    new DocumentTemplateItem(), new DocumentTemplateItem()
                }
            };

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                context.DocumentTemplates.Add(template);
                await context.SaveChangesAsync();
            }

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var service = new DocumentsService(context);

                var items = new Dictionary <int, string> {
                    [0] = "Item 1", [1] = "Item 2"
                };
                await service.AddDocumentFromTemplate(userId, template.IdDocumentTemplate, "Document Name", "Abstract", new List <string> {
                    "tag1", "tag2"
                }, items);

                await context.SaveChangesAsync();
            }

            return(template);
        }
Beispiel #14
0
 public void Login(string username, string password)
 {
     if (loggedIn)
     {
         throw new ApplicationException("Already logged in.");
     }
     try
     {
         service = new DocumentsService("DocListUploader");
         ((GDataRequestFactory)service.RequestFactory).KeepAlive = false;
         if (!string.IsNullOrEmpty(hapConfig.Current.ProxyServer.Address) && hapConfig.Current.ProxyServer.Enabled)
         {
             ((GDataRequestFactory)service.RequestFactory).Proxy = new WebProxy(hapConfig.Current.ProxyServer.Address, hapConfig.Current.ProxyServer.Port);
         }
         service.setUserCredentials(username, password);
         //force the service to authenticate
         DocumentsListQuery query = new DocumentsListQuery();
         query.NumberToRetrieve = 1;
         service.Query(query);
         loggedIn = true;
     }
     catch (AuthenticationException e)
     {
         loggedIn = false;
         service  = null;
         throw e;
     }
 }
        public async void GetSecureAssetByDocumentId_ShouldNotReturnDocument_IfGroupDoesNotReferenceAsset()
        {
            // Arrange
            var document = new DocumentBuilder().Build();

            _mockDocumentRepository.Setup(o => o.Get(It.IsAny <string>()))
            .ReturnsAsync((Asset)null);

            _mockGroupAdvisorRepository.Setup(o => o.CheckIfUserHasAccessToGroupBySlug(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(true);

            _mockGroupRepository.Setup(o => o.GetGroup(It.IsAny <string>(), It.IsAny <bool>()))
            .ReturnsAsync(HttpResponse.Successful(new GroupBuilder().AdditionalDocuments(new List <Document>()).Build()));

            _mockDocumentFactory.Setup(o => o.ToModel(It.IsAny <Asset>())).Returns(document);

            _mockContentfulConfigBuilder.Setup(o => o.Build(It.IsAny <string>())).Returns(new ContentfulConfig("", "", ""));

            _mockLoggedInHelper.Setup(o => o.GetLoggedInPerson()).Returns(new LoggedInPerson()
            {
                Email = "email",
                Name  = "name"
            });

            var documentsService = new DocumentsService(_mockDocumentRepositoryFunc.Object, _mockGroupAdvisorRepositoryFunc.Object, _mockGroupRepositoryFunc.Object, _mockDocumentFactory.Object, _mockContentfulConfigBuilder.Object, _mockLoggedInHelper.Object);

            // Act
            var result = await documentsService.GetSecureDocumentByAssetId("stockportgov", "asset id", "slug");

            // Assert
            result.Should().BeNull();
        }
        public void DeleteDocumentById_ShouldReturnExceptionUserPemissionDeniedDocAccessTypeIdDeptMismatch()
        {
            #region Arrange

            var  docId           = 1;
            bool exceptionCaught = false;

            MRMUser testMRMUser = new MRMUser()
            {
                Id           = 1,
                FirstName    = "TestFirst",
                LastName     = "TestLast",
                DepartmentId = 19//Finance
            };

            DocumentAccessType testDocAccessType = new DocumentAccessType()
            {
                Code = Constants.DocumentAccessType.Department,
                Name = "Department"
            };

            Document testDocument = new Document()
            {
                Id   = 1,
                Name = "TestDocumentName",
                OthersCanDeleteFlag  = true,
                DocumentAccessTypeId = 1,  //Department
                DepartmentId         = 84, //MRM Team
                DeliverableId        = 1,
                FileName             = "TestFileName",
                Description          = "TestDescription",
                IsActiveFlag         = true,
                OwnerMRMUserId       = 99,
                DocumentAccessType   = testDocAccessType
            };

            mockUserRepository.Setup(user => user.GetById(It.IsAny <int>())).Returns((MRMUser)null);
            mockDocumentRepository.Setup(doc => doc.GetSingle(It.IsAny <Expression <Func <Document, bool> > >())).Returns(
                (Expression <Func <Document, bool> > expr) => testDocument);
            #endregion

            #region Act
            try
            {
                var docService = new DocumentsService(mockUnitOfWork.Object, null, mockDocumentRepository.Object, mockUserRepository.Object,
                                                      mockDocumentAccessTypeRepository.Object, mockMRMUserRepository.Object, mockDeliverableDocumentRepository.Object, mockContractRequestMasterVendorDocumentRepository.Object);

                docService.DeleteDocumentById(docId);
            }
            catch
            {
                exceptionCaught = true;
            }

            #endregion


            //Assert
            Assert.IsTrue(exceptionCaught);
        }
Beispiel #17
0
        public User Login(string login, string password)
        {
            try
            {
                var service = new DocumentsService("Idea Provider");
                ((GDataRequestFactory)service.RequestFactory).KeepAlive = false;
                service.setUserCredentials(login, password);
                //force the service to authenticate
                DocumentsListQuery query = new DocumentsListQuery();
                query.NumberToRetrieve = 1;
                service.Query(query);

                Service = service;
                _user   = new User
                {
                    Email    = login,
                    Login    = login,
                    Password = password
                };
                return(_user);
            }
            catch (AuthenticationException)
            {
                return(null);
            }
        }
Beispiel #18
0
        public DocumentsServiceTest()
        {
            _unitOfWorkMock          = new Mock <IUnitOfWork>();
            _documentsRepositoryMock = new Mock <IDocumentsRepository>();

            _documentsService = new DocumentsService(_unitOfWorkMock.Object, _documentsRepositoryMock.Object);
        }
Beispiel #19
0
        private bool SendFile(string uriUpload, string htmlBuf)
        {
            try
            {
                Uri uri = new Uri(uriUpload);
                Console.WriteLine("uri in send: " + uri);
                string[]         token        = uri.UserInfo.Split(':');
                string           filename     = "Report Floading " + DateTime.Now.ToString("dd-MM-yyyy hh.ss") + ".html";
                string           fullPathName = StorageManager.getEnvValue("wrDirectory") + filename;
                DocumentsService service      = new DocumentsService("Floading report");
                Console.WriteLine("token[0] in send: " + token[0] + " token[1] in send: " + token[1]);
                service.setUserCredentials(token[0], token[1]);
                FileStream stream    = new FileStream(fullPathName, FileMode.CreateNew, FileAccess.Write);
                byte[]     htmlBytes = new System.Text.ASCIIEncoding().GetBytes(htmlBuf);
                stream.Write(htmlBytes, 0, htmlBytes.Length);
                stream.Close();
                DocumentsListQuery query = new DocumentsListQuery();
                DocumentsFeed      feed  = service.Query(query);

                DocumentEntry newEntry = service.UploadDocument(fullPathName, filename);

                File.Delete(fullPathName);
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Beispiel #20
0
        public DocumentsServiceTest()
        {
            _documentRepositoryMock = new Mock <IDocumentRepository>();
            _documentsService       = new DocumentsService(_documentRepositoryMock.Object);

            _documents = new List <Document>
            {
                new Document
                {
                    Id           = Guid.NewGuid(),
                    CandidateId  = Guid.NewGuid(),
                    Filename     = "MyCV.pdf",
                    DocumentType = DocumentType.BusinessPlan,
                    ReviewerId   = Guid.NewGuid()
                },
                new Document
                {
                    Id           = Guid.NewGuid(),
                    CandidateId  = Guid.NewGuid(),
                    Filename     = "MyDoc.docx",
                    DocumentType = DocumentType.License
                },
                new Document
                {
                    Id           = Guid.NewGuid(),
                    CandidateId  = Guid.NewGuid(),
                    Filename     = "TestPdf.pdf",
                    DocumentType = DocumentType.Other
                }
            };
        }
        public async void GetSecureDocument_ShouldCallDocumentsRepository()
        {
            // Arrange
            var mockDocumentsRepository = new Mock <IDocumentsRepository>();
            var mockHttpClientWrapper   = new Mock <IHttpClientWrapper>();
            var logger   = new Mock <ILogger <DocumentsService> >();
            var document = new DocumentBuilder().Build();
            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 })
            };

            var documentsService = new DocumentsService(mockDocumentsRepository.Object, mockHttpClientWrapper.Object, logger.Object);

            // Mock
            mockDocumentsRepository.Setup(o => o.GetSecureDocument("asset id", "group-slug")).ReturnsAsync(document);
            mockHttpClientWrapper.Setup(o => o.GetAsync(It.IsAny <string>())).ReturnsAsync(response);

            // Act
            var documentResponse = await documentsService.GetSecureDocument("asset id", "group-slug");

            // Assert
            mockDocumentsRepository.Verify(o => o.GetSecureDocument(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            documentResponse.Should().NotBeNull();
            documentResponse.MediaType.Should().Be(document.MediaType);
            documentResponse.FileData.Should().BeAssignableTo(typeof(byte[]));
        }
Beispiel #22
0
 public DocsAPI(string username, string password)
 {
     m_service  = new DocumentsService(APP_NAME);
     m_username = username;
     m_password = password;
     m_service.setUserCredentials(username, password);
 }
Beispiel #23
0
        public async Task Can_Add_Document_New_Version()
        {
            var dbContextOptions = CreateNewContextOptions();
            var user             = await CreateUserWithDocument(dbContextOptions);

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var service = new DocumentsService(context);

                await service.AddDocumentNewVersion(user.Id, 1, new byte[] { 2, 3, 4 });

                await context.SaveChangesAsync();
            }

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var states = await context.DocumentStates.ToListAsync();

                Assert.Equal(2, states.Count);

                var oldState = states.First();
                var newState = states.Last();

                Assert.Equal(0.02, newState.Version);
                Assert.NotEqual(oldState.IdDocumentData, newState.IdDocumentData);
            }
        }
Beispiel #24
0
        public async Task Can_Change_Document_Status()
        {
            var dbContextOptions = CreateNewContextOptions();

            await CreateUserWithDocument(dbContextOptions);

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var service = new DocumentsService(context);

                await service.ChangeStatus(1, DocumentStatus.Final);

                await context.SaveChangesAsync();
            }

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var document = await context.Documents.Include(it => it.DocumentStates).FirstAsync();

                Assert.Equal(2, document.DocumentStates.Count);

                var states = await context.DocumentStates.ToListAsync();

                var oldState = states.First();
                var newState = states.Last();

                Assert.Equal(1, newState.Version);
                Assert.NotEqual(oldState.StatusDate, newState.StatusDate);
                Assert.Equal(DocumentStatus.Final, newState.DocumentStatus);
                Assert.Equal(oldState.IdDocumentData, newState.IdDocumentData);
            }
        }
Beispiel #25
0
        public DocumentsService GetDocumentsService()
        {
            DocumentsService service = new DocumentsService("code.google.com/p/exult/");

            service.Credentials = GetDataCredentials();
            return(service);
        }
Beispiel #26
0
        public void Documents()
        {
            var service = new DocumentsService(_Client);

            var bankAccountsResourceTokens = new[]
            {
                "5E64B2E0B0D4AE42A3F2981CC4055CF613F6C17B5C2912029C587581E72ECDB8", // Pessoa Física - Document: 90564489603 - Id: dac_2585CBF0E2A23649
                "F3FEB619853E74753853E0BBFC1A6CBF53189A3F8059035877C136641897AAB9"  // Pessoa Jurídica - Document: 78338726311040 - Id: dac_591251E5D47F08AE
            };

            foreach (var resourceToken in bankAccountsResourceTokens)
            {
                //
                // Lista dos documentos

                var documents = service.ListDocuments(resourceToken);

                Assert.IsNotNull(documents);
                Assert.IsNotNull(documents.Embedded);
                Assert.IsNotNull(documents.Embedded.Documents);
                Assert.IsTrue(documents.Embedded.Documents.Count > 0);

                foreach (var document in documents.Embedded.Documents)
                {
                    //
                    // Consulta os documentos de forma individual

                    var tempDocument = service.GetDocument(resourceToken, document.Id);

                    Assert.IsNotNull(tempDocument);
                    Assert.AreEqual(tempDocument.Id, document.Id);

                    //
                    // Envia os documentos

                    if (tempDocument.ApprovalStatus == DocumentStatus.AWAITING || tempDocument.ApprovalStatus == DocumentStatus.REJECTED)
                    {
                        var filePost = new Models.Requests.PostDocumentResource
                        {
                            ResourceToken = resourceToken,
                            DocumentId    = tempDocument.Id,
                            Files         = new List <FileData>
                            {
                                new FileData
                                {
                                    Name     = $"{tempDocument.Type}_{Guid.NewGuid().ToString().Split("-")[0].ToUpper()}.pdf",
                                    Contents = File.ReadAllBytes($@"{Environment.CurrentDirectory}\..\..\..\files\{tempDocument.Type}.pdf")
                                }
                            }
                        };

                        var postResult = service.PostDocument(filePost);

                        Assert.IsNotNull(postResult);
                        Assert.AreEqual(postResult.Type, tempDocument.Type);
                    }
                }
            }
        }
        public async void GetSecureAssetByDocumentId_ShouldNotReturnDocument_ToUnauthorisedUser()
        {
            // Arrange
            var expectedResult = new DocumentBuilder().Build();

            _mockDocumentRepository.Setup(o => o.Get(It.IsAny <string>()))
            .ReturnsAsync(new Asset()
            {
                Description          = "description",
                DescriptionLocalized = new Dictionary <string, string> {
                    { "en-GB", "description" }
                },
                File = new File()
                {
                    Url     = "url",
                    Details = new FileDetails()
                    {
                        Size = 22
                    }
                },
                FilesLocalized = new Dictionary <string, File> {
                    { "en-GB", new File() }
                },
                SystemProperties = new SystemProperties()
                {
                    Id = "asset id"
                },
                Title          = "title",
                TitleLocalized = new Dictionary <string, string> {
                    { "en-GB", "title" }
                }
            });

            _mockGroupAdvisorRepository.Setup(o => o.CheckIfUserHasAccessToGroupBySlug(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(false);

            _mockGroupRepository.Setup(o => o.GetGroup(It.IsAny <string>(), It.IsAny <bool>()))
            .ReturnsAsync(HttpResponse.Successful(new GroupBuilder().AdditionalDocuments(new List <Document> {
                expectedResult
            }).Build()));

            _mockDocumentFactory.Setup(o => o.ToModel(It.IsAny <Asset>())).Returns(expectedResult);

            _mockContentfulConfigBuilder.Setup(o => o.Build(It.IsAny <string>())).Returns(new ContentfulConfig("", "", ""));

            _mockLoggedInHelper.Setup(o => o.GetLoggedInPerson()).Returns(new LoggedInPerson()
            {
                Email = "email",
                Name  = "name"
            });

            var documentsService = new DocumentsService(_mockDocumentRepositoryFunc.Object, _mockGroupAdvisorRepositoryFunc.Object, _mockGroupRepositoryFunc.Object, _mockDocumentFactory.Object, _mockContentfulConfigBuilder.Object, _mockLoggedInHelper.Object);


            // Act
            var result = await documentsService.GetSecureDocumentByAssetId("stockportgov", "asset id", "slug");

            // Assert
            result.Should().BeNull();
        }
Beispiel #28
0
        public SpreadsheetProxy(Credentials credentials)
        {
            spreadsheetService = new SpreadsheetsService("groundfloor-svc1");
            spreadsheetService.setUserCredentials(credentials.username, credentials.password);

            documentService = new DocumentsService("groundfloor-svc2");
            documentService.setUserCredentials(credentials.username, credentials.password);
        }
Beispiel #29
0
        public void DoWorkbookUpload(object in_instance)
        {
            var instance = in_instance as Google2uData;

            if (instance == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(instance.WorkbookUploadPath))
            {
                try
                {
                    // We need a DocumentService
                    var service  = new DocumentsService("Google2Unity");
                    var mimeType = Google2uMimeType.GetMimeType(instance.WorkbookUploadPath);

                    var authenticator = new OAuth2Authenticator("Google2Unity", _authParameters);

                    // Instantiate a DocumentEntry object to be inserted.
                    var entry = new DocumentEntry
                    {
                        MediaSource = new MediaFileSource(instance.WorkbookUploadPath, mimeType)
                    };

                    // Define the resumable upload link
                    var createUploadUrl =
                        new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full");
                    var link = new AtomLink(createUploadUrl.AbsoluteUri)
                    {
                        Rel = ResumableUploader.CreateMediaRelation
                    };

                    entry.Links.Add(link);

                    // Set the service to be used to parse the returned entry
                    entry.Service = service;


                    // Instantiate the ResumableUploader component.
                    var uploader = new ResumableUploader();

                    // Set the handlers for the completion and progress events
                    uploader.AsyncOperationCompleted += OnSpreadsheetUploadDone;
                    uploader.AsyncOperationProgress  += OnSpreadsheetUploadProgress;

                    // Start the upload process
                    uploader.InsertAsync(authenticator, entry, instance);
                }
                catch (Exception)
                {
                    PushNotification(
                        "There is a problem with your credentials. Clear the credentials and Re-Authorize G2U");
                    //instance.Messages.Add(new G2GUIMessage(GFGUIMessageType.InvalidLogin, ex.Message));
                    instance.Commands.Remove(GFCommand.WaitingForUpload);
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Will authenticate the user and setup the DocumentService used throughout NocsService.
        /// </summary>
        public static void AuthenticateUser(string userName, string password, bool forceAuthToken)
        {
            Working = true;

            try
            {
                if (forceAuthToken)
                {
                    _settings = null;
                }
                SetupService(userName, password, 3, null, null);

                _documentService.setUserCredentials(userName, password);
                _documentService.QueryClientLoginToken();
            }
            catch (InvalidCredentialsException)
            {
                Trace.WriteLine(DateTime.Now + " - NocsService: Invalid credentials");
                _documentService = null;
                throw new Exception("Invalid credentials.");
            }
            catch (CaptchaRequiredException)
            {
                Trace.WriteLine(DateTime.Now + " - NocsService: CaptchaRequiredException");
                _documentService = null;
                throw new Exception("Invalid credentials.");
            }
            catch (AuthenticationException)
            {
                Trace.WriteLine(DateTime.Now + " - NocsService: AuthenticationException");
                _documentService = null;
                throw new Exception("Invalid credentials.");
            }
            catch (GDataRequestException exRequest)
            {
                var error = GetErrorMessage(exRequest);

                if (exRequest.ResponseString == null && error.ToLowerInvariant().Contains("execution of request failed"))
                {
                    throw new GDataRequestException("Couldn't authenticate user, connection timed out");
                }

                Trace.WriteLine(DateTime.Now + " - NocsService: " + error);
                _documentService = null;
                throw new Exception(error);
            }
            catch (Exception ex)
            {
                var error = GetErrorMessage(ex);
                Trace.WriteLine(DateTime.Now + " - NocsService: " + error);
                _documentService = null;
                throw new Exception(error);
            }
            finally
            {
                Working = false;
            }
        }