Exemplo n.º 1
0
        public ObjectResult ApiBattleShipPost(int boardId,
                                              BattleShipToBeCreatedRequest battleShipToBeCreatedRequest)
        {
            logger.LogDebug("Start - Request for new battle ship");

            ObjectResult result = null;

            var battleShip = BattleShipFactory(boardId, battleShipToBeCreatedRequest);

            // prep board to ask question
            var board = boardRepo.Get(boardId);
            // ask board whether given battle ship can be added
            var battleShipAssociation = board.CanAddBattleShip(battleShip);

            // if can be associated save the battle ship to database
            if (battleShipAssociation.Status == true)
            {
                var battleShipFromRepo = battleShipService
                                         .SaveBattleShip(boardId, battleShip.BattleShipBlocks);
                var successResponse = ResponseFactory.Create(battleShipFromRepo);

                result = CreatedAtAction(nameof(ApiBattleShipGet),
                                         new { boardId, id = successResponse.Id }, successResponse);
            }
            else
            {
                // 404 Error
                result = new BadRequestObjectResult(battleShipAssociation);
            }

            logger.LogDebug("End - Request for new battle ship");

            return(result);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var responseList = new List <string>
            {
                "TABLE|10|Item Id 10",
                "ARTICLE|ABCCDEE|true|2,5",
                "TABLE|15|Item Id 15",
                "TABLE|20|Item Id 20",
                "CALENDAR|01/05/2016 14:00|Meeting",
                "ARTICLE|9388d99|false|0,20",
                "CALENDAR|06/02/2017 17:00|Buy more Redbull"
            };

            Console.WriteLine("Processing list: ");
            Console.WriteLine();

            var responses = responseList.Select(responseString => ResponseFactory.Create(responseString));

            // If you want to process the responses
            ProcessTableResponses(responses.OfType <TableResponse>());
            ProcessArticleResponses(responses.OfType <ArticleResponse>());
            ProcessCalendarResponses(responses.OfType <CalendarResponse>());

            // If you just want the DTOs
            var tableDtos    = responses.OfType <TableResponse>().Select(r => r.GetValue());
            var articleDtos  = responses.OfType <ArticleResponse>().Select(r => r.GetValue());
            var calendarDtos = responses.OfType <CalendarResponse>().Select(r => r.GetValue());

            Console.WriteLine();
            Console.Write("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 3
0
        public ObjectResult ApiBoardPost()
        {
            logger.LogDebug("Start - Request for new board");

            var board         = new Board();
            var boardFromRepo = boardRepo.Create(board);
            var blocks        = Enumerable.Range(
                boardFromRepo.FirstBlockNumber,
                boardFromRepo.LastBlockNumber)
                                .Select(n => new Block
            {
                BoardId = boardFromRepo.Id,
                Number  = n
            })
                                .ToList();
            var blocksFromRepo = blockRepo.CreateBlocksForBoard(blocks);

            boardFromRepo = boardRepo.Get(boardFromRepo.Id);
            var response = ResponseFactory.Create(boardFromRepo);

            logger.LogDebug("End - Request for new board");

            return(CreatedAtAction(nameof(ApiBoardGet),
                                   new { id = boardFromRepo.Id }, response));
        }
Exemplo n.º 4
0
        // 1400.02.14
        // send encrypted message and get encrypted message
        public async static Task <Response <TResponse> > EncryptedHttpPostAsync <TResponse>(string url, object parameter, WebProxy proxy, string encPubKey, string decPriKey) where TResponse : class
        {
            try
            {
                var message = EncryptedMessage.Create(parameter, encPubKey);

                //var response = await NetHelper.HttpPostAsync<EncryptedMessage>(url, message, null, proxy);
                var response = await NetHelper.HttpPostAsync <EncryptedMessage>(new HttpParameters()
                {
                    Address = url, Data = message, Proxy = proxy
                });

                if (response.HasNotNullResult())
                {
                    return(ResponseFactory.Create <TResponse>(response.Result.Decrypt <TResponse>(decPriKey)));
                }
                else
                {
                    return(ResponseFactory.CreateError <TResponse>(response.ErrorMessage));
                }
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <TResponse>(ex.Message));
            }
        }
Exemplo n.º 5
0
        public static Response <string> HttpGetString(string address, string contentType = contentTypeJson, WebProxy proxy = null)
        {
            try
            {
                //WebClient client = new WebClient();

                //client.Headers.Add(HttpRequestHeader.ContentType, contentType);
                //client.Headers.Add(HttpRequestHeader.UserAgent, "application!");

                //client.Encoding = Encoding.UTF8;

                //if (proxy?.Address != null)
                //{
                //    client.Proxy = proxy;
                //}
                var client = CreateWebClient(contentType, Encoding.UTF8, proxy, bearer: null);

                var stringResult = client.DownloadString(address);

                return(ResponseFactory.Create(stringResult));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <string>(ex.Message));
            }
        }
Exemplo n.º 6
0
        public static Response <T> HttpGet <T>(string address, Encoding encoding = null, WebProxy proxy = null, string bearer = null, string contentType = contentTypeJson) where T : class
        {
            try
            {
                //WebClient client = new WebClient();

                //client.Headers.Add(HttpRequestHeader.ContentType, contentType);
                //client.Headers.Add(HttpRequestHeader.UserAgent, "application!");

                //client.Encoding = encoding;

                //if (proxy?.Address != null)
                //{
                //    client.Proxy = proxy;
                //}
                var client = CreateWebClient(contentType, encoding, proxy, bearer);

                var stringResult = client.DownloadString(address);

                return(ResponseFactory.Create(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(stringResult)));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <T>(ex.Message));
            }
        }
Exemplo n.º 7
0
        public void AddServiceVersion_DoesNotAddServiceVersion_IfResponseStatusCodeIsOtherThanNoContent()
        {
            // Arrange
            var response = ResponseFactory.Create(StatusCodes.Status200OK);

            // Act
            ResultHelpers.AddServiceVersion(response, () => _version);

            // Assert
            Assert.False(response.Headers.ContainsKey(ODataVersionConstraint.ODataServiceVersionHeader));
        }
Exemplo n.º 8
0
        public void AddEntityId_DoesNotAddEntityId_IfResponseStatusCodeIsOtherThanNoContent()
        {
            // Arrange
            var response = ResponseFactory.Create(StatusCodes.Status200OK);

            // Act
            ResultHelpers.AddEntityId(response, () => _entityId);

            // Assert
            Assert.False(response.Headers.ContainsKey(ResultHelpers.EntityIdHeaderName));
        }
Exemplo n.º 9
0
        public IActionResult ApiBoardGet(int id)
        {
            logger.LogDebug($"Start - Request for board {id}");

            var board    = boardRepo.Get(id);
            var response = ResponseFactory.Create(board);

            logger.LogDebug($"End - Request for board {id}");

            return(Ok(response));
        }
Exemplo n.º 10
0
        public void Promises_are_kept()
        {
            var stream  = new Subject <Response>();
            var factory = new ResponseFactory(stream, NullLogger <ResponseFactory> .Instance);

            var future1 = factory.Create <int>();
            var future2 = factory.Create <int>();
            var future3 = factory.Create <int>();

            stream.OnNext(new Response <int>(future1.Id, new[] { 123 }));
            stream.OnNext(new Response <int>(future2.Id, new[] { 234, 345 }));

            future1.Task.IsCompleted.Should().BeTrue();
            future1.Task.Result.Result.Should().BeEquivalentTo(new[] { 123 });

            future2.Task.IsCompleted.Should().BeTrue();
            future2.Task.Result.Result.Should().BeEquivalentTo(new[] { 234, 345 });

            future3.Task.IsCompleted.Should().BeFalse();
        }
        public IActionResult ApiAttackGet(int boardId, int id)
        {
            logger.LogDebug($"Start - Request for attack {id}");

            var attack   = attackRepo.Get(boardId, id);
            var response = ResponseFactory.Create(attack);

            logger.LogDebug($"End - Request for attack {id}");

            return(Ok(response));
        }
Exemplo n.º 12
0
 protected virtual DataResponse <T> CreateResponse()
 {
     if (ResponseFactory != null)
     {
         return(ResponseFactory.Create <T>());
     }
     else
     {
         return(new DataResponse <T>());
     }
 }
Exemplo n.º 13
0
        public IActionResult ApiBattleShipGet(int boardId, int id)
        {
            logger.LogDebug($"Start - Request for battle ship {id}");

            var battleShip = battleShipRepo.Get(boardId, id);
            var response   = ResponseFactory.Create(battleShip);

            logger.LogDebug($"End - Request for battle ship {id}");

            return(Ok(response));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> GetShorted([FromBody] UrlContract contract)
        {
            if (!_validator.Validate(contract.Url))
            {
                return(Ok(ResponseFactory.Create(false, "Wrong url format")));
            }

            var hashedValue = _hashProvider.GetHashed(contract.Url);
            await _linkRepository.AddEntry(hashedValue, contract.Url);

            return(Ok(ResponseFactory.Create(true, $"{Request.Scheme}://{Request.Host}/{hashedValue}")));
        }
Exemplo n.º 15
0
        public static Response <T> HttpPost <T>(HttpParameters parameters) where T : class
        {
            try
            {
                var result = HttpPostString(parameters);

                return(ResponseFactory.Create <T>(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(result.Result)));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <T>(ex.GetFullMessage()));
            }
        }
Exemplo n.º 16
0
        public void Shoud_Create_FailedResponse_WithOut_Data(string message)
        {
            // Arrange

            // Act
            var factory  = new ResponseFactory();
            var response = factory.Create(message);

            // Assert
            response.Success.Should().Be(false);
            response.Message.Should().Be(message);

            response.As <SuccessfulResponse <object> >().Should().Be(default);
Exemplo n.º 17
0
        public void AddEntityId_AddsEntityId_IfResponseStatusCodeIsNoContent()
        {
            // Arrange
            var response = ResponseFactory.Create(StatusCodes.Status204NoContent);

            // Act
            ResultHelpers.AddEntityId(response, () => _entityId);

            // Assert
            var entityIdHeaderValues = response.Headers[ResultHelpers.EntityIdHeaderName].ToList();

            Assert.Single(entityIdHeaderValues);
            Assert.Equal(_entityId.ToString(), entityIdHeaderValues.Single());
        }
Exemplo n.º 18
0
        public void AddServiceVersion_AddsODataVersion_IfResponseStatusCodeIsNoContent()
        {
            // Arrange
            var response = ResponseFactory.Create(StatusCodes.Status204NoContent);

            // Act
            ResultHelpers.AddServiceVersion(response, () => _version);

            // Assert
            var versionHeaderValues = response.Headers[ODataVersionConstraint.ODataServiceVersionHeader].ToList();

            Assert.Single(versionHeaderValues);
            Assert.Equal(_version, versionHeaderValues.Single());
        }
Exemplo n.º 19
0
        public static async Task <Response <string> > HttpPostXmlAsync(string address, string xmlData, Encoding encoding, WebProxy proxy = null)
        {
            try
            {
                var client = CreateWebClient(contentTypeXml, encoding, proxy);

                var stringResult = await client.UploadStringTaskAsync(address, xmlData);

                return(ResponseFactory.Create <string>(stringResult));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <string>(ex.Message));
            }
        }
Exemplo n.º 20
0
        public void AddEntityId_DoesNotAddEntityId_IfResponseStatusCodeIsOtherThanNoContent()
        {
            // Arrange
            var response = ResponseFactory.Create(HttpStatusCode.OK);

            // Act
            ResultHelpers.AddEntityId(response, () => _entityId);

            // Assert
#if NETCORE
            Assert.False(response.Headers.ContainsKey(ResultHelpers.EntityIdHeaderName));
#else
            Assert.False(response.Headers.Contains(ResultHelpers.EntityIdHeaderName));
#endif
        }
Exemplo n.º 21
0
        public static Response <bool> HttpDelete(string address, string contentType = contentTypeJson, WebProxy proxy = null, string bearerToken = null)
        {
            try
            {
                var client = CreateWebClient(contentType, Encoding.UTF8, proxy, bearer: bearerToken);

                var stringResult = client.UploadData(address, "DELETE", new byte[0]);

                return(ResponseFactory.Create(true));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <bool>(ex.Message));
            }
        }
Exemplo n.º 22
0
        public void Ids_are_allocated_quickly()
        {
            var stream  = new Subject <Response>();
            var factory = new ResponseFactory(stream, NullLogger <ResponseFactory> .Instance);
            var sw      = Stopwatch.StartNew();

            for (var i = 0; i < 10000; i++)
            {
                factory.Create <Response <int> >();
            }

            var ms = sw.Elapsed.TotalMilliseconds;

            (ms / 10000).Should().BeLessThan(0.1);
        }
Exemplo n.º 23
0
        public async Task SendAsync_ReturnsOriginalResponseIfNoObjectContent()
        {
            // Arrange
            var originalResponse = ResponseFactory.Create(HttpStatusCode.OK, "test");
            ODataNullValueMessageHandler handler = CreateHandler(originalResponse);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost/any");

            request.ODataContext().Path = new ODataPath(new EntitySetSegment(_entitySet));

            // Act
            var response = await SendToHandler(handler, request);

            // Assert
            Assert.Same(originalResponse, response);
        }
Exemplo n.º 24
0
        public void Receiving_errors_should_trigger_task_failure()
        {
            var stream  = new Subject <Response>();
            var factory = new ResponseFactory(stream, NullLogger <ResponseFactory> .Instance);

            var future = factory.Create <int>();

            stream.OnNext(new ErrorResponse(future.Id, new(234, "Foobar") ));

            future.Task.IsFaulted.Should().BeTrue();
            var exception = future.Task.Exception?.InnerException;

            exception.Should().NotBeNull()
            .And.BeOfType <YeelightException>()
            .Which.Message.Should().Be("Foobar");
        }
Exemplo n.º 25
0
        public void Ids_are_created_without_apparent_collisions()
        {
            var  stream  = new Subject <Response>();
            var  factory = new ResponseFactory(stream, NullLogger <ResponseFactory> .Instance);
            var  ids     = new HashSet <int>();
            bool result  = true;

            for (var i = 0;
                 i < 100000 && result;
                 i++, result = ids.Add(factory.Create <Response <int> >().Id))
            {
                ;
            }

            result.Should().BeTrue("collision if already in set");
        }
Exemplo n.º 26
0
        public void AddEntityId_AddsEntityId_IfResponseStatusCodeIsNoContent()
        {
            // Arrange
            var response = ResponseFactory.Create(HttpStatusCode.NoContent);

            // Act
            ResultHelpers.AddEntityId(response, () => _entityId);

            // Assert
#if NETCORE
            var entityIdHeaderValues = response.Headers[ResultHelpers.EntityIdHeaderName].ToList();
#else
            var entityIdHeaderValues = response.Headers.GetValues(ResultHelpers.EntityIdHeaderName).ToList();
#endif
            Assert.Single(entityIdHeaderValues);
            Assert.Equal(_entityId.ToString(), entityIdHeaderValues.Single());
        }
Exemplo n.º 27
0
        public void AddServiceVersion_AddsODataVersion_IfResponseStatusCodeIsNoContent()
        {
            // Arrange
            var response = ResponseFactory.Create(HttpStatusCode.NoContent);

            // Act
            ResultHelpers.AddServiceVersion(response, () => _version);

            // Assert
#if NETCORE
            var versionHeaderValues = response.Headers[ODataVersionConstraint.ODataServiceVersionHeader].ToList();
#else
            var versionHeaderValues = response.Headers.GetValues(ODataVersionConstraint.ODataServiceVersionHeader).ToList();
#endif
            Assert.Single(versionHeaderValues);
            Assert.Equal(_version, versionHeaderValues.Single());
        }
Exemplo n.º 28
0
        public void GivenDynamicTemplate_WhenCreatingResponseFromObject_ThenCreatesExpectedResponse()
        {
            var mockRequest = CreateMockRequestObject();

            var mockTemplate = new Mock <ITemplate>();

            mockTemplate.Setup(x => x.Response)
            .Returns("{ \"Message\": \"Captured : {{a}}, {{b}}, {{c}}\" }");

            var expectedResponse = "{ \"Message\": \"Captured : 1, 2, 3\" }";

            var factory = new ResponseFactory();

            var response = factory.Create(mockRequest.Object, mockTemplate.Object);

            Assert.That(expectedResponse, Is.EqualTo(response.Content));
        }
Exemplo n.º 29
0
        public void GivenDynamicTemplate_WhenCreatingResponseFromObjectUsingIndexes_ThenCreatesResponse()
        {
            var mockRequest = CreateMockRequestArray();

            var expected = "{ \"Message\": \"Captured : b, c, a\" }";

            var mockTemplate = new Mock <ITemplate>();

            mockTemplate.Setup(x => x.Response)
            .Returns("{ \"Message\": \"Captured : {{1}}, {{2}}, {{0}}\" }");

            var factory = new ResponseFactory();

            var response = factory.Create(mockRequest.Object, mockTemplate.Object);

            Assert.That(response.Content, Is.EqualTo(expected));
        }
Exemplo n.º 30
0
        public void GivenDynamicTemplate_WhenCreatingResponseFromNestedObject_ThenCreatesResponse()
        {
            var mockRequest = CreateNestedMockRequestObject();

            var mockTemplate = new Mock <ITemplate>();

            mockTemplate.Setup(x => x.Response)
            .Returns("{ \"Message\": \"Captured : {{String}}, {{Number}}, {{Bool}}, {{Array[1]}}, {{Nested.String}}, {{Nested.Number}}, {{Nested.Bool}}, {{Nested.Array[1]}}\" }");

            var factory = new ResponseFactory();

            var response = factory.Create(mockRequest.Object, mockTemplate.Object);

            var expected = "{ \"Message\": \"Captured : String-0, Number-0, Bool-0, Array-0, Nested-String-0, Nested-Number-0, Nested-Bool-0, Nested-Array-0\" }";

            Assert.That(response.Content, Is.EqualTo(expected));
        }