示例#1
0
        private static async Task CreateGuidAsync()
        {
            var info = new GuidInfoBase();

            Console.Write("Enter guid to create (skip generates new guid): ");
            if (ReadGuid(out System.Guid? guid))
            {
                Console.Write("Enter user name: ");
                info.User = Console.ReadLine();
                Console.Write("Enter expiration date/time (mm/dd/yyyy hh/mm/ss) or skip for 30 day default: ");
                if (ReadDateTime(out DateTime? date))
                {
                    info.Expire = date;
                    var proxy = new GuidInfosProxy(HttpClient.Instance);
                    try
                    {
                        var guidInfo = !guid.HasValue ?
                                       await proxy.CreateGuidInfoAsync(info) :
                                       await proxy.CreateOrUpdateGuidInfoAsync(guid.Value, info);

                        DisplayGuidInfo(guidInfo);
                    }
                    catch (GuidApiException <GuidApiError> ex)
                    {
                        DisplayError(ex, ex.Result);
                    }
                    catch (GuidApiException ex)
                    {
                        DisplayError(ex);
                    }
                }
            }
        }
示例#2
0
        private async static Task UpdateGuidAsync()
        {
            Console.Write("Enter guid to update: ");
            if (ReadGuid(out System.Guid? guid, false))
            {
                var info = new GuidInfoBase();
                Console.Write("Enter user name: ");
                info.User = Console.ReadLine();
                Console.Write("Enter expiration date/time (mm/dd/yyyy hh/mm/ss): ");
                if (ReadDateTime(out DateTime? date))
                {
                    info.Expire = date;
                    var proxy = new GuidInfosProxy(HttpClient.Instance);
                    try
                    {
                        var guidInfo = await proxy.CreateOrUpdateGuidInfoAsync(guid.Value, info);

                        DisplayGuidInfo(guidInfo);
                    }
                    catch (GuidApiException <GuidApiError> ex)
                    {
                        DisplayError(ex, ex.Result);
                    }
                    catch (GuidApiException ex)
                    {
                        DisplayError(ex);
                    }
                }
            }
        }
        public async Task CreateOrUpdateGuidInfo_Update()
        {
            // entity in database
            var dbEntity = new GuidInfoEntity()
            {
                Guid   = System.Guid.NewGuid(),
                User   = "******",
                Expire = new DateTime(2020, 2, 2, 2, 2, 2, DateTimeKind.Utc)
            };

            // modified properties
            var infoBase = new GuidInfoBase()
            {
                User   = "******",
                Expire = new DateTime(2022, 1, 1, 1, 1, 1, DateTimeKind.Utc)
            };

            // find entity in database
            var mockRepo = new Mock <IRepository <GuidInfoEntity> >();

            mockRepo.Setup(r => r.GetAsync(It.IsAny <Expression <Func <GuidInfoEntity, bool> > >()))
            .ReturnsAsync(new List <GuidInfoEntity>()
            {
                dbEntity
            })
            .Verifiable();

            // update it
            mockRepo.Setup(r => r.Update(It.IsAny <GuidInfoEntity>()))
            .Verifiable();

            // save it
            var mockContext = new Mock <IGuidRepositoryContext>();

            mockContext.Setup(r => r.SaveChangesAsync())
            .Returns(Task.CompletedTask)
            .Verifiable();
            mockContext.Setup(r => r.GuidInfos)
            .Returns(mockRepo.Object);

            // and invalidate cache
            var mockCache = new Mock <IEntityCache <GuidInfoEntity> >();

            mockCache.Setup(r => r.InvalidateEntityAsync(It.IsAny <string>(), dbEntity.Guid.ToString()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            var controller = new GuidInfosController(mockContext.Object, mockCache.Object, _mockClock.Object);
            var info       = await controller.CreateOrUpdateGuidInfoAsync(dbEntity.Guid, infoBase);

            Assert.IsType <ActionResult <GuidInfo> >(info);
            var value = Assert.IsType <GuidInfo>(info.Value);

            Assert.Equal(value.User, infoBase.User);
            Assert.Equal(value.Expire, infoBase.Expire);

            mockRepo.Verify();
            mockContext.Verify();
            mockCache.Verify();
        }
        public async Task CreateOrUpdateGuidInfo_Create()
        {
            // create with specific guid
            System.Guid guid     = System.Guid.NewGuid();
            var         infoBase = new GuidInfoBase()
            {
                User   = "******",
                Expire = new DateTime(2020, 2, 2, 2, 2, 2, DateTimeKind.Utc)
            };

            // make sure we do not find it in database
            var mockRepo = new Mock <IRepository <GuidInfoEntity> >();

            mockRepo.Setup(r => r.GetAsync(It.IsAny <Expression <Func <GuidInfoEntity, bool> > >()))
            .ReturnsAsync(new List <GuidInfoEntity>())
            .Verifiable();

            // so we can add it there
            mockRepo.Setup(r => r.AddAsync(It.IsAny <GuidInfoEntity>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            // and save changes
            var mockContext = new Mock <IGuidRepositoryContext>();

            mockContext.Setup(r => r.SaveChangesAsync())
            .Returns(Task.CompletedTask)
            .Verifiable();
            mockContext.Setup(r => r.GuidInfos)
            .Returns(mockRepo.Object);

            var mockCache = new Mock <IEntityCache <GuidInfoEntity> >();

            var controller = new GuidInfosController(mockContext.Object, mockCache.Object, _mockClock.Object);
            var info       = await controller.CreateOrUpdateGuidInfoAsync(guid, infoBase);

            Assert.IsType <ActionResult <GuidInfo> >(info);
            var result = Assert.IsType <CreatedAtRouteResult>(info.Result);

            Assert.Equal("GetGuidInfo", result.RouteName);
            Assert.Equal((int)HttpStatusCode.Created, result.StatusCode);
            var value = Assert.IsType <GuidInfo>(result.Value);

            Assert.Equal(value.User, infoBase.User);
            Assert.Equal(value.Expire, infoBase.Expire);
            Assert.Equal(value.Guid, guid.ToString("N").ToUpper());

            mockRepo.Verify();
            mockContext.Verify();
        }
        public async Task CreateGuidInfo_DefaultExpire()
        {
            // do not specify expiration date
            var infoBase = new GuidInfoBase()
            {
                User = "******"
            };

            // we are going to add to database
            var mockRepo = new Mock <IRepository <GuidInfoEntity> >();

            mockRepo.Setup(r => r.AddAsync(It.IsAny <GuidInfoEntity>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            // and save changes
            var mockContext = new Mock <IGuidRepositoryContext>();

            mockContext.Setup(r => r.SaveChangesAsync())
            .Returns(Task.CompletedTask)
            .Verifiable();
            mockContext.Setup(r => r.GuidInfos)
            .Returns(mockRepo.Object);

            var mockCache = new Mock <IEntityCache <GuidInfoEntity> >();

            var controller = new GuidInfosController(mockContext.Object, mockCache.Object, _mockClock.Object);
            var info       = await controller.CreateGuidInfoAsync(infoBase);

            Assert.IsType <ActionResult <GuidInfo> >(info);
            var result = Assert.IsType <CreatedAtRouteResult>(info.Result);

            Assert.Equal("GetGuidInfo", result.RouteName);
            Assert.Equal((int)HttpStatusCode.Created, result.StatusCode);
            var value = Assert.IsType <GuidInfo>(result.Value);

            Assert.Equal(value.User, infoBase.User);
            Assert.Equal(value.Expire, _now.AddDays(30));
            Assert.True(System.Guid.TryParse(value.Guid, out System.Guid guid));

            _mockClock.Verify();
            mockRepo.Verify();
            mockContext.Verify();
        }
        public async Task CreateGuidInfo_InvalidUser()
        {
            // User must not be null, empty, or whitespace
            var infoBase = new GuidInfoBase()
            {
                User   = string.Empty,
                Expire = null
            };

            var mockRepo  = new Mock <IGuidRepositoryContext>();
            var mockCache = new Mock <IEntityCache <GuidInfoEntity> >();

            var controller = new GuidInfosController(mockRepo.Object, mockCache.Object, _mockClock.Object);
            var info       = await controller.CreateGuidInfoAsync(infoBase);

            Assert.IsType <ActionResult <GuidInfo> >(info);
            var result = Assert.IsType <BadRequestObjectResult>(info.Result);
            var value  = Assert.IsType <GuidApiError>(result.Value);

            Assert.Equal((int)value.Code, (int)GuidErrorCode.InvalidUser);
        }
示例#7
0
        /// <exception cref="GuidApiException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <GuidInfo> CreateGuidInfoAsync(GuidInfoBase info, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append("api/guid");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(info, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(GuidInfo);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <GuidInfo>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new GuidApiException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ == "400")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(GuidApiError);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <GuidApiError>(responseData_, _settings.Value);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new GuidApiException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                            throw new GuidApiException <GuidApiError>("A server side error occurred.", (int)response_.StatusCode, responseData_, headers_, result_, null);
                        }
                        else
                        if (status_ == "201")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(GuidInfo);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <GuidInfo>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new GuidApiException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new GuidApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(GuidInfo));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
示例#8
0
 /// <exception cref="GuidApiException">A server side error occurred.</exception>
 public System.Threading.Tasks.Task <GuidInfo> CreateGuidInfoAsync(GuidInfoBase info)
 {
     return(CreateGuidInfoAsync(info, System.Threading.CancellationToken.None));
 }
示例#9
0
        public async Task <ActionResult <GuidInfo> > CreateOrUpdateGuidInfoAsync(System.Guid id, [FromBody] GuidInfoBase info)
        {
            var infos = await _context.GuidInfos.GetAsync(i => i.Guid == id);

            if (!infos.Any())
            {
                // guid info not found, create a new one
                return(await CreateGuidInfo(id, info));
            }
            else
            {
                // remove from cache
                await InvalidateCache(id);

                // guid info found, update database
                infos[0].UpdateFrom(info);
                _context.GuidInfos.Update(infos[0]);
                await _context.SaveChangesAsync();

                return(infos[0].ToGuidInfo());
            }
        }
示例#10
0
        private async Task <ActionResult <GuidInfo> > CreateGuidInfo(System.Guid guid, GuidInfoBase info)
        {
            if (string.IsNullOrWhiteSpace(info.User))
            {
                return(BadRequest(new GuidApiError(GuidErrorCode.InvalidUser)));
            }
            else
            {
                var entity = new GuidInfoEntity()
                {
                    Guid   = guid,
                    Expire = info.Expire ?? GetDefaultExpireDate(),
                    User   = info.User
                };

                await _context.GuidInfos.AddAsync(entity);

                await _context.SaveChangesAsync();

                var guidInfo = entity.ToGuidInfo();
                return(CreatedAtRoute("GetGuidInfo", new { id = guidInfo.Guid }, guidInfo));
            }
        }
示例#11
0
 public async Task <ActionResult <GuidInfo> > CreateGuidInfoAsync([FromBody] GuidInfoBase info)
 {
     return(await CreateGuidInfo(System.Guid.NewGuid(), info));
 }