/// <summary>
        /// Extension method to fill the data to the viewmodel from the repository model class object.
        /// </summary>
        /// <param name="viewModel">Repository view model.</param>
        /// <param name="model">Repository model.</param>
        public static void SetValuesFrom(this ManageReopsitoryViewModel viewModel, Repository model)
        {
            Check.IsNotNull<ManageReopsitoryViewModel>(viewModel, "repositoryViewModel");
            Check.IsNotNull<Repository>(model, "repositoryModel");

            viewModel.AllowedFileTypes = model.AllowedFileTypes;
            viewModel.BaseRepositoryId = model.BaseRepositoryId;
            viewModel.DeleteFielURL = model.HttpDeleteUriTemplate;
            viewModel.DownloadFileURL = model.HttpGetUriTemplate;
            viewModel.GetIdentifierURL = model.HttpIdentifierUriTemplate;
            viewModel.ImpersonatePassword = model.ImpersonatingPassword;
            viewModel.ImpersonateUserName = model.ImpersonatingUserName;
            viewModel.IsImpersonate = model.IsImpersonating == null ? false : (bool)model.IsImpersonating;
            viewModel.IsVisibleToAll = model.IsVisibleToAll;
            viewModel.VisibilityOption = model.IsVisibleToAll ? 1 : 2;
            viewModel.PostFileURL = model.HttpPostUriTemplate;
            viewModel.RepositoryId = model.RepositoryId;
            viewModel.RepositoryName = model.Name;
            viewModel.UserAgreement = model.UserAgreement;
            viewModel.CreatedBy = model.CreatedBy;
            viewModel.CreatedDate = model.CreatedOn;
            viewModel.AccessToken = model.AccessToken;
            viewModel.RefreshToken = model.RefreshToken;
            viewModel.TokenExpiresOn = model.TokenExpiresOn;

            // set repository metadata
            SetRepositoryMetaData(viewModel, model);
        }
        public void Allow_Publish_For_Impersonated_Repository()
        {
            // construct the model
            // construct the model
            AuthToken authToken = new AuthToken()
            {
                UserId = 1,
                RespositoryId = 2
            };

            File fakeFile = new File() { Name = "test1", FileId = 100, RepositoryId = 1, CreatedBy = 1, Status = FileStatus.None.ToString() };
            PublishMessage model = new PublishMessage() { RepositoryId = 1, AuthToken = authToken, FileId = fakeFile.FileId, UserId = 1 };
            this.repository = new Repository() { BaseRepositoryId = 2, Name = "test", IsImpersonating = true, AccessToken = "accessToken", RefreshToken = "refreshToken", TokenExpiresOn = DateTime.UtcNow.AddHours(1), BaseRepository = new BaseRepository { Name = "SkyDrive" } };
            SkyDriveFileService skyDriveFileService = this.GetSkyDriveFileService();
            IFileProcesser fileProcessor = new StubIFileProcesser()
            {
                DownloadDocumentFile = file => new DataDetail() { FileNameToDownLoad = "abc.xyz" }
            };

            string fileIdentifier;
            using (ShimsContext.Create())
            {
                ShimFileFactory.GetFileTypeInstanceStringIBlobDataRepositoryIFileRepositoryIRepositoryService = (fileExtension, blobDataRepository, fileDataRepository, repositoryService) => fileProcessor;
                fileIdentifier = skyDriveFileService.PublishFile(model);
            }

            Assert.IsFalse(string.IsNullOrEmpty(fileIdentifier));
        }
Exemple #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RepositoryBase" /> class.
 /// </summary>
 /// Initializes a new instance of the <see cref="RepositoryBase" /> class.
 /// <param name="authentication">Authentication parameter</param>
 /// <param name="name">Name parameter</param>
 /// <param name="url">Url parameter </param>
 public RepositoryModel(string authentication, string name, string url, Repository selectedRepository)
 {
     this.authorization = authentication;
     this.repositoryName = name;
     this.repositoryUrl = url;
     this.selectedRepository = selectedRepository;
 }
Exemple #4
0
        public HttpResponseMessage GetCitation(int fileId, int repositoryId)
        {
            DM.File file = fileService.GetFileByFileId(fileId);
            if (file == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.FileNotFound));
            }

            DM.Repository repository = this.repositoryService.GetRepositoryById(repositoryId);
            if (repository == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Repository_Not_Found));
            }
            else if (repository.BaseRepository.BaseRepositoryId != 1)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, string.Format(MessageStrings.CitationNotSupportedMessage, repository.BaseRepository.Name)));
            }

            Citation citation = new Citation()
            {
                PublicationYear = DateTime.Now.Year.ToString(),
                Title           = file.Title,
                Publisher       = string.Concat(this.user.LastName, ", ", this.user.FirstName)
            };

            if (!string.IsNullOrWhiteSpace(file.Citation))
            {
                citation = JsonConvert.DeserializeObject <Citation>(file.Citation);
            }

            return(Request.CreateResponse(HttpStatusCode.OK, citation));
        }
Exemple #5
0
        public HttpResponseMessage GetRepository(int id)
        {
            // Check if the model binding was successful and is in a valid state
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Empty));
            }
            try
            {
                // Check if the repository service is valid
                Check.IsNotNull(this.repositoryService, "repositoryService");

                DM.Repository repository = this.repositoryService.GetRepositoryById(id);

                return(Request.CreateResponse <DM.Repository>(HttpStatusCode.OK, repository));
            }
            catch (ArgumentNullException ane)
            {
                if (ane.ParamName.Equals("repositoryService"))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, MessageStrings.Repository_Service_Is_Null));
                }
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, MessageStrings.Invalid_Repository_id));
            }
            catch (Exception ex)
            {
                string error = ex.Message + ex.StackTrace + ex.GetType().ToString();
                if (null != ex.InnerException)
                {
                    error += ex.InnerException.Message + ex.InnerException.StackTrace + ex.InnerException.GetType().ToString();
                }
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
            }
        }
        /// <summary>
        /// Downloads the File from Repository
        /// </summary>
        /// <param name="file">File object.</param>
        /// <param name="repository">Repository instance.</param>
        /// <param name="user">User instance.</param>
        /// <param name="credentials">credentials required by the repository.</param>
        /// <returns>DataFile containing the file data.</returns>
        public override DataFile DownLoadFileFromRepository(File file, Repository repository, User user, RepositoryCredentials credentials)
        {
            // construct the AuthToken object
            AuthToken authToken = new AuthToken()
            {
                UserId = user.UserId,
                RespositoryId = repository.RepositoryId
            };

            if (credentials != null)
            {
                authToken.AccessToken = credentials[WindowsLiveAuthenticationCredentialKeys.AccessToken];
                authToken.RefreshToken = credentials[WindowsLiveAuthenticationCredentialKeys.RefreshToken];
                
                if (credentials[WindowsLiveAuthenticationCredentialKeys.TokenExpiresOn] != null)
                {
                    DateTime tokenExpiryDate;
                    if (DateTime.TryParse(credentials[WindowsLiveAuthenticationCredentialKeys.TokenExpiresOn], out tokenExpiryDate))
                    {
                        authToken.TokenExpiresOn = tokenExpiryDate;
                    };
                }
            }
            
            this.RepositoryAdapter = this.RepositoryAdapterFactory.GetRepositoryAdapter(repository.BaseRepository.Name);

            // Retreive the AuthToken from database or save the token to database if access token is present in the credentials.
            authToken = this.GetOrUpdateAuthTokens(repository, authToken);
           
            DataFile dataFile = this.RepositoryAdapter.DownloadFile(file.Identifier, authToken.AccessToken, file.Name);
            return dataFile;           
        }
        private void AddDefaultData()
        {
            User newUser = new User()
            {
                NameIdentifier = "s0Me1De9Tf!Er$tRing",
                FirstName = "TestFirstName",
                MiddleName = "TestMiddleName",
                LastName = "TestLastName",
                IdentityProvider = "Windows Live",
                Organization = "TestOrganization",
                EmailId = "*****@*****.**",
                CreatedOn = DateTime.Now,
                ModifiedOn = DateTime.Now,
                IsActive = true,
                UserAttributes = null
            };

            // User with userid 1
            AddUser(newUser);

            //  RepositoryType repoType1 = new RepositoryType() { IsActive = true, Name = "type1", RepositoryTypeId = 1, Repositories = null };

            // Adding new repository types
            // AddRepositoryType(repoType1);

            BaseRepository baseRepo = new BaseRepository() { BaseRepositoryId = 1, Name = "Merrit" };

            AddBaseRepository(baseRepo);

            Repository repositoryObject = new Repository()
            {
                AllowedFileTypes = "xlsx,nc,csv",
                CreatedBy = 1,
                // Files = null,
                CreatedOn = DateTime.Now,
                HttpDeleteUriTemplate = "http://google.com",
                HttpGetUriTemplate = "http://google.com",
                HttpIdentifierUriTemplate = "http://google.com",
                HttpPostUriTemplate = "http://google.com",
                ImpersonatingPassword = "******",
                ImpersonatingUserName = "******",
                IsActive = true,
                IsImpersonating = true,
                ModifiedBy = 1,
                ModifiedOn = DateTime.Now,
                Name = "Repository1",
                RepositoryId = 1,
                UserAgreement = "Test Agreement1",
                BaseRepositoryId = 1
            };

            AddRepository(repositoryObject);

            File fileToAdd = new File() { Citation = "Citation 1", CreatedBy = 1, CreatedOn = DateTime.Now, Description = "Document 1", FileAttributes = null, FileColumns = null, FileId = 1, FileQualityChecks = null, Identifier = "asdahgsdfsghadfsghad", isDeleted = false, MimeType = "Mime type 1", ModifiedBy = 1, ModifiedOn = DateTime.Now, Name = "Document One", Repository = null, RepositoryId = 1, Size = 20.90, Status = "Uploaded", Title = "Document 1" };

            File fileToAdd1 = new File() { Citation = "Citation 2", CreatedBy = 1, CreatedOn = DateTime.Now, Description = "Document 2", FileAttributes = null, FileColumns = null, FileId = 2, FileQualityChecks = null, Identifier = "wrwe23423ewr", isDeleted = false, MimeType = "Mime type 2", ModifiedBy = 1, ModifiedOn = DateTime.Now, Name = "Document Two", Repository = null, RepositoryId = 1, Size = 20.90, Status = "Uploaded", Title = "Document 2" };

            AddFile(fileToAdd);
            AddFile(fileToAdd1);

            FileColumnUnit fileUnit = new FileColumnUnit()
            {
                Name = "Text",
                Status = true
            };
            AddFileColumnUnit(fileUnit);

            FileColumnType fileType = new FileColumnType()
            {
                Name = "Acre",
                Status = true
            };

            AddFileColumnType(fileType);
        }
Exemple #8
0
        /// <summary>
        /// Method to update the repository.
        /// </summary>
        /// <param name="repository">Repository details.</param>
        /// <returns>Updated repository.</returns>
        /// <exception cref="ArgumentException">When repository is null</exception>
        public Repository UpdateRepository(Repository repository)
        {
            Check.IsNotNull<Repository>(repository, "modifiedRepository");
            Repository updatedRepository = Context.Repositories.Attach(repository);

            
            Context.SetEntityState<Repository>(updatedRepository, EntityState.Modified);


            return updatedRepository;
        }
        /// <summary>
        /// validates if the token is expired
        /// </summary>
        /// <param name="token">AuthToken</param>
        /// <returns>Boolean</returns>
        private AuthToken RefreshAccessToken(Repository repository, AuthToken token)
        {
            if (DateTime.UtcNow < token.TokenExpiresOn)
            {
                return token;
            }

            AuthToken freshToken = this.RepositoryAdapter.RefreshToken(token.RefreshToken);

            freshToken.RespositoryId = token.RespositoryId;
            freshToken.UserId = token.UserId;

            if ((bool)repository.IsImpersonating)
            {
                repository.AccessToken = freshToken.AccessToken;
                repository.RefreshToken = freshToken.RefreshToken;
                repository.TokenExpiresOn = freshToken.TokenExpiresOn;
                this.RepositoryDetails.UpdateRepository(repository);
            }
            else
            {
                this.userService.AddUpdateAuthToken(freshToken);
            }

            return freshToken;
        }
        /// <summary>
        /// Action method to save the repository data to the database.
        /// </summary>
        /// <param name="repositoryViewModel">Repository viewmodel.</param>
        /// <returns>Json result with the status.</returns>
        public ActionResult SaveRepository(ManageReopsitoryViewModel repositoryViewModel)
        {
            string message = string.Empty;
            string status = "success";
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            try
            {
                if (repositoryViewModel != null)
                {
                    Repository repModel = new Repository();
                    repModel = repositoryViewModel.SetValuesTo(repModel);

                    // serlize the data file before passing to API
                    string repositoryData = repModel.SerializeObject<Repository>("repositoryModel");

                    // create the object of HttpWeb Request Manager
                    webRequestManager = new HttpWebRequestManager();
                    webClientManager = new WebClientRequestManager();
                    webRequestManager.SetRequestDetails(new RequestParams()
                    {
                        RequestURL = string.Concat(BaseController.BaseWebApiRepositoryPath + "?repositoryName=" + repModel.Name),
                    });

                    string repositoryIdResult = webRequestManager.RetrieveWebResponse();
                    int repositoryResult = jsSerializer.Deserialize<int>(repositoryIdResult);

                    if (repositoryResult == 0 || repModel.RepositoryId == repositoryResult)
                    {
                        NameValueCollection values = new NameValueCollection();
                        values.Add("repositoryModel", repositoryData.EncodeTo64());

                        string responseString = webClientManager.UploadValues(new RequestParams()
                        {
                            RequestURL = string.Concat(BaseController.BaseWebApiRepositoryPath),
                            RequestMode = RequestMode.POST,
                            AllowAutoRedirect = false,
                            Values = values
                        });

                        if (!string.IsNullOrEmpty(webClientManager.RedirectionURL))
                        {
                            status = "redirect";
                            message = webClientManager.RedirectionURL;
                            return Json(new { Status = status, Message = message });
                        }

                        bool postResult = jsSerializer.Deserialize<bool>(responseString);

                        if (postResult)
                        {
                            status = "success";
                            // after updating the repostory metadata field,delete the repository metadata field that are marked for deletion
                            if (repositoryViewModel.DeletedMetaDataFieldIds != null && repositoryViewModel.DeletedMetaDataFieldIds.Length > 0)
                            {
                                string deleteResponseString = webClientManager.UploadValues(new RequestParams()
                                {
                                    RequestURL = string.Concat(BaseController.BaseWebApiRepositoryPath, "?repositorId=", repositoryViewModel.RepositoryId, "&repositoryMetadataFields=", repositoryViewModel.DeletedMetaDataFieldIds),
                                    RequestMode = RequestMode.DELETE
                                });

                                jsSerializer = new JavaScriptSerializer();
                                jsSerializer.Deserialize<bool>(deleteResponseString);
                            }

                        }
                        else
                        {
                            ViewBag.ErrorMessage = Messages.RepositoryErrMsg;
                            status = "error";
                            message = Messages.RepositoryErrMsg;
                        }
                    }
                    else
                    {
                        status = "error";
                        message = Messages.DuplicateRepositoryMsg;
                    }
                }
                else
                {
                    status = "error";
                    message = Messages.RepositoryErrMsg;
                }
            }
            catch (WebException webException)
            {
                using (Stream stream = webException.Response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        status = "error";
                        message = reader.ReadToEnd();
                        jsSerializer = new JavaScriptSerializer();
                        var data = jsSerializer.Deserialize<Dictionary<string,object>>(message);
                        message = (string)data.First(m=>m.Key == "Message").Value;
                    }
                }
            }
            catch (Exception exception)
            {
                message = exception.Message;
            }

            return Json(new { Status = status, Message = message });
        }
        public void Return_ErrorCode_When_Adapter_Returns_Failure()
        {
            // construct the model
            AuthToken authToken = new AuthToken()
            {
                AccessToken = "accessToken",
                RefreshToken = "refreshToken",
                TokenExpiresOn = DateTime.UtcNow.AddHours(-1),
                RespositoryId = 1
            };

            File fakeFile = new File() { Name = "test1", FileId = 100, RepositoryId = 1, CreatedBy = 1, Status = FileStatus.None.ToString() };
            PublishMessage model = new PublishMessage() { RepositoryId = 3, AuthToken = authToken, FileId = fakeFile.FileId, UserId = 1 };
            this.repository = new Repository() { BaseRepositoryId = 2, Name = "test", IsImpersonating = false, BaseRepository = new BaseRepository { Name = "SkyDrive" } };
            this.userAuthToken = null;
            var fileProvider = this.GetSkyDriveFileService();
            this.skyDriveAdapter = new Microsoft.Research.DataOnboarding.RepositoryAdapters.Interfaces.Fakes.StubIRepositoryAdapter()
            {
                PostFilePublishFileModel = (publishFileModel) =>
                {
                    OperationStatus status = OperationStatus.CreateFailureStatus("error");
                    return status;
                },
            };
            IFileProcesser fileProcessor = new StubIFileProcesser()
            {
                DownloadDocumentFile = file => new DataDetail() { FileNameToDownLoad = "abc.xyz" }
            };

            string fileIdentifier;
            using (ShimsContext.Create())
            {
                ShimFileFactory.GetFileTypeInstanceStringIBlobDataRepositoryIFileRepositoryIRepositoryService = (fileExtension, blobDataRepository, fileDataRepository, repositoryService) => fileProcessor;
                ShimSkyDriveFileService.AllInstances.GetOrUpdateAuthTokensRepositoryAuthToken = (skyDriveFileService, repository, at) => new AuthToken();
                fileIdentifier = fileProvider.PublishFile(model);
            }

            Assert.IsTrue(string.IsNullOrEmpty(fileIdentifier));
        }
        public void Allow_Download()
        {
            BaseRepository baseRepository = new BaseRepository()
            {
                BaseRepositoryId = 2,
                Name = "SkyDrive"
            };

            this.repository = new Repository() { BaseRepositoryId = 2, Name = "test", IsImpersonating = false, BaseRepository = baseRepository };
            RepositoryCredentials repositoryCredentials = new RepositoryCredentials();
            File file = new File()
            {
                FileId = 1
            };

            User user = new User()
            {
                UserId = 1
            };
          
            var fileProvider = this.GetSkyDriveFileService();
            this.skyDriveAdapter = new Microsoft.Research.DataOnboarding.RepositoryAdapters.Interfaces.Fakes.StubIRepositoryAdapter()
            {
                PostFilePublishFileModel = (publishFileModel) =>
                    {
                        OperationStatus status = OperationStatus.CreateFailureStatus("error");
                        return status;
                    },
                DownloadFileStringStringString = (identifier, accessToken, fileName) =>
                    {
                        return new DataFile();
                    }
            };

            DataFile result;
            using (ShimsContext.Create())
            {
                ShimSkyDriveFileService.AllInstances.GetOrUpdateAuthTokensRepositoryAuthToken = (skyDriveFileService, repository, authToken) => new AuthToken();
                result = fileProvider.DownLoadFileFromRepository(file, this.repository, user, repositoryCredentials);
            }

            Assert.IsNotNull(result);
        }
Exemple #13
0
        private static Repository SetRepositoryValues(Repository repositoryDetails)
        {
            var repositry = new Repository();
            repositry.RepositoryId = repositoryDetails.RepositoryId;
            repositry.AllowedFileTypes = repositoryDetails.AllowedFileTypes;
            repositry.BaseRepositoryId = repositoryDetails.BaseRepositoryId;
            repositry.CreatedBy = repositoryDetails.CreatedBy;
            repositry.CreatedOn = repositoryDetails.CreatedOn;
            repositry.HttpDeleteUriTemplate = repositoryDetails.HttpDeleteUriTemplate;
            repositry.HttpGetUriTemplate = repositoryDetails.HttpGetUriTemplate;
            repositry.HttpIdentifierUriTemplate = repositoryDetails.HttpIdentifierUriTemplate;
            repositry.HttpPostUriTemplate = repositoryDetails.HttpPostUriTemplate;
            repositry.ImpersonatingPassword = repositoryDetails.ImpersonatingPassword;
            repositry.ImpersonatingUserName = repositoryDetails.ImpersonatingUserName;
            repositry.IsActive = repositoryDetails.IsActive;
            repositry.IsImpersonating = repositoryDetails.IsImpersonating;
            repositry.IsVisibleToAll = repositoryDetails.IsVisibleToAll;
            repositry.ModifiedBy = repositoryDetails.ModifiedBy;
            repositry.ModifiedOn = repositoryDetails.ModifiedOn;
            repositry.Name = repositoryDetails.Name;
            repositry.UserAgreement = repositoryDetails.UserAgreement;
            repositry.AccessToken = repositoryDetails.AccessToken;
            repositry.RefreshToken = repositoryDetails.RefreshToken;
            repositry.TokenExpiresOn = repositoryDetails.TokenExpiresOn;

            return repositry;
        }
Exemple #14
0
 private Repository GetRepositoryWithOutChildDetails(Repository repsoitory)
 {
     var plainRepositroty = new Repository();
     return plainRepositroty;
 }
Exemple #15
0
        private RepositoryMetadata SetRepositoryMetaData(Repository repositoryData, Repository updatedRepositoryData, RepositoryMetadata savedRepositoryMetaData)
        {
            var actualRepositoryMetaData = repositoryData.RepositoryMetadata.FirstOrDefault();

            actualRepositoryMetaData.RepositoryId = updatedRepositoryData.RepositoryId;
            if (actualRepositoryMetaData.RepositoryMetadataId > 0)
            {
                actualRepositoryMetaData.ModifiedBy = updatedRepositoryData.CreatedBy;
                actualRepositoryMetaData.ModifiedOn = DateTime.UtcNow;
            }
            else
            {
                actualRepositoryMetaData.CreatedBy = updatedRepositoryData.CreatedBy;
                actualRepositoryMetaData.CreatedOn = DateTime.UtcNow;
            }

            savedRepositoryMetaData = this.repositoryDetails.SaveRepositoryMetaData(actualRepositoryMetaData);
            return savedRepositoryMetaData;
        }
Exemple #16
0
        /// <summary>
        /// Downloads the file from Repository.
        /// </summary>
        /// <param name="fileId">File Id.</param>
        /// <param name="user">User instance.</param>
        /// <returns>File stream.</returns>
        private HttpResponseMessage DownloadFileFromRepository(int fileId, User user)
        {
            HttpError error;

            try
            {
                if (fileId <= 0)
                {
                    error = new HttpError(string.Format(MessageStrings.Argument_Error_Message_Template, "fileId"));
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));
                }

                var file = this.fileService.GetFiles(p => p.FileId == fileId && p.CreatedBy == user.UserId).FirstOrDefault();

                if (file == null)
                {
                    error = new HttpError(MessageStrings.FileDoesntExist)
                    {
                        {
                            "FileId",
                            fileId
                        }
                    };

                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, error));
                }

                if (file.RepositoryId == null)
                {
                    error = new HttpError(MessageStrings.File_Repository_Is_Null)
                    {
                        {
                            "FileId",
                            fileId
                        }
                    };

                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, error));
                }

                DM.Repository repository = this.repositoryService.GetRepositoryById((int)file.RepositoryId);

                if (repository == null)
                {
                    error = new HttpError(MessageStrings.Repository_Not_Found)
                    {
                        {
                            "RepositoryId",
                            (int)file.RepositoryId
                        }
                    };

                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, error));
                }

                RepositoryCredentials repositoryCredentials = GetRepsitoryCredentials();

                this.fileService = this.fileServiceFactory.GetFileService(repository.BaseRepository.Name);
                DataFile dataFile = this.fileService.DownLoadFileFromRepository(file, repository, user, repositoryCredentials);

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(new MemoryStream(dataFile.FileContent));
                result.Content.Headers.ContentType                 = new MediaTypeHeaderValue(Constants.APPLICATION_X_ZIP);
                result.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = dataFile.FileName;
                return(result);
            }
            catch (ArgumentNullException ane)
            {
                message = string.Format(MessageStrings.Argument_Error_Message_Template, ane.ParamName);
                status  = HttpStatusCode.BadRequest;
            }
            catch (FileDownloadException downloadException)
            {
                if (downloadException.FileDownloadExceptionType == FileDownloadExceptionType.DownloadUrlNotFound.ToString())
                {
                    error = downloadException.GetHttpError(MessageStrings.Download_URL_Empty);
                }
                else
                {
                    error = downloadException.GetHttpError(string.Empty);
                }

                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
            }
            catch (WebException ex)
            {
                // If status code is 404 then send the custom message indicating file does not exist in repository.
                // else read the message and send it to client as text.
                HttpResponseMessage response;
                if (ex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
                {
                    error    = new HttpError(MessageStrings.FileDoesNotExistInRepository);
                    response = Request.CreateErrorResponse(HttpStatusCode.NotFound, error);
                }
                else
                {
                    string errorText = string.Empty;
                    using (Stream st = ((System.Net.WebException)(ex)).Response.GetResponseStream())
                        using (StreamReader reader = new StreamReader(st))
                        {
                            errorText = reader.ReadToEnd();
                        }
                    error    = new HttpError(errorText);
                    response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error);
                }

                return(response);
            }

            return(Request.CreateErrorResponse(status, message));
        }
Exemple #17
0
        public HttpResponseMessage Publish()
        {
            string         message    = string.Empty;
            HttpStatusCode status     = HttpStatusCode.OK;
            PostFileModel  dataDetail = new PostFileModel();

            try
            {
                diagnostics.WriteInformationTrace(TraceEventId.Flow, "Into publish");

                if (HttpContext.Current.Request["PostFileData"] != null)
                {
                    var postFileString = HttpContext.Current.Request["PostFileData"];

                    if (postFileString != null)
                    {
                        //diagnostics.WriteInformationTrace(TraceEventId.Flow, "Into publishing3");

                        /****************************************************
                        * TODO: Try catch block below is required to handle the case where the
                        * clients send post request with JSON payload as plain text.
                        * The API needs to be refactored to take the model as input
                        * and have the MVC framework resolve/deserialize the payload
                        * into model object.
                        * **************************************************/
                        PostFileModel postFileData = default(PostFileModel);
                        try
                        {
                            postFileData = Helper.DeSerializeObject <PostFileModel>(postFileString.DecodeFrom64(), "postFile");
                        }
                        catch (Exception)
                        {
                            // If the data is not base 64 encoded
                            using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(postFileString)))
                            {
                                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(PostFileModel));
                                postFileData = (PostFileModel)jsonSerializer.ReadObject(stream);
                            }
                        }

                        DM.Repository repository = repositoryService.GetRepositoryById(postFileData.SelectedRepositoryId);
                        this.fileService = this.fileServiceFactory.GetFileService(repository.BaseRepository.Name);

                        // Get the AuthToken from the request. TODO need to move below code to SkyDriveFileController.
                        AuthToken userAuthToken = postFileData.UserAuthToken;
                        userAuthToken.UserId        = this.user.UserId;
                        userAuthToken.RespositoryId = repository.RepositoryId;

                        // Save the file details to db and publish logic
                        this.fileService.SaveFile(postFileData);

                        return(Request.CreateResponse <OperationStatus>(HttpStatusCode.OK, OperationStatus.CreateSuccessStatus()));
                    }
                }
            }
            catch (ArgumentNullException ane)
            {
                diagnostics.WriteErrorTrace(TraceEventId.Exception, ane);
                status = HttpStatusCode.BadRequest;

                if (ane.ParamName.Equals("fileService"))
                {
                    message = MessageStrings.File_Service_Is_Null;
                }
                else
                {
                    message = ane.Message + ane.StackTrace + ane.GetType().ToString();
                }
            }
            catch (Exception ex)
            {
                diagnostics.WriteErrorTrace(TraceEventId.Exception, ex);
                message = ex.Message + ex.StackTrace + ex.GetType().ToString();
                if (null != ex.InnerException)
                {
                    message += ex.InnerException.Message + ex.InnerException.StackTrace + ex.InnerException.GetType().ToString();
                }

                status = HttpStatusCode.InternalServerError;
            }

            return(Request.CreateErrorResponse(status, message));
        }
Exemple #18
0
        /// <summary>
        /// Gets or updates the AuthTokens
        /// </summary>
        /// <param name="repository">Repository</param>
        /// <param name="userAuthToken">AuthToken</param>
        /// <returns>AuthToken</returns>
        private AuthToken GetOrUpdateAuthTokens(Repository repository, AuthToken userAuthToken)
        {
            AuthToken token = userAuthToken;
            
            // if Impersonating then get the token from repository
            if ((bool)repository.IsImpersonating)
            {
                diagnostics.WriteVerboseTrace(TraceEventId.Flow, "Impersonation is ON");
                token = new AuthToken()
                {
                    AccessToken = repository.AccessToken,
                    RefreshToken = repository.RefreshToken,
                    TokenExpiresOn = (DateTime)repository.TokenExpiresOn
                };
            }
            // if accessToken is null then get the authtoken from the database
            else
            {
                if (string.IsNullOrEmpty(userAuthToken.AccessToken))
                {
                    diagnostics.WriteVerboseTrace(TraceEventId.Flow, "Get the token from the database");
                    token = this.userService.GetUserAuthToken(userAuthToken.UserId, repository.RepositoryId);
                }
                else if(userAuthToken.Id <= 0)
                {
                    diagnostics.WriteVerboseTrace(TraceEventId.Flow, "Request has the token so add the token to database");
                    token = this.userService.AddUpdateAuthToken(userAuthToken);
                }
            }

            if (null == token)
            {
                throw new AccessTokenNotFoundException()
                {
                    RepositoryId = repository.RepositoryId,
                    UserId = userAuthToken.UserId
                };
            }

            // check if the AuthToken expired if yes then get new access token from refresh token
            return RefreshAccessToken(repository, token);
        }
 /// <summary>
 /// Downloads the File from Repository
 /// </summary>
 /// <param name="file">File object.</param>
 /// <param name="repository">Repository instance.</param>
 /// <param name="user">User instance.</param>
 /// <param name="credentials">credentials required by the repository.</param>
 /// <returns>DataFile containing the file data.</returns>
 public virtual DataFile DownLoadFileFromRepository(DM.File file, Repository repository, User user, RepositoryCredentials credentials)
 {
     throw new NotSupportedException();
 }
Exemple #20
0
        /// <summary>
        /// Returns the AuthToken for the Repository and User
        /// </summary>
        /// <param name="repository">Repository instance.</param>
        /// <param name="userId">User Id.</param>
        /// <returns>AuthToken object.</returns>
        private AuthToken GetAuthTokens(Repository repository, int userId)
        {
            AuthToken token;

            // if Impersonating then get the token from repository
            if ((bool)repository.IsImpersonating)
            {
                diagnostics.WriteVerboseTrace(TraceEventId.Flow, "Impersonation is ON");
                token = new AuthToken()
                {
                    AccessToken = repository.AccessToken,
                    RefreshToken = repository.RefreshToken,
                    TokenExpiresOn = (DateTime)repository.TokenExpiresOn
                };
            }
            else
            {
                diagnostics.WriteVerboseTrace(TraceEventId.Flow, "Get the token from the database");
                token = this.userService.GetUserAuthToken(userId, repository.RepositoryId);
            }

            if (null == token)
            {
                throw new AccessTokenNotFoundException()
                {
                    RepositoryId = repository.RepositoryId,
                    UserId = userId
                };
            }

            // check if the AuthToken expired if yes then get new access token from refresh token
            return RefreshAccessToken(repository, token);
        }
        public void Get_Repository_By_Id_When_No_Repository_Service_Available()
        {
            Repository fakeRepository = new Repository() { RepositoryId = 3, CreatedBy = 1, BaseRepositoryId = 1, IsActive = true };

            this.repositoryService = null;

            RepositoryController repositoryController = CreateRequest(HttpMethod.Get);
            // Perform
            var response = repositoryController.GetRepository(fakeRepository.RepositoryId);

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.InternalServerError, "Expexted and actual status are not equal");
            var result = response.Content.ReadAsAsync<HttpError>().Result;
            Assert.IsNotNull(result, "Result is null");
            Assert.AreEqual(result.Message, "Repository service outage. Contact Data Onboarding support.", "Result is not null");
        }
        /// <summary>
        /// Downloads the File from Repository
        /// </summary>
        /// <param name="file">File object.</param>
        /// <param name="repository">Repository instance.</param>
        /// <param name="user">User instance.</param>
        /// <param name="credentials">credentials required by the repository.</param>
        /// <returns>DataFile containing the file data.</returns>
        public override DataFile DownLoadFileFromRepository(DomainModel.File file, Repository repository, User user, RepositoryCredentials credentials)
        {
            string userName = string.Empty;
            string password = string.Empty;

            if ((bool)repository.IsImpersonating)
            {
                userName = repository.ImpersonatingUserName;
                password = repository.ImpersonatingPassword;
            }
            else
            {
                userName = credentials[BasicAuthenticationCredentialKeys.UserName];
                password = credentials[BasicAuthenticationCredentialKeys.Password];

                if (string.IsNullOrEmpty(userName))
                {
                    throw new ArgumentNullException(BasicAuthenticationCredentialKeys.UserName);
                }

                if (string.IsNullOrEmpty(password))
                {
                    throw new ArgumentNullException(BasicAuthenticationCredentialKeys.Password);
                }
            }

            var authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName /*UserName*/ + ":" + password/*Password*/));

            if (string.IsNullOrEmpty(repository.HttpGetUriTemplate))
            {
                throw new FileDownloadException()
                {
                    FileId = file.FileId,
                    RepositoryId = repository.RepositoryId,
                    FileDownloadExceptionType = FileDownloadExceptionType.DownloadUrlNotFound.ToString()
                };
            }

            var downloadURL = string.Join(string.Empty, repository.HttpGetUriTemplate, HttpUtility.UrlEncode(file.Identifier));
            IRepositoryAdapter repAdapter = this.RepositoryAdapterFactory.GetRepositoryAdapter(repository.BaseRepository.Name);
            DataFile dataFile = repAdapter.DownloadFile(downloadURL, authorization, file.Name);
            return dataFile;
        }
        public void Get_Repository_By_Id_Error_Inner_Exception()
        {
            Repository fakeRepository = new Repository() { RepositoryId = 3, CreatedBy = 1, BaseRepositoryId = 1, IsActive = true };

            this.repositoryService = new Microsoft.Research.DataOnboarding.RepositoriesService.Interface.Fakes.StubIRepositoryService()
            {
                GetRepositoryByIdInt32 = id => { throw new Exception("", new Exception("Some Inner Exception")); }
            };

            RepositoryController repositoryController = CreateRequest(HttpMethod.Get);

            // Perform
            var response = repositoryController.GetRepository(fakeRepository.RepositoryId);

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.InternalServerError, "Expexted and actual status are not equal");
            var result = response.Content.ReadAsAsync<HttpError>().Result;
            Assert.IsTrue(result.Message.Contains("Some Inner Exception"), "Result is not as expected");
        }
        /// <summary>
        /// Helper method to get the post query data.
        /// </summary>
        /// <param name="identifier">Unique identifier.</param>
        /// <param name="fileData">File information.</param>
        /// <param name="postFileData">Post file indormation.</param>
        /// <returns></returns>
        protected MerritQueryData GetPostQueryData(string identifier, DM.File fileData, Citation citation, Repository repository, PublishMessage postFileData)
        {
            Check.IsNotNull(identifier, "identifier");

            MerritQueryData queryData = new MerritQueryData();

            // TODO: Currently hard coded, needs to be replaced with specific value
            queryData.MetadataXML = @"<eml:eml packageId=""doi:10.5072/12345?"" system=""DCXL"" xmlns:eml=""eml://ecoinformatics.org/eml2.1.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""eml://ecoinformatics.org/eml-2.1.0 eml.xsd"">    <dataset id=""doi:10.5072/12345"">        <creator>            <!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-resource.html#creator -->            <!-- multiple creators allowed -->            <individualName>                <givenName></givenName>                <surName></surName>            </individualName>            <address>                <deliveryPoint></deliveryPoint>                <city></city>                <administrativeArea></administrativeArea><postalCode></postalCode><country></country></address><phone></phone><electronicMailAddress></electronicMailAddress><organizationName></organizationName></creator><title></title><pubDate></pubDate><abstract><para></para></abstract><publisher><para></para></publisher><url></url><contact><individualName><givenName></givenName><surName></surName></individualName><address><deliveryPoint></deliveryPoint><city></city><administrativeArea></administrativeArea><postalCode></postalCode><country></country></address><phone></phone><electronicMailAddress></electronicMailAddress><organizationName></organizationName></contact><keywordSet><keyword></keyword><keywordThesaurus></keywordThesaurus></keywordSet><coverage><!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-resource.html#coverage -->  <geographicCoverage><geographicDescription></geographicDescription><boundingCoordinates><westBoundingCoordinate></westBoundingCoordinate><eastBoundingCoordinate></eastBoundingCoordinate><northBoundingCoordinate></northBoundingCoordinate><southBoundingCoordinate></southBoundingCoordinate></boundingCoordinates></geographicCoverage><temporalCoverage id=""tempcov""><rangeOfDates> <beginDate><calendarDate></calendarDate></beginDate><endDate><calendarDate></calendarDate></endDate></rangeOfDates></temporalCoverage></coverage><project><!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-dataset.html#project --><title></title><abstract><para></para></abstract><funding><para></para></funding></project>        <intellectualRights>            <para></para>        </intellectualRights>        <dataTable>            <!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-dataTable.html#dataTable -->            <!-- dataTable is equivalent to a single tab in the excel spreadsheet.         One can have multiple data tables within the document. -->            <entityName></entityName>            <entityDescription></entityDescription>            <attributeList>                <!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-dataTable.html#attributeList -->                <!-- attribute list is equivalent to the parameter table from the requirements document.         One can have many attributes in a single table. -->                <attribute>                    <attributeName>                        <!-- non-empty string --></attributeName>                    <attributeDefinition>                        <!-- non-empty string --></attributeDefinition>                </attribute>            </attributeList>        </dataTable>    </dataset>    <additionalMetadata>        <describes>tempcov</describes>        <metadata>            <description>                <!-- non-empty string describing temporal coverage -->            </description>        </metadata>    </additionalMetadata>    <additionalMetadata>        <metadata>            <formattedCitation>                <!-- non-empty string -->            </formattedCitation>        </metadata>    </additionalMetadata></eml:eml>";

            List<DKeyValuePair<string, string>> content = new List<DKeyValuePair<string, string>>();

            Check.IsNotNull<DM.Repository>(repository, "selectedRepository");

            var repositoryMetadata = repository.RepositoryMetadata.FirstOrDefault();
            if (repositoryMetadata != null)
            {
                foreach (var repositoryMetaData in repositoryMetadata.RepositoryMetadataFields)
                {
                    DKeyValuePair<string, string> metadata = new DKeyValuePair<string, string>();
                    metadata.Key = repositoryMetaData.Name;
                    var metadataField = fileData.FileMetadataFields.Where(f => f.RepositoryMetadataFieldId == repositoryMetaData.RepositoryMetadataFieldId).FirstOrDefault();

                    if (metadataField != null)
                    {
                        metadata.Value = fileData.FileMetadataFields.Where(f => f.RepositoryMetadataFieldId == repositoryMetaData.RepositoryMetadataFieldId).FirstOrDefault().MetadataValue;
                    }

                    content.Add(metadata);
                }
            }

            //set the data to filemetadata fields
            //postFileData.FileMetaDataFields = fileData.FileMetadataFields;

            content.Add(new DKeyValuePair<string, string>() { Key = "Profile", Value = ConfigReader<string>.GetSetting("Profile_Post") });
            content.Add(new DKeyValuePair<string, string>() { Key = "who", Value = citation.Publisher });
            content.Add(new DKeyValuePair<string, string>() { Key = "what", Value = citation.Title });
            content.Add(new DKeyValuePair<string, string>() { Key = "when", Value = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture) });
            content.Add(new DKeyValuePair<string, string>() { Key = "where", Value = identifier });
            content.Add(new DKeyValuePair<string, string>() { Key = "ARK", Value = identifier });

            queryData.KeyValuePair = content.ToArray();

            return queryData;
        }
Exemple #25
0
        public HttpResponseMessage GetFileLevelMetadata(int fileId, int repositoryId)
        {
            List <FileLevelMetadata> fileLevelMetadataList = new List <FileLevelMetadata>();

            DM.File file = fileService.GetFileByFileId(fileId);
            if (file == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.FileNotFound));
            }

            DM.Repository repository = this.repositoryService.GetRepositoryById(repositoryId);
            if (repository == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Repository_Not_Found));
            }

            if (repository.RepositoryMetadata == null || !repository.RepositoryMetadata.Any())
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.NoMetadataFould));
            }

            RepositoryMetadata repositoryMetadata = repository.RepositoryMetadata.FirstOrDefault(m => m.IsActive == true);

            if (repositoryMetadata == null || repositoryMetadata.RepositoryMetadataFields == null || !repositoryMetadata.RepositoryMetadataFields.Any())
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.NoMetadataFould));
            }

            file.RepositoryId = repositoryId;
            foreach (RepositoryMetadataField repositoryMetadataField in repositoryMetadata.RepositoryMetadataFields)
            {
                FileLevelMetadata fileLevelMetadata = new FileLevelMetadata()
                {
                    RepositoryMetadataId      = repositoryMetadataField.RepositoryMetadataId,
                    RepositoryMetadataFieldId = repositoryMetadataField.RepositoryMetadataFieldId,
                    MetaDataTypeId            = repositoryMetadataField.MetadataTypeId,
                    FieldName   = repositoryMetadataField.Name,
                    Description = repositoryMetadataField.Description,
                    IsRequired  = repositoryMetadataField.IsRequired,
                    Datatype    = repositoryMetadataField.MetadataTypeId.ToString()
                };

                if (!string.IsNullOrWhiteSpace(repositoryMetadataField.Range))
                {
                    float[] range = repositoryMetadataField.Range.Split(new string[] { Constants.RangeSeparator }, StringSplitOptions.RemoveEmptyEntries).Select(v => Convert.ToSingle(v)).ToArray();
                    fileLevelMetadata.RangeValues = range;
                }

                FileMetadataField fileMetadataField = null;
                // first try to get the values from the database
                if (file.FileMetadataFields != null && file.FileMetadataFields.Any())
                {
                    fileMetadataField = file.FileMetadataFields.Where(p => p.RepositoryMetadataFieldId == repositoryMetadataField.RepositoryMetadataFieldId).FirstOrDefault();
                }

                if (fileMetadataField != null)
                {
                    fileLevelMetadata.FileMetadataFieldId = fileMetadataField.FileMetadataFieldId;
                    fileLevelMetadata.FieldValue          = fileMetadataField.MetadataValue;
                }

                fileLevelMetadataList.Add(fileLevelMetadata);
            }

            return(Request.CreateResponse(HttpStatusCode.OK, fileLevelMetadataList));
        }
        public void Get_Repository_By_Id_Failure()
        {
            Repository fakeRepository = new Repository() { RepositoryId = 3, CreatedBy = 1, BaseRepositoryId = 1, IsActive = true };

            this.repositoryService = new Microsoft.Research.DataOnboarding.RepositoriesService.Interface.Fakes.StubIRepositoryService()
            {
                GetRepositoryByIdInt32 = id => { return null; }
            };

            RepositoryController repositoryController = CreateRequest(HttpMethod.Get);
            // Perform
            var response = repositoryController.GetRepository(fakeRepository.RepositoryId);

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Expexted and actual status are not equal");
            var result = response.Content.ReadAsAsync<Repository>().Result;
            Assert.IsNull(result, "Result is not null");
        }
        public void Update_Repository_Test()
        {
            Repository repositoryObject = new Repository()
            {
                AllowedFileTypes = "xlsx,nc,csv",
                CreatedBy = 1,
                /// Files = null,
                CreatedOn = DateTime.Now,
                HttpDeleteUriTemplate = "http://test.com",
                HttpGetUriTemplate = "http://test.com",
                HttpIdentifierUriTemplate = "http://test.com",
                HttpPostUriTemplate = "http://test.com",
                ImpersonatingPassword = "******",
                ImpersonatingUserName = "******",
                IsActive = true,
                IsImpersonating = true,
                ModifiedBy = 1,
                ModifiedOn = DateTime.Now,
                Name = "Updated repository",
                RepositoryId = 12,
                UserAgreement = "Test Agreement1",
                BaseRepositoryId = 1,
                IsVisibleToAll = true,
                RepositoryMetadata = new List<RepositoryMetadata>()
            };

            var result = this.repsoitoryService.AddUpdateRepository(repositoryObject);

            Assert.IsTrue(result);
        }
        public void Get_Repository_By_Id_When_Model_State_Invalid()
        {
            Repository fakeRepository = new Repository() { RepositoryId = 3, CreatedBy = 1, BaseRepositoryId = 1, IsActive = true };

            this.repositoryService = new Microsoft.Research.DataOnboarding.RepositoriesService.Interface.Fakes.StubIRepositoryService(); 

            RepositoryController repositoryController = CreateRequest(HttpMethod.Get);
            repositoryController.ModelState.AddModelError("Invalid", "Invalid Model State");
            // Perform
            var response = repositoryController.GetRepository(fakeRepository.RepositoryId);

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest, "Expexted and actual status are not equal");
            var result = response.Content.ReadAsAsync<HttpError>().Result;
            Assert.IsNotNull(result, "Result is null");
        }
        public void AddUpdateRepository_ShouldThrowNullRefernceException_WhenTokenExpiresOnIsNull()
        {
            Repository repositoryObject = new Repository()
            {
                IsImpersonating = true,
                BaseRepositoryId = 2,
                AccessToken = "AccessToken",
                RefreshToken = "RefreshToken"
            };

            try
            {
                var result = this.repsoitoryService.AddUpdateRepository(repositoryObject);
                Assert.Fail("Should have exceptioned above!");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(ArgumentNullException));
                Assert.IsTrue(ex.Message.ToString().Contains("tokenExpiresOn"));
            }
        }
        public void Get_Repository_By_Id_When_Invalid_Repository_Id()
        {
            Repository fakeRepository = new Repository() { RepositoryId = -2 };

            this.repositoryService = new Microsoft.Research.DataOnboarding.RepositoriesService.Interface.Fakes.StubIRepositoryService()
            {
                GetRepositoryByIdInt32 = id => { throw new ArgumentNullException("InvalidRepositoryId"); }
            };

            RepositoryController repositoryController = CreateRequest(HttpMethod.Get);

            // Perform
            var response = repositoryController.GetRepository(fakeRepository.RepositoryId);

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest, "Expexted and actual status are not equal");
            var result = response.Content.ReadAsAsync<HttpError>().Result;
            Assert.AreEqual(result.Message, "Invalid repository id.", "Result is not as expected");
        }
        public void Initialize()
        {
            // Unit of work code
            this.unitOfWork =
                new StubIUnitOfWork()
                {
                    Commit = () => { return; }
                };

            // User repository
            this.userRepository = new StubIUserRepository()
            {
                GetUserbyUserIdInt32 = (userId) =>
                {
                    List<UserRole> userRoles = new List<UserRole>();
                    userRoles.Add(new UserRole() { Role = null, RoleId = 1, UserId = userId, UserRoleId = 1 });
                    User userNew = new User() { CreatedOn = DateTime.UtcNow, EmailId = "*****@*****.**", FirstName = "First", IdentityProvider = "identity", IsActive = true, LastName = "Last", MiddleName = "midele", ModifiedOn = DateTime.UtcNow, NameIdentifier = "nameIdentifier", Organization = "Test Org", UserAttributes = null, UserId = userId, UserRoles = userRoles };
                    return userNew;
                }
            };

            // File repository implementation
            this.fileRepository = new StubIFileRepository()
            {
                GetFilesByRepositoryInt32 = (repositoryId) =>
                    {
                        File fileToAdd = new File() { Citation = "Citation 1", CreatedBy = 1, CreatedOn = DateTime.Now, Description = "Document 1", FileAttributes = null, FileColumns = null, FileId = 1, FileQualityChecks = null, Identifier = "asdahgsdfsghadfsghad", isDeleted = false, MimeType = "Mime type 1", ModifiedBy = 1, ModifiedOn = DateTime.Now, Name = "Document One", Repository = null, RepositoryId = 1, Size = 20.90, Status = "Uploaded", Title = "Document 1" };
                        File fileToAdd1 = new File() { Citation = "Citation 2", CreatedBy = 1, CreatedOn = DateTime.Now, Description = "Document 2", FileAttributes = null, FileColumns = null, FileId = 2, FileQualityChecks = null, Identifier = "wrwe23423ewr", isDeleted = false, MimeType = "Mime type 2", ModifiedBy = 1, ModifiedOn = DateTime.Now, Name = "Document Two", Repository = null, RepositoryId = 1, Size = 20.90, Status = "Posted", Title = "Document 2" };

                        List<File> lstFiles = new List<File>();

                        lstFiles.Add(fileToAdd);
                        lstFiles.Add(fileToAdd);

                        return lstFiles;
                    },
                DeleteFileInt32StringBooleanBoolean = (fileId, status, isFileData, isHardDelete) =>
                    {
                        return true;
                    },
                UpdateFileFile = (modifiedFile) =>
                    {
                        return null;
                    }
            };

            // Repository details fake implementation
            this.repositoryDetails = new StubIRepositoryDetails()
            {
                RetrieveRepositories = () =>
                    {
                        Repository repositoryObject = new Repository()
                        {
                            AllowedFileTypes = "xlsx,nc,csv",
                            CreatedBy = 1,
                            /// Files = null,
                            CreatedOn = DateTime.Now,
                            HttpDeleteUriTemplate = "http://test.com",
                            HttpGetUriTemplate = "http://test.com",
                            HttpIdentifierUriTemplate = "http://test.com",
                            HttpPostUriTemplate = "http://test.com",
                            ImpersonatingPassword = "******",
                            ImpersonatingUserName = "******",
                            IsActive = true,
                            IsImpersonating = true,
                            ModifiedBy = 1,
                            ModifiedOn = DateTime.Now,
                            Name = "Repository1",
                            RepositoryId = 1,
                            UserAgreement = "Test Agreement1",
                            BaseRepositoryId = 1,
                            IsVisibleToAll = true
                        };

                        Repository repositoryObject1 = new Repository()
                        {
                            AllowedFileTypes = "xlsx,csv",
                            CreatedBy = 1,
                            //Files = null,
                            CreatedOn = DateTime.Now,
                            HttpDeleteUriTemplate = "http://gmail.com",
                            HttpGetUriTemplate = "http://gmail.com",
                            HttpIdentifierUriTemplate = "http://gmail.com",
                            HttpPostUriTemplate = "http://gmail.com",
                            ImpersonatingPassword = "******",
                            ImpersonatingUserName = "******",
                            IsActive = true,
                            IsImpersonating = true,
                            ModifiedBy = 1,
                            ModifiedOn = DateTime.Now,
                            Name = "Repository2",
                            RepositoryId = 2,
                            UserAgreement = "Test Agreement1",
                            BaseRepositoryId = 1,
                            IsVisibleToAll = true
                        };

                        List<Repository> lstRep = new List<Repository>();
                        lstRep.Add(repositoryObject);
                        lstRep.Add(repositoryObject1);
                        return lstRep;
                    },
                RetrieveRepositoryTypes = () =>
                    {
                        List<BaseRepository> lstBaseRep = new List<BaseRepository>();
                        lstBaseRep.Add(new BaseRepository() { BaseRepositoryId = 1, Name = "Merritt" });
                        lstBaseRep.Add(new BaseRepository() { BaseRepositoryId = 2, Name = "Sky" });
                        return lstBaseRep;
                    },
                AddRepositoryRepository = (repository) =>
                    {
                        repository.RepositoryId = 10;
                        repository.Name = "From add method";
                        return repository;
                    },
                UpdateRepositoryRepository = (repository) =>
                    {
                        repository.Name = "From update method";
                        return repository;
                    },
                GetRepositoryByIdInt32 = (repositoryId) =>
                    {
                        Repository repositoryObject = new Repository()
                        {
                            AllowedFileTypes = "xlsx,nc,csv",
                            CreatedBy = 1,
                            /// Files = null,
                            CreatedOn = DateTime.Now,
                            HttpDeleteUriTemplate = "http://test.com",
                            HttpGetUriTemplate = "http://test.com",
                            HttpIdentifierUriTemplate = "http://test.com",
                            HttpPostUriTemplate = "http://test.com",
                            ImpersonatingPassword = "******",
                            ImpersonatingUserName = "******",
                            IsActive = true,
                            IsImpersonating = true,
                            ModifiedBy = 1,
                            ModifiedOn = DateTime.Now,
                            Name = "Get by id method",
                            RepositoryId = repositoryId,
                            UserAgreement = "Test Agreement1",
                            BaseRepositoryId = 1,
                            IsVisibleToAll = true
                        };

                        return repositoryObject;
                    },
                GetBaseRepositoryNameInt32 = (baseRepositoryId) =>
                {
                    return "base rep Name";
                },
                DeleteRepositoryInt32 = (repositoryId) =>
                    {
                        Repository repositoryObject = new Repository()
                        {
                            AllowedFileTypes = "xlsx,nc,csv",
                            CreatedBy = 1,
                            /// Files = null,
                            CreatedOn = DateTime.Now,
                            HttpDeleteUriTemplate = "http://test.com",
                            HttpGetUriTemplate = "http://test.com",
                            HttpIdentifierUriTemplate = "http://test.com",
                            HttpPostUriTemplate = "http://test.com",
                            ImpersonatingPassword = "******",
                            ImpersonatingUserName = "******",
                            IsActive = true,
                            IsImpersonating = true,
                            ModifiedBy = 1,
                            ModifiedOn = DateTime.Now,
                            Name = "Delete rep method",
                            RepositoryId = repositoryId,
                            UserAgreement = "Test Agreement1",
                            BaseRepositoryId = 1,
                            IsVisibleToAll = true
                        };

                        return repositoryObject;
                    },
                GetRepositoryByNameString = (repositoryName) =>
                    {
                        Repository repositoryObject = new Repository()
                        {
                            AllowedFileTypes = "xlsx,nc,csv",
                            CreatedBy = 1,
                            /// Files = null,
                            CreatedOn = DateTime.Now,
                            HttpDeleteUriTemplate = "http://test.com",
                            HttpGetUriTemplate = "http://test.com",
                            HttpIdentifierUriTemplate = "http://test.com",
                            HttpPostUriTemplate = "http://test.com",
                            ImpersonatingPassword = "******",
                            ImpersonatingUserName = "******",
                            IsActive = true,
                            IsImpersonating = true,
                            ModifiedBy = 1,
                            ModifiedOn = DateTime.Now,
                            Name = repositoryName,
                            RepositoryId = 12,
                            UserAgreement = "Test Agreement1",
                            BaseRepositoryId = 1,
                            IsVisibleToAll = true
                        };

                        return repositoryObject;
                    }
            };

            this.repsoitoryService = new RepositoriesService.RepositoryService(repositoryDetails, unitOfWork, userRepository, fileRepository);
        }
Exemple #32
0
        /// <summary>
        /// Method to add new repository record.
        /// </summary>
        /// <param name="repository">Repository details.</param>
        /// <returns>Newly created repository.</returns>
        /// <exception cref="ArgumentException">When repository is null</exception>
        public Repository AddRepository(Repository repository)
        {
            Check.IsNotNull<Repository>(repository, "newRepository");

            return Context.Repositories.Add(repository);
        }
        public void Add_Repository_Test()
        {
            IRepositoryDetails repository = new RepositoryDetails(testDBContext);

            Repository repositoryObject = new Repository()
            {
                AllowedFileTypes = "xlsx,nc,csv",
                CreatedBy = 1,
                // Files = null,
                CreatedOn = DateTime.Now,
                HttpDeleteUriTemplate = "http://google.com",
                HttpGetUriTemplate = "http://google.com",
                HttpIdentifierUriTemplate = "http://google.com",
                HttpPostUriTemplate = "http://google.com",
                ImpersonatingPassword = "******",
                ImpersonatingUserName = "******",
                IsActive = true,
                IsImpersonating = true,
                ModifiedBy = 1,
                ModifiedOn = DateTime.Now,
                Name = "AddedRepository",
                RepositoryId = 3,
                UserAgreement = "Test Agreement Added",
                BaseRepositoryId = 1
            };

            AddRepository(repositoryObject);

            var addedRepository = repository.GetRepositoryById(3);

            Assert.AreEqual(addedRepository.AllowedFileTypes, repositoryObject.AllowedFileTypes);

            Assert.AreEqual(addedRepository.CreatedBy, repositoryObject.CreatedBy);

            Assert.AreEqual(addedRepository.CreatedOn, repositoryObject.CreatedOn);

            Assert.AreEqual(addedRepository.HttpDeleteUriTemplate, repositoryObject.HttpDeleteUriTemplate);

            Assert.AreEqual(addedRepository.HttpGetUriTemplate, repositoryObject.HttpGetUriTemplate);

            Assert.AreEqual(addedRepository.HttpIdentifierUriTemplate, repositoryObject.HttpIdentifierUriTemplate);

            Assert.AreEqual(addedRepository.HttpPostUriTemplate, repositoryObject.HttpPostUriTemplate);

            Assert.AreEqual(addedRepository.ImpersonatingPassword, repositoryObject.ImpersonatingPassword);

            Assert.AreEqual(addedRepository.ImpersonatingUserName, repositoryObject.ImpersonatingUserName);

            Assert.AreEqual(addedRepository.IsActive, repositoryObject.IsActive);

            Assert.AreEqual(addedRepository.IsImpersonating, repositoryObject.IsImpersonating);

            Assert.AreEqual(addedRepository.ModifiedBy, repositoryObject.ModifiedBy);

            Assert.AreEqual(addedRepository.ModifiedOn, repositoryObject.ModifiedOn);

            Assert.AreEqual(addedRepository.Name, repositoryObject.Name);

            Assert.AreEqual(addedRepository.RepositoryId, repositoryObject.RepositoryId);

            Assert.AreEqual(addedRepository.UserAgreement, repositoryObject.UserAgreement);
        }
 private void AddRepository(Repository repo)
 {
     IRepositoryDetails repository = new RepositoryDetails(testDBContext);
     repository.AddRepository(repo);
     testDBContext.Commit();
 }
        private void AddDefaultData()
        {
            User newUser = new User()
            {
                NameIdentifier = "s0Me1De9Tf!Er$tRing",
                FirstName = "SomeFirstName",
                MiddleName = "SomeMiddleName",
                LastName = "SomeLastName",
                IdentityProvider = "Windows Live",
                Organization = "SomeOrganization",
                EmailId = "*****@*****.**",
                CreatedOn = DateTime.Now,
                ModifiedOn = DateTime.Now,
                IsActive = true,
                UserAttributes = null
            };

            // User with userid 1
            AddUser(newUser);

            // Adding metadata types
            MetadataType metaType = new MetadataType() { MetadataTypeId = 1, Name = "Text", Status = true };
            MetadataType metaType1 = new MetadataType() { MetadataTypeId = 2, Name = "Numaric", Status = true };
            MetadataType metaType2 = new MetadataType() { MetadataTypeId = 3, Name = "Email", Status = true };

            AddMetaDataType(metaType);
            AddMetaDataType(metaType1);
            AddMetaDataType(metaType2);

            BaseRepository baseRepo = new BaseRepository() { BaseRepositoryId = 1, Name = "Merrit" };

            AddBaseRepository(baseRepo);

            Repository repositoryObject = new Repository()
            {
                AllowedFileTypes = "xlsx,nc,csv",
                CreatedBy = 1,
                /// Files = null,
                CreatedOn = DateTime.Now,
                HttpDeleteUriTemplate = "http://google.com",
                HttpGetUriTemplate = "http://google.com",
                HttpIdentifierUriTemplate = "http://google.com",
                HttpPostUriTemplate = "http://google.com",
                ImpersonatingPassword = "******",
                ImpersonatingUserName = "******",
                IsActive = true,
                IsImpersonating = true,
                ModifiedBy = 1,
                ModifiedOn = DateTime.Now,
                Name = "Repository1",
                RepositoryId = 1,
                UserAgreement = "Test Agreement1",
                BaseRepositoryId = 1,
                IsVisibleToAll = true
            };

            Repository repositoryObject1 = new Repository()
            {
                AllowedFileTypes = "xlsx,csv",
                CreatedBy = 1,
                //Files = null,
                CreatedOn = DateTime.Now,
                HttpDeleteUriTemplate = "http://gmail.com",
                HttpGetUriTemplate = "http://gmail.com",
                HttpIdentifierUriTemplate = "http://gmail.com",
                HttpPostUriTemplate = "http://gmail.com",
                ImpersonatingPassword = "******",
                ImpersonatingUserName = "******",
                IsActive = true,
                IsImpersonating = true,
                ModifiedBy = 1,
                ModifiedOn = DateTime.Now,
                Name = "Repository2",
                RepositoryId = 2,
                UserAgreement = "Test Agreement1",
                BaseRepositoryId = 1,
                IsVisibleToAll = true
            };

            // Adding 2 new repositories
            AddRepository(repositoryObject);
            AddRepository(repositoryObject1);

            // Adding repository metadata and metadata fields
            RepositoryMetadata repMetadata = new RepositoryMetadata() { CreatedBy = 1, CreatedOn = DateTime.UtcNow, IsActive = true, ModifiedBy = 1, ModifiedOn = DateTime.UtcNow, Name = "Merrit Test metadata", RepositoryId = 1, RepositoryMetadataId = 1, RepositoryMetadataFields = null };

            AddRepositoryMetadata(repMetadata);

            RepositoryMetadataField repMDField = new RepositoryMetadataField() { Description = "Create Name", IsRequired = true, Mapping = "Test Mapping", MetadataTypeId = 1, Name = "Create Name", Order = 1, Range = "", RepositoryMetadataFieldId = 1, RepositoryMetadataId = 1 };
            RepositoryMetadataField repMDField1 = new RepositoryMetadataField() { Description = "Create Phone", IsRequired = true, Mapping = "Test Mapping", MetadataTypeId = 1, Name = "Create Phone", Order = 2, Range = "", RepositoryMetadataFieldId = 2, RepositoryMetadataId = 1 };
            RepositoryMetadataField repMDField2 = new RepositoryMetadataField() { Description = "Create Email", IsRequired = true, Mapping = "Test Mapping", MetadataTypeId = 1, Name = "Create Email", Order = 3, Range = "", RepositoryMetadataFieldId = 3, RepositoryMetadataId = 1 };

            AddRepositoryMetadataFields(repMDField);
            AddRepositoryMetadataFields(repMDField1);
            AddRepositoryMetadataFields(repMDField2);
        }