Beispiel #1
0
        public void ShouldAddNewShortUrlEntityFromEmptyCode()
        {
            var urlShortenDto = new ShortUrlDto
            {
                Url = "www.example.com"
            };

            var urlShorten = new ShortUrl
            {
                Code = "Code1",
                Url  = "www.example.com"
            };

            creatorService.Setup(x => x.Execute(urlShortenDto))
            .Returns(urlShorten);

            var service = new UrlShortenerService(repository.Object,
                                                  new GenerateCodeCommand(),
                                                  creatorService.Object,
                                                  new ShortenUrlUsageCommand(),
                                                  mapper.Object);


            var result = service.Add(urlShortenDto);

            repository.Verify(x => x.Add(It.IsAny <ShortUrl>()), Times.Once);

            Assert.False(string.IsNullOrEmpty(result.Code));
            Assert.False(string.IsNullOrEmpty(urlShortenDto.Code));
        }
Beispiel #2
0
        public void ShouldReturnShortenUrlEntityFromDto()
        {
            var mapper = new Mock <IMapper>();

            mapper.Setup(x => x.Map <ShortUrl>(It.IsAny <ShortUrlDto>()))
            .Returns(new ShortUrl
            {
                Code = "AAAZZ4",
                Url  = "www.example.com"
            });

            var list = new List <ShortUrl>();

            var task = Task.FromResult <IList <ShortUrl> >(list);

            var repository = new Mock <IRepository <ShortUrl> >();

            repository.Setup(x => x.ListAsync(It.IsAny <Expression <Func <ShortUrl, bool> > >()))
            .Returns(task);

            var service = new UrlShortenerCreatorService(mapper.Object,
                                                         repository.Object,
                                                         this.codeValidator);

            var shortenUrlDto = new ShortUrlDto
            {
                Code = "AAAZZ4",
                Url  = "www.example.com"
            };

            var result = service.Execute(shortenUrlDto);

            Assert.Equal(result.Code, shortenUrlDto.Code);
            Assert.Equal(result.Url, shortenUrlDto.Url);
        }
Beispiel #3
0
        public void ShouldThrowExceptionWhenNotFoundAEntityByCode()
        {
            var code = "Code1";

            var urlShortenDto = new ShortUrlDto
            {
                Code = "Code1",
                Url  = "www.example.com"
            };

            var urlShorten = new ShortUrl
            {
                Code = "Code1",
                Url  = "www.example.com"
            };

            creatorService.Setup(x => x.Execute(urlShortenDto))
            .Returns(urlShorten);

            var list = new List <ShortUrl>();

            var task = Task.FromResult <IList <ShortUrl> >(list);

            repository.Setup(x => x.ListAsync(It.IsAny <Expression <Func <ShortUrl, bool> > >()))
            .Returns(task);

            var service = new UrlShortenerService(repository.Object,
                                                  new GenerateCodeCommand(),
                                                  creatorService.Object,
                                                  new ShortenUrlUsageCommand(),
                                                  mapper.Object);

            Assert.ThrowsAsync <NotFoundException>(() => service.GetUrlByCode(code));
        }
        public static ShortUrl Create(ShortUrlDto dto)
        {
            // Eğer üretilmek istenen original url kalıcı bir bağlantıysa,
            // ve daha önce aynı original url için kalıcı bir bağlantı oluşturulmuşsa
            // yeni bir bağlantı oluşturmak yerine varolanı döndür.
            // Kullanıcı bazlı olarak!.

            var shortUrlRecord = db.ShortUrls.FirstOrDefault(x =>
                                                             x.OriginalUrl == dto.OriginalUrl &&
                                                             x.ApiKeyId == dto.ApiKeyId &&
                                                             x.isPermanent == dto.isPermanent
                                                             );

            if (shortUrlRecord != null)
            {
                return(shortUrlRecord);
            }


            var newShortUrl = new ShortUrl()
            {
                OriginalUrl = dto.OriginalUrl,
                Url         = UniqueId.Generate(),
                isPermanent = dto.isPermanent,
                CreatorId   = dto.CreatorId,
                ApiKeyId    = dto.ApiKeyId,
                CreatedAt   = DateTime.Now,
                ExpiresAt   = DateTime.Now.AddDays(dto.Expiration)
            };

            db.ShortUrls.Add(newShortUrl);
            db.SaveChanges();

            return(newShortUrl);
        }
Beispiel #5
0
        public void ShouldGenerateConflictException()
        {
            var shortenUrl = new ShortUrl
            {
                Code = "AAA123",
                Url  = "www.example.com"
            };

            var mapper = new Mock <IMapper>();

            mapper.Setup(x => x.Map <ShortUrl>(It.IsAny <ShortUrlDto>()));

            var list = new List <ShortUrl> {
                shortenUrl
            };

            var task = Task.FromResult <IList <ShortUrl> >(list);

            var repository = new Mock <IRepository <ShortUrl> >();

            repository.Setup(x => x.ListAsync(It.IsAny <Expression <Func <ShortUrl, bool> > >()))
            .Returns(task);

            var service = new UrlShortenerCreatorService(mapper.Object,
                                                         repository.Object,
                                                         this.codeValidator);

            var shortenUrlDto = new ShortUrlDto
            {
                Code = "AAA123",
                Url  = "www.example.com"
            };

            Assert.Throws <ConflictException>(() => service.Execute(shortenUrlDto));
        }
Beispiel #6
0
        public void CreateShortUrlEntry(ShortUrlDto shortUrl, HttpContext _httpContext)
        {
            var user = _httpContext.User;

            if (!user.Identity.IsAuthenticated)
            {
                throw new AccessViolationException();
            }
            try
            {
                var userObject = _userManager.GetUserAsync(user);
                shortUrl.Owner = userObject.Result;
            }
            catch (Exception ex)
            {
                throw new AccessViolationException("unable to find {user}");
            }

            var newShortUrl = new ShortUrl(shortUrl);

            try
            {
                _dbContext.Add(newShortUrl);
                _dbContext.SaveChanges();
                //  _dbContext.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception(null, ex);
            }
        }
Beispiel #7
0
        public ShortUrCreatedlDto Add(ShortUrlDto shortUrlDto)
        {
            var shortUrl = CreateShortenUrl(shortUrlDto);

            this.repository.Add(shortUrl);

            return(new ShortUrCreatedlDto {
                Code = shortUrl.Code
            });
        }
Beispiel #8
0
        private ShortUrl CreateShortenUrl(ShortUrlDto shortUrlDto)
        {
            if (string.IsNullOrEmpty(shortUrlDto.Code))
            {
                shortUrlDto.Code = GenerateCode();
            }

            var shortUrlEntity = urlShortenerCreatorService.Execute(shortUrlDto);

            return(shortUrlEntity);
        }
Beispiel #9
0
        public IActionResult Post(ShortUrlDto shortUrlDto)
        {
            if (string.IsNullOrEmpty(shortUrlDto.Url))
            {
                return(BadRequest("Url is not present"));
            }

            var shortUrlCreated = this.urlShortenerService.Add(shortUrlDto);

            return(Created(string.Empty, shortUrlCreated));
        }
Beispiel #10
0
        public void ShoulReturnStatsByCode()
        {
            var code = "Code1";

            var statDto = new UrlStatDto
            {
                CreatedAt  = DateTime.Now.AddDays(-2),
                LastUsage  = DateTime.Now,
                UsageCount = 1
            };

            var urlShortenDto = new ShortUrlDto
            {
                Code = "Code1",
                Url  = "www.example.com"
            };

            var urlShorten = new ShortUrl
            {
                Code = "Code1",
                Url  = "www.example.com"
            };

            this.mapper.Setup(x => x.Map <UrlStatDto>(urlShorten))
            .Returns(statDto);

            creatorService.Setup(x => x.Execute(urlShortenDto))
            .Returns(urlShorten);

            var list = new List <ShortUrl> {
                urlShorten
            };

            var task = Task.FromResult <IList <ShortUrl> >(list);

            repository.Setup(x => x.ListAsync(It.IsAny <Expression <Func <ShortUrl, bool> > >()))
            .Returns(task);

            var service = new UrlShortenerService(repository.Object,
                                                  new GenerateCodeCommand(),
                                                  creatorService.Object,
                                                  new ShortenUrlUsageCommand(),
                                                  mapper.Object);

            var result = Task.Run(() => service.GetStatByCode(code)).Result;

            repository.Verify(x => x.ListAsync(It.IsAny <Expression <Func <ShortUrl, bool> > >()), Times.Once);
            Assert.Equal(1, result.UsageCount);
            Assert.True(DateTime.Now > result.CreatedAt);
            Assert.True(result.UsageCount > 0);
        }
Beispiel #11
0
        public ShortUrl Execute(ShortUrlDto shortUrlDto)
        {
            if (!IsValid(shortUrlDto.Code))
            {
                UnprocessableEntity();
            }

            if (IsConflictEntity(shortUrlDto.Code))
            {
                ConflictEntity(shortUrlDto.Code);
            }

            return(this.mapper.Map <ShortUrl>(shortUrlDto));
        }
Beispiel #12
0
        public HttpResponseMessage Post(HttpRequestMessage request, ShortUrlDto dto)
        {
            var principal = (ClaimsPrincipal)User;
            var apiKeyId  = int.Parse(principal.Claims.First(x => x.Type == ClaimTypes.Sid).Value);

            dto.ApiKeyId = apiKeyId;

            try
            {
                return(request.CreateResponse(HttpStatusCode.Created, ShortUrlService.Create(dto)));
            }
            catch (Exception)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
Beispiel #13
0
        public void ShouldReturnShortUrlEntityFromCodeAndUpdate()
        {
            var code = "Code1";

            var urlShortenDto = new ShortUrlDto
            {
                Code = "Code1",
                Url  = "www.example.com"
            };

            var urlShorten = new ShortUrl
            {
                Code = "Code1",
                Url  = "www.example.com"
            };

            creatorService.Setup(x => x.Execute(urlShortenDto))
            .Returns(urlShorten);

            var list = new List <ShortUrl>
            {
                new ShortUrl {
                    Code = "Code2", Url = "www.example2.com"
                }
            };

            var task = Task.FromResult <IList <ShortUrl> >(list);

            repository.Setup(x => x.ListAsync(It.IsAny <Expression <Func <ShortUrl, bool> > >()))
            .Returns(task);

            var service = new UrlShortenerService(repository.Object,
                                                  new GenerateCodeCommand(),
                                                  creatorService.Object,
                                                  new ShortenUrlUsageCommand(),
                                                  mapper.Object);


            var result = service.GetUrlByCode(code).Result;

            repository.Verify(x => x.ListAsync(It.IsAny <Expression <Func <ShortUrl, bool> > >()), Times.Once);
            repository.Verify(x => x.Update(It.IsAny <ShortUrl>()), Times.Once);

            Assert.False(string.IsNullOrEmpty(result));
        }
Beispiel #14
0
        public static ShortUrl Update(ShortUrlDto dto, bool isAdmin)
        {
            var shortUrlRecord = db.ShortUrls.FirstOrDefault(x =>
                                                             x.Id == dto.Id &&
                                                             (isAdmin || x.ApiKeyId == dto.ApiKeyId)
                                                             );

            if (shortUrlRecord == null)
            {
                throw new Exception("Short Url record not found");
            }

            shortUrlRecord.isPermanent = dto.isPermanent;
            shortUrlRecord.ExpiresAt   = dto.ExpiresAt;

            db.SaveChanges();

            return(shortUrlRecord);
        }
Beispiel #15
0
        public async Task <IActionResult> Get(string shorturl, [FromQuery(Name = "ipAdress")] string ipAdress = null, [FromQuery(Name = "redirect")] bool redirect = true)
        {
            try
            {
                ShortUrlDto shortUrl = _shortUrlService.GetItemFromDataStore(shorturl);

                if (shortUrl != null)
                {
                    var    userAgent       = HttpContext.Request.Headers["User-Agent"];
                    string parsedUserAgent = Convert.ToString(userAgent[0]);

                    var ip = ipAdress ?? GetIpAddress();

                    VisitorRequestDto visitorRequest = new VisitorRequestDto
                    {
                        Ip        = ip,
                        ShortUrl  = shorturl,
                        UserAgent = parsedUserAgent
                    };

                    VisitorResponseDto visitorResponse = await _visitorService.RegisterVisitor(visitorRequest);

                    if (visitorResponse.Success)
                    {
                        if (redirect)
                        {
                            return(Redirect(shortUrl.LongURL));
                        }

                        return(Ok(shortUrl));
                    }

                    return(BadRequest("Can't register visitor"));
                }

                return(NotFound());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Beispiel #16
0
        public void ShouldGenerateUnprocessableEntityException()
        {
            var mapper = new Mock <IMapper>();

            mapper.Setup(x => x.Map <ShortUrl>(It.IsAny <ShortUrlDto>()));

            var repository = new Mock <IRepository <ShortUrl> >();

            var service = new UrlShortenerCreatorService(mapper.Object,
                                                         repository.Object,
                                                         this.codeValidator);

            var shortenUrl = new ShortUrlDto
            {
                Code = "AAA",
                Url  = "www.example.com"
            };

            Assert.Throws <UnprocessableEntityException>(() => service.Execute(shortenUrl));
        }
Beispiel #17
0
        public void EditShortUrlEntry(ShortUrlDto shortUrl)
        {
            try
            {
                var updateResult = _dbContext.Find <ShortUrl>(shortUrl.Id);

                updateResult.UrlNickname = (shortUrl.UrlNickname ?? updateResult.UrlNickname);
                updateResult.RedirectUrl = (shortUrl.RedirectUrl ?? updateResult.RedirectUrl);
                updateResult.FileName    = (shortUrl.FileName ?? updateResult.FileName);
                updateResult.UrlType     = shortUrl.UrlType;
                //  updateResult.Active = (shortUrl.RedirectUrl ?? updateResult.RedirectUrl);

                updateResult.Active = shortUrl.Active;
                _dbContext.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public override async Task <ShortUrlListDto> Handle(GetAllShortUrlQuery request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var totalCount = await GetTotalCount(cancellationToken);

            var result = new ShortUrlListDto
            {
                TotalCount = totalCount
            };

            List <ShortUrl> list = await GetShortUrls(request, totalCount);

            if (list.Any())
            {
                result.ShortUrls = list.AsQueryable().Select(s => ShortUrlDto.MapFromEntity(s, _globalSettings.RouterDomain));
            }

            // @Event
            _mediator.Publish(new ShortUrlsQueried()
            {
                ShortUrls = list
            }, cancellationToken).Forget();

            return(result);
        }
Beispiel #19
0
 public static List <ShortUrlDto> FindAll(bool isAdmin) => ShortUrlDto.FromEntityList(db.ShortUrls.ToList());