public HttpResponseMessage SignOut([FromUri] string callback)
        {
            diagnostics.WriteInformationTrace(TraceEventId.InboundParameters,
                                              "Client callback uri:{0}", callback);

            if (string.IsNullOrEmpty(callback))
            {
                diagnostics.WriteErrorTrace(TraceEventId.Exception, "callback parameter is null or empty");
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(MessageStrings.Argument_Error_Message_Template, callback)));
            }

            FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
            var    acsConfig = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration;
            string wtrealm   = acsConfig.Realm;

            // construct the call back Url
            UriBuilder wreply = new UriBuilder(this.Request.RequestUri.Scheme, this.Request.RequestUri.Host);

            wreply.Path = "SignOutCallback";
            string queryparam = string.Concat("callback=", callback);

            wreply.Query = queryparam;
            string url = string.Format("{0}?wa=wsignout1.0&wreply={1}&wtrealm={2}", acsConfig.Issuer, HttpUtility.UrlEncode(wreply.ToString()), wtrealm);

            // Construct the Response
            var response = Request.CreateResponse(HttpStatusCode.Moved);

            response.Headers.Location = new Uri(url);

            diagnostics.WriteVerboseTrace(TraceEventId.OutboundParameters,
                                          "Redirect Uri to Acs logout {0}",
                                          response.Headers.Location);
            return(response);
        }
Example #2
0
        public HttpResponseMessage GetRepositories()
        {
            // 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 file service is valid
                Check.IsNotNull(this.repositoryService, "repositoryService");

                bool isAdmin = this.user.UserRoles.Any(ur => ur.Role.Name.Equals(Roles.Administrator.ToString(), StringComparison.OrdinalIgnoreCase));

                IEnumerable <RepositoryDataModel> repositoryList = this.repositoryService.RetrieveRepositories(isAdmin);

                return(Request.CreateResponse <IEnumerable <RepositoryDataModel> >(HttpStatusCode.OK, repositoryList));
            }
            catch (ArgumentNullException ane)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ane.Message));
            }
            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();
                }
                diagnostics.WriteErrorTrace(TraceEventId.Exception, "Exception:{0}", error);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
            }
        }
Example #3
0
        public async Task <HttpResponseMessage> GetQualityCheckRulesAndFileSheets(int fileId)
        {
            var fileService = fileServiceFactory.GetFileService(BaseRepositoryEnum.Default.ToString());
            Func <DM.File, bool> fileByFileIdAndUserIdFilter = f => f.FileId == fileId && f.CreatedBy == this.user.UserId && (f.isDeleted == null || f.isDeleted == false);
            var file = fileService.GetFiles(fileByFileIdAndUserIdFilter).FirstOrDefault();

            if (file == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.FileNotFound));
            }

            string fileExtension = Path.GetExtension(file.Name);

            if (!(fileExtension.Equals(Constants.XLSX, StringComparison.InvariantCultureIgnoreCase) || fileExtension.Equals(Constants.CSV, StringComparison.InvariantCultureIgnoreCase)))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, MessageStrings.QualityCheckNotSupportedErrorMessage));
            }

            bool isAdmin = this.user.UserRoles.Any(ur => ur.Role.Name.Equals(Roles.Administrator.ToString(), StringComparison.OrdinalIgnoreCase));
            QualityChecksViewModel qualityChecksViewModel = new QualityChecksViewModel();

            qualityChecksViewModel.ColumnRules = this.qcService.GetQualityCheckRules(isAdmin);
            try
            {
                qualityChecksViewModel.FileSheets = await fileService.GetDocumentSheetDetails(file);
            }
            catch (FileFormatException ex)
            {
                diagnostics.WriteErrorTrace(TraceEventId.Exception, ex);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, qualityChecksViewModel));
        }
Example #4
0
        /// <summary>
        /// Executes when Unhandled Exception is thrown.
        /// </summary>
        /// <param name="context">ActionExecuted Context</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            DiagnosticsProvider diagnostics = new DiagnosticsProvider(this.GetType());
            Exception           exception   = context.Exception;

            diagnostics.WriteErrorTrace(TraceEventId.Exception, exception);
            context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception.Message);
        }
Example #5
0
        public HttpResponseMessage GetUsersByNameIdentifier()
        {
            string         message        = string.Empty;
            string         nameIdentifier = string.Empty;
            HttpStatusCode status         = HttpStatusCode.OK;

            try
            {
                // Check if the user service is valid
                Check.IsNotNull(this.userService, "userService");
                nameIdentifier = Helpers.IdentityHelper.GetNameClaimTypeValue(this.User as ClaimsPrincipal);

                diagnostics.WriteVerboseTrace(TraceEventId.InboundParameters,
                                              "Retrieving user with name identifier:{0}",
                                              nameIdentifier);

                User retrievedUser = this.userService.GetUserWithRolesByNameIdentifier(nameIdentifier);
                return(Request.CreateResponse <UserInformation>(status, new UserInformation(retrievedUser)));
            }
            catch (ArgumentNullException ane)
            {
                if (ane.ParamName.Equals("userService"))
                {
                    message = MessageStrings.User_Service_Is_Null;
                    status  = HttpStatusCode.InternalServerError;
                }
            }
            catch (ArgumentException ae)
            {
                message = string.Format(CultureInfo.CurrentCulture, MessageStrings.Argument_Error_Message_Template, ae.ParamName);
                status  = HttpStatusCode.BadRequest;
            }
            catch (UserNotFoundException)
            {
                message = MessageStrings.User_Not_Found;
                status  = HttpStatusCode.NotFound;
                diagnostics.WriteErrorTrace(TraceEventId.Exception,
                                            "User with nameidentifier {0} not found",
                                            nameIdentifier);
            }

            return(Request.CreateErrorResponse(status, message));
        }
        public HttpResponseMessage AuthorizeUser()
        {
            try
            {
                // Check if OAuthCode exists if not then redict to Windows Live
                if (!this.HasOAuthCode())
                {
                    diagnostics.WriteInformationTrace(TraceEventId.Flow, "Redirecting to live");

                    // Retreive the call back param
                    string callBackUrl         = this.Request.GetQueryNameValuePairs().Where(p => p.Key == "callBackUrl").FirstOrDefault().Value;
                    string windowsLiveLoginUrl = this.GetWindowsLiveLoginUrl(callBackUrl);

                    // Construct the Response
                    var response = Request.CreateResponse(HttpStatusCode.Moved);
                    response.Headers.Location = new Uri(windowsLiveLoginUrl);

                    return(response);
                }
                else
                {
                    diagnostics.WriteInformationTrace(TraceEventId.Flow, "Call back from live");

                    string code        = this.Request.GetQueryNameValuePairs().Where(p => p.Key == SkyDriveConstants.OAuth_Code).FirstOrDefault().Value;
                    string callBackUrl = this.Request.GetQueryNameValuePairs().Where(p => p.Key == "callBackUrl").FirstOrDefault().Value;

                    // Get the AccessToken and Refresh Token by calling WindowsLive rest API
                    OAuthToken token = GetWindowsLiveTokens(code, callBackUrl);

                    diagnostics.WriteInformationTrace(TraceEventId.Flow, "Redirecting to client");

                    var    response          = Request.CreateResponse(HttpStatusCode.Moved);
                    string clientCallBackUrl = AppendAuthTokensToCallBackUrl(token, callBackUrl);
                    response.Headers.Location = new Uri(clientCallBackUrl);
                    return(response);
                }
            }
            catch (Exception ex)
            {
                diagnostics.WriteErrorTrace(TraceEventId.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));
            }
        }
Example #7
0
        protected void Application_Error(object sender, EventArgs e)
        {
            // Get the error details
            Exception ex = Server.GetLastError();

            // Check exception type and default Http 500 (internal server error)
            Response.StatusCode = (ex is HttpException) ? (ex as HttpException).GetHttpCode() : (int)HttpStatusCode.InternalServerError;

            // Log exception
            DiagnosticsProvider diagnostics = new DiagnosticsProvider(this.GetType());
            string error = string.Join("\n", "Unhandled Exception: ", ex.ToString());

            diagnostics.WriteErrorTrace(TraceEventId.Exception, error);

            // Clear buffers
            Server.ClearError();
            Response.End();
        }
Example #8
0
        public HttpResponseMessage AddUpdateAuthToken(AuthToken token)
        {
            try
            {
                // Create file service instance
                Repository repository = this.repositoryService.GetRepositoryById(token.RespositoryId);
                if (null == repository)
                {
                    diagnostics.WriteErrorTrace(TraceEventId.Exception, "Repository is null");
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Invalid_Repository_id));
                }
                token.UserId = this.user.UserId;
                this.userService.AddUpdateAuthToken(token);
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (ArgumentException ex)
            {
                message = string.Format(CultureInfo.CurrentCulture, MessageStrings.Argument_Error_Message_Template, ex.ParamName);
                status  = HttpStatusCode.BadRequest;
            }

            return(Request.CreateErrorResponse(status, message));
        }
Example #9
0
        public HttpResponseMessage SaveFileLevelMetadata(int fileId, int repositoryId, IEnumerable <SaveFileLevelMetadata> saveFileLevelMetadataList)
        {
            HttpResponseMessage httpResponseMessage;

            try
            {
                Check.IsNotNull(saveFileLevelMetadataList, "saveFileLevelMetadataList");

                fileService.SaveFileLevelMetadata(fileId, repositoryId, saveFileLevelMetadataList);
                httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, true);
            }
            catch (ArgumentException ex)
            {
                diagnostics.WriteErrorTrace(TraceEventId.Exception, ex);
                message             = string.Format(CultureInfo.CurrentCulture, MessageStrings.Argument_Error_Message_Template, ex.ParamName);
                httpResponseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
            }

            return(httpResponseMessage);
        }
Example #10
0
        public HttpResponseMessage Publish(PublishMessage publishMessage)
        {
            string    message = string.Empty;
            HttpError error   = null;

            try
            {
                if (null == publishMessage)
                {
                    diagnostics.WriteErrorTrace(TraceEventId.Exception, "publishMessage null");
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(MessageStrings.Argument_Error_Message_Template, "publishMessage")));
                }

                publishMessage.UserId = this.user.UserId;

                Repository repository = this.repositoryService.GetRepositoryById(publishMessage.RepositoryId);
                if (null == repository)
                {
                    diagnostics.WriteErrorTrace(TraceEventId.Exception, "Repository is null");
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Invalid_Repository_id));
                }

                // Create file service instance
                this.fileService = this.fileServiceFactory.GetFileService(repository.BaseRepository.Name);

                File file = this.fileService.GetFileByFileId(publishMessage.FileId);
                if (null == file)
                {
                    diagnostics.WriteErrorTrace(TraceEventId.Exception, "File is null");
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Invalid_File_Id));
                }

                // Perform validations
                this.fileService.ValidateForPublish(publishMessage);

                // Publish the message to queue
                this.publishQueueService.PostFileToQueue(publishMessage);

                file.Status       = FileStatus.Inqueue.ToString();
                file.RepositoryId = repository.RepositoryId;
                file.ModifiedOn   = DateTime.UtcNow;
                // update the file status and associate repository
                this.fileService.UpdateFile(file);

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (ArgumentException argumentException)
            {
                error = new HttpError(string.Format(MessageStrings.Argument_Error_Message_Template, argumentException.ParamName));
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));
            }
            catch (MetadataValidationException metadataValidationException)
            {
                if (metadataValidationException.NotFound)
                {
                    error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Required_Field_Metadata_Not_Found_Template, metadataValidationException.FieldName));
                }
                else if (metadataValidationException.MetadataTypeNotFound)
                {
                    error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Metadata_Type_Not_Found_Template, metadataValidationException.FieldName));
                }
                else
                {
                    error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Metadata_Field_Value_Type_Mismatch_Template, metadataValidationException.FieldName));
                }

                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
            }
            catch (DataFileNotFoundException fileNotFoundException)
            {
                error = fileNotFoundException.GetHttpError(MessageStrings.FileNotFound);
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, error));
            }
            catch (RepositoryNotFoundException repositoryNotFoundException)
            {
                error = repositoryNotFoundException.GetHttpError(MessageStrings.Invalid_Repository_id);
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, error));
            }
            catch (AccessTokenNotFoundException accessTokenNotFoundException)
            {
                error = accessTokenNotFoundException.GetHttpError(MessageStrings.Access_Token_Is_Null);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
            }
            catch (FileAlreadyPublishedException fileAlreadyPublishedException)
            {
                error = fileAlreadyPublishedException.GetHttpError(MessageStrings.File_Already_Published);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
            }
        }
Example #11
0
        public async Task <HttpResponseMessage> Post(string fileName, string fileExtension, string contentType)
        {
            try
            {
                Check.IsNotEmptyOrWhiteSpace(fileName, "fileName");
                Check.IsNotEmptyOrWhiteSpace(fileExtension, "fileExtension");
                Check.IsNotEmptyOrWhiteSpace(contentType, "contentType");

                byte[] fileContent = default(byte[]);
                if (Request.Content.IsMimeMultipartContent("form-data"))
                {
                    string root = Path.GetTempPath();
                    MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(root);
                    await Request.Content.ReadAsMultipartAsync(streamProvider);

                    MultipartFileData multipartFileData = streamProvider.FileData.First();

                    /*********************************************************
                     * This API under stress can cause IO exception, for File read
                     * or Delete operation. More details @https://aspnetwebstack.codeplex.com/workitem/176
                     * Following logic retries file operations at most 3 times
                     * inducing the recommended delay in case of failure.
                     */
                    int executionDelay   = 50,
                        readRetryCount   = 3,
                        deleteRetryCount = 3;

                    // Retry mechanics for file read operation
                    while (readRetryCount-- > 0)
                    {
                        try
                        {
                            using (FileStream fileSource = new FileStream(multipartFileData.LocalFileName, FileMode.Open, FileAccess.Read))
                            {
                                fileContent = await fileSource.GetBytesAsync();
                            }
                            break;
                        }
                        catch (IOException ioe)
                        {
                            diagnostics.WriteErrorTrace(TraceEventId.Exception, ioe.ToString());
                        }
                        await Task.Delay(executionDelay);
                    }

                    // Retry mechanics for file delete operation
                    while (deleteRetryCount-- > 0)
                    {
                        try
                        {
                            await Task.Factory.StartNew(() => System.IO.File.Delete(multipartFileData.LocalFileName));

                            break;
                        }
                        catch (IOException ioe)
                        {
                            diagnostics.WriteErrorTrace(TraceEventId.Exception, ioe.ToString());
                        }
                        await Task.Delay(executionDelay);
                    }
                }
                else
                {
                    var bufferlessInputStream = HttpContext.Current.Request.GetBufferlessInputStream();
                    Check.IsNotNull(bufferlessInputStream, "HttpContext.Current.Request.GetBufferlessInputStream()");
                    fileContent = await bufferlessInputStream.GetBytesAsync();
                }

                this.fileService.ValidateForUpload(fileName, this.user.UserId);

                DataFile dataFile = new DataFile
                {
                    FileContent    = fileContent,
                    ContentType    = contentType,
                    FileName       = fileName,
                    CreatedBy      = this.user.UserId,
                    FileExtentsion = fileExtension
                };

                IFileHandler fileHandler = this.fileHandlerFactory.GetFileHandler(contentType, this.user.UserId);
                diagnostics.WriteInformationTrace(Utilities.Enums.TraceEventId.Flow, "blob-before file upload");
                var uploadedDataDetails = fileHandler.Upload(dataFile);
                diagnostics.WriteInformationTrace(Utilities.Enums.TraceEventId.Flow, "blob-after file upload");
                if (!uploadedDataDetails.Any() || uploadedDataDetails.Any(dd => dd.FileDetail.FileId == 0))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, MessageStrings.UploadFailed));
                }

                return(Request.CreateResponse <IEnumerable <DataDetail> >(HttpStatusCode.OK, uploadedDataDetails));
            }
            catch (ValidationException validationException)
            {
                HttpError error = validationException.GetHttpError(string.Format(MessageStrings.Upload_Validation_Error_Template, validationException.FileName));
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
            }
            catch (ArgumentException ex)
            {
                message = string.Format(CultureInfo.CurrentCulture, MessageStrings.Argument_Error_Message_Template, ex.ParamName);
                status  = HttpStatusCode.BadRequest;
            }

            return(Request.CreateErrorResponse(status, message));
        }