public void GetFolderPath_Returns500StatusCodeIfOneOfFoldersIsNull()
        {
            // arrange
            string currFolderId = "20";
            string userId       = "1234";
            Folder folder1      = new Folder {
                Id = "1", ParentFolderId = null, OwnerId = userId, Path = "C:\\Folder1"
            };
            Folder folder2 = null;
            Folder folder3 = new Folder {
                Id = "20", ParentFolderId = "5", OwnerId = userId, Path = "C:\\Folder1\\Folder2\\Folder3"
            };
            var mock = new Mock <IUnitOfWork>();

            mock.Setup(a => a.GetRepository <Folder>().Get("1")).Returns(folder1);
            mock.Setup(a => a.GetRepository <Folder>().Get("5")).Returns(folder2);
            mock.Setup(a => a.GetRepository <Folder>().Get("20")).Returns(folder3);
            FileSystemService service = new FileSystemService(mock.Object, _mapper);
            int expected = 500;

            // act
            StatusCodeException ex = Assert.Throws <StatusCodeException>(() => service.GetFolderPath(currFolderId, userId));

            // assert
            Assert.AreEqual(expected, ex.Data["Status code"]);
        }
        public void ChangeAccess_Returns403StatusCodeIfYouAreNotOwner()
        {
            // arrange
            string userId       = "4321";
            string currFolderId = "1";

            string[] foldersId = { "22" };
            string[] filesId   = { };

            var mock = new Mock <IUnitOfWork>();

            mock.Setup(a => a.GetRepository <Folder>().Get("1")).Returns(new Folder
            {
                Id             = "1",
                OwnerId        = "1234",
                ParentFolderId = currFolderId
            });
            mock.Setup(a => a.GetRepository <Folder>().Get("22")).Returns(new Folder
            {
                Id             = "22",
                OwnerId        = "1234",
                ParentFolderId = currFolderId
            });
            mock.Setup(a => a.GetRepository <Folder>().Find(It.IsAny <Func <Folder, bool> >())).Returns(new List <Folder>());
            mock.Setup(a => a.GetRepository <File>().Find(It.IsAny <Func <File, bool> >())).Returns(new List <File>());
            FileSystemService service = new FileSystemService(mock.Object, _mapper);
            int expected = 403;

            // act
            StatusCodeException ex = Assert.Throws <StatusCodeException>(() =>
                                                                         service.ChangeAccess(currFolderId, userId, foldersId, filesId, true));

            // assert
            Assert.AreEqual(expected, ex.Data["Status code"]);
        }
Exemple #3
0
        public void StatusCodeExceptionCodeAndMessage()
        {
            var e = new StatusCodeException(HttpStatusCode.Conflict, "lala");

            Assert.Equal(HttpStatusCode.Conflict, e.StatusCode);
            Assert.Equal("lala", e.Message);
        }
 private static void NullOrEmptyThrow(object input, StatusCodeException exception)
 {
     switch (input)
     {
     case string s when string.IsNullOrEmpty(s):
     case ICollection c when c.Count == 0:
     case null:
         throw exception;
     }
 }
Exemple #5
0
 /// <summary>
 ///  构造标准输出对象
 /// </summary>
 /// <param name="exception">微服务异常基类</param>
 /// <param name="requestId"></param>
 /// <param name="result"></param>
 /// <returns></returns>
 private PackageObjectResult BuidResult(StatusCodeException exception, Guid requestId, object result = null)
 {
     return(new PackageObjectResult(new PackageObject()
     {
         StatusCode = exception.StatusCode,
         Body = result,
         RequestId = requestId,
         Notification = exception.Message,
         Now = DateTimeOffset.Now
     }));
 }
        public void CheckEditAccess_Returns500StatusCodeIfFolderIsNull()
        {
            // arrange
            string            currUserId = "4321";
            FolderVM          folder     = null;
            var               mock       = new Mock <IUnitOfWork>();
            FileSystemService service    = new FileSystemService(mock.Object, _mapper);
            int               expected   = 500;

            // act
            StatusCodeException ex = Assert.Throws <StatusCodeException>(() => service.CheckEditAccess(folder, currUserId));

            // assert
            Assert.AreEqual(expected, ex.Data["Status code"]);
        }
Exemple #7
0
        public void HasSharedChildren_Returns404StatusCodeIfFolderDoesNotExists()
        {
            // arrange
            Folder folderFromDB = null;
            var    mock         = new Mock <IUnitOfWork>();

            mock.Setup(a => a.GetRepository <Folder>().Get("23")).Returns(folderFromDB);
            FileSystemService service = new FileSystemService(mock.Object, _mapper);
            int expected = 404;

            // act
            StatusCodeException ex = Assert.Throws <StatusCodeException>(() => service.HasSharedChildren("23"));

            // assert
            Assert.AreEqual(expected, ex.Data["Status code"]);
        }
Exemple #8
0
        public void GetFileById_Returns404StatusCodeIfFileIsNull()
        {
            // arrange
            File fileFromDB = null;
            var  mock       = new Mock <IUnitOfWork>();

            mock.Setup(a => a.GetRepository <File>().Get("23")).Returns(fileFromDB);
            FileSystemService service = new FileSystemService(mock.Object, _mapper);
            int expected = 404;

            // act
            StatusCodeException ex = Assert.Throws <StatusCodeException>(() => service.GetFileById("23"));

            // assert
            Assert.AreEqual(expected, ex.Data["Status code"]);
        }
Exemple #9
0
        public void CreateFolder_Returns500StatusCodeIfParentIsNull()
        {
            // arrange
            string   userId = "1234";
            string   name   = "newFolder";
            FolderVM folder = null;
            var      mock   = new Mock <IUnitOfWork>();

            mock.Setup(a => a.GetRepository <Folder>().Create(It.IsAny <Folder>()));
            FileSystemService service = new FileSystemService(mock.Object, _mapper);
            int expected = 500;

            // act
            StatusCodeException ex = Assert.Throws <StatusCodeException>(() => service.CreateFolder(folder, name, userId));

            // assert
            Assert.AreEqual(expected, ex.Data["Status code"]);
        }
Exemple #10
0
        public void GetElementsFromFolder_Returns404StatusCodeIfFolderIsNull()
        {
            // arrange
            string userId = "1234";
            Folder parent = null;

            var mock = new Mock <IUnitOfWork>();

            mock.Setup(a => a.GetRepository <Folder>().Get("1")).Returns(parent);
            FileSystemService service = new FileSystemService(mock.Object, _mapper);
            int expected = 404;

            // act
            StatusCodeException ex = Assert.Throws <StatusCodeException>(() =>
                                                                         service.GetElementsFromFolder(null, userId));

            // assert
            Assert.AreEqual(expected, ex.Data["Status code"]);
        }
Exemple #11
0
        /// <summary>
        /// Creates a UA fault message from an exception.
        /// </summary>
        protected virtual Exception CreateSoapFault(RequestHeader requestHeader, Exception e)
        {
            ServiceFault fault = new ServiceFault();

            fault.ResponseHeader = CreateResponseHeader(requestHeader);

            // specify a code.
            StatusCodeException sce = e as StatusCodeException;

            if (sce != null)
            {
                fault.ResponseHeader.ServiceResult = new StatusCode(sce.Code);
            }
            else
            {
                fault.ResponseHeader.ServiceResult = new StatusCode(StatusCodes.BadUnexpectedError);
            }

            // return the message for the exception (add it to the string table first and store the index in the diagnostics).
            if ((requestHeader.ReturnDiagnostics & (uint)DiagnosticsMasks.ServiceLocalizedText) != 0)
            {
                fault.ResponseHeader.StringTable.Add(e.Message);
                fault.ResponseHeader.ServiceDiagnostics.LocalizedText = fault.ResponseHeader.StringTable.Count - 1;
            }

            // return the stack trace for the exception.
            // this is really handy for debugging but is a security risk and never should be done in a production system.
            if ((requestHeader.ReturnDiagnostics & (uint)DiagnosticsMasks.ServiceAdditionalInfo) != 0)
            {
                fault.ResponseHeader.ServiceDiagnostics.AdditionalInfo = e.StackTrace;
            }

            // construct the fault code and fault reason.
            FaultCode   code   = new FaultCode(StatusCodes.GetBrowseName(fault.ResponseHeader.ServiceResult.Code), Namespaces.OpcUa);
            FaultReason reason = new FaultReason(e.Message);;

            // return the fault.
            return(new FaultException <ServiceFault>(fault, reason, code));
        }
Exemple #12
0
        public async Task <ActionResult <IList <string> > > AddToRole(Guid userId, string role)
        {
            if (!await roleManager.RoleExistsAsync(role))
            {
                throw StatusCodeException.BadRequest();
            }
            var targetUser = await GetUser(userId);

            if (targetUser == null)
            {
                return(NotFound("User not found"));
            }

            var result = await UserManager.AddToRoleAsync(targetUser, role);

            if (result.Succeeded)
            {
                return(Ok(await UserManager.GetRolesAsync(targetUser)));
            }

            return(BadRequest(string.Join(',', result.Errors.Select(e => e.Description))));
        }
        public async Task <RecaptchaResult> Check(string token, string ip)
        {
            var values = new Dictionary <string, string>
            {
                { "secret", options.Value.SecretKey },
                { "response", token },
                { "remoteip", ip }
            };

            var content = new FormUrlEncodedContent(values);

            try
            {
                var response = await httpClient.PostAsync("", content);

                var stringResponse = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <RecaptchaResult>(stringResponse));
            }
            catch (Exception ex)
            {
                throw StatusCodeException.BadRequest(ex.Message);
            }
        }
        private async Task <ActionResult <SolutionResponse> > AddSolutionFromStringRaw(string fileBody, string language, Guid exerciseId, Guid authorId, bool isAdmin = false)
        {
            if (!await context.Exercises.AnyAsync(
                    e => e.ExerciseID == exerciseId &&
                    (e.Challenge.StartTime == null || e.Challenge.StartTime <= Now) &&
                    (e.Challenge.EndTime == null || e.Challenge.EndTime >= Now)))
            {
                throw StatusCodeException.Conflict("Not found started challenge and exercise");
            }

            if (!isAdmin)
            {
                var lastSendingDate = (await context
                                       .Solutions
                                       .Where(s => s.UserId == authorId)
                                       .Where(s => s.ExerciseId == exerciseId)
                                       .Select(s => s.SendingTime)
                                       .ToListAsync())
                                      .DefaultIfEmpty(DateTimeOffset.MinValue)
                                      .Max();

                if ((Now - lastSendingDate) < TimeSpan.FromMinutes(1))
                {
                    throw StatusCodeException.TooManyRequests;
                }

                var oldSolution = await context
                                  .Solutions
                                  .Where(s => s.UserId == authorId)
                                  .Where(s => s.Raw == fileBody)
                                  .Where(s => s.ExerciseId == exerciseId)
                                  .FirstOrDefaultAsync();

                if (oldSolution != null)
                {
                    return(mapper.Map <SolutionResponse>(mapper.Map <SolutionInternalModel>(oldSolution)));
                }
            }

            Solution solution = new Solution()
            {
                Raw         = fileBody,
                Language    = language,
                ExerciseId  = exerciseId,
                UserId      = authorId,
                Status      = SolutionStatus.InQueue,
                SendingTime = DateTimeOffset.UtcNow
            };

            await context.Solutions.AddAsync(solution);

            await context.SaveChangesAsync();

            if (await context.TestData.AnyAsync(td => td.ExerciseDataGroup.ExerciseId == exerciseId))
            {
                logger.LogInformation($"Put solution {solution.Id} to test queue");
                queue.PutInQueue(solution.Id);
            }
            else
            {
                logger.LogWarning($"No exercise data for {solution.Id}, no put to test queue");
            }

            return(mapper.Map <SolutionResponse>(mapper.Map <SolutionInternalModel>(solution)));
        }
Exemple #15
0
        public void StatusCodeExceptionDefaultCode()
        {
            var e = new StatusCodeException();

            Assert.Equal(HttpStatusCode.InternalServerError, e.StatusCode);
        }
Exemple #16
0
        public void StatusCodeExceptionMessageConstructor()
        {
            var e = new StatusCodeException("hello");

            Assert.Equal("hello", e.Message);
        }