public Task <Estatistica> Estatisticas(string alias, string referencia, string ip) { return(Task.Run(() => { using (var urlContext = new ShortenContext()) { ShortenUrl url = urlContext.ShortenUrl.Where(u => u.Alias == alias).FirstOrDefault(); if (url == null) { throw new ShortenNotFoundException(); } url.NumeroDeClicks = url.NumeroDeClicks + 1; Estatistica estatistica = new Estatistica() { Data = DateTime.Now, Ip = ip, Referencia = referencia, ShortenUrl = url }; urlContext.Estatistica.Add(estatistica); urlContext.SaveChanges(); return estatistica; } })); }
public static ShortUrlResponse ToObject(this ShortenUrl model) { return(new ShortUrlResponse() { OriginalUrl = model.OriginalUrl, ShortUrl = model.ShortUrl }); }
public void AddUrlTest() { var result = ShortenUrl.AddUrl(new[] { "http://www.baidu.com" }); result.ForEach(x => { Console.WriteLine(x.ToString()); }); }
public async Task <ActionResult> Index(Url url) { if (ModelState.IsValid) { ShortenUrl shortenUrl = await this._urlRepositorio.ShortenUrl(url.LongURL, Request.UserHostAddress, url.CustomAlias); url.ShortenURL = string.Format("{0}://{1}{2}{3}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"), shortenUrl.Alias); } return(View(url)); }
void IShortenUrlServiceQuery.Add(ShortenUrl shortenUrl) { try { unitOfWork.Repository <ShortenUrl>().Add(shortenUrl); unitOfWork.SaveChanges(); } catch { throw; } }
public async Task <Url> Shorten([FromUri] string url, [FromUri] string segment = "") { ShortenUrl shortenUrl = await this._urlRepositorio.ShortenUrl(HttpUtility.UrlDecode(url), HttpContext.Current.Request.UserHostAddress, segment); Url urlModel = new Url() { LongURL = url, ShortenURL = string.Format("{0}://{1}/{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Authority, shortenUrl.Alias) }; return(urlModel); }
public void ConvertUrl_should_not_convert_long_to_short_and_found_exception_if_appsettings_key_absence() { //var shortenUrlSetting = new ShortenUrlSetting(); var shortenUrl = new ShortenUrl() { ShortUrl = "testurl" }; this.shortenUrlSetting.Setup(x => x.Value).Returns(It.IsAny <ShortenUrlSetting>()); sut = new ShortUrlCommand(this.shortenUrlServiceQuery.Object, this.shortenUrlSetting.Object); this.shortenUrlServiceQuery.Setup(x => x.GetByLongUrl(It.IsAny <string>())).Returns(shortenUrl); var exp = Assert.Throws <NullReferenceException>(() => sut.ConvertUrl("testurl")); }
public void ConvertUrl_should_convert_empty_longurl_if_not_stored_in_db() { var shortenUrlSetting = new ShortenUrlSetting(); shortenUrlSetting.DomainName = "http://shortenurl.my/"; var shortenUrl = new ShortenUrl() { ShortUrl = "testUrl", LongUrl = "https://www.linkedin.com/in/ehasanulhoque/" }; this.shortenUrlSetting.Setup(x => x.Value).Returns(shortenUrlSetting); sut = new ShortUrlCommand(this.shortenUrlServiceQuery.Object, this.shortenUrlSetting.Object); this.shortenUrlServiceQuery.Setup(x => x.GetByShortUrl(It.IsAny <string>())).Returns(It.IsAny <ShortenUrl>()); var result = sut.ConvertUrl(shortenUrlSetting.DomainName + shortenUrl.ShortUrl); result.Should().BeNullOrEmpty(); }
public void ConvertUrl_should_convert_short_to_long_for_url_without_http_by_getting_from_db_if_already_stored_in_db() { var shortenUrlSetting = new ShortenUrlSetting(); shortenUrlSetting.DomainName = "http://shortenurl.my/"; var shortenUrl = new ShortenUrl() { ShortUrl = "testUrl", LongUrl = "https://www.linkedin.com/in/ehasanulhoque/" }; this.shortenUrlSetting.Setup(x => x.Value).Returns(shortenUrlSetting); sut = new ShortUrlCommand(this.shortenUrlServiceQuery.Object, this.shortenUrlSetting.Object); this.shortenUrlServiceQuery.Setup(x => x.GetByShortUrl(It.IsAny <string>())).Returns(shortenUrl); var result = sut.ConvertUrl("shortenurl.my/" + shortenUrl.ShortUrl); result.Should().Contain(shortenUrl.LongUrl); }
public void ConvertUrl_should_convert_long_to_short_by_getting_last_part_of_short_url_from_db_if_already_stored_in_db() { var shortenUrlSetting = new ShortenUrlSetting(); shortenUrlSetting.DomainName = "http://shortenurl.my/"; var shortenUrl = new ShortenUrl() { ShortUrl = "testurl" }; this.shortenUrlSetting.Setup(x => x.Value).Returns(shortenUrlSetting); sut = new LongUrlCommand(this.shortenUrlServiceQuery.Object, this.shortenUrlSetting.Object); this.shortenUrlServiceQuery.Setup(x => x.GetByLongUrl(It.IsAny <string>())).Returns(shortenUrl); var result = sut.ConvertUrl("testurl"); result.Should().Contain(shortenUrl.ShortUrl); }
public async Task <ActionResult <ShortenUrl> > Create(string url) { if (string.IsNullOrEmpty(url)) { throw new ArgumentException("Parameter is required", nameof(url)); } var userId = await GetOrCreateUserId(); var shortenUrl = new ShortenUrl() { UserId = userId, FullUrl = url }; shortenUrl = _dbService.Create(shortenUrl); return(shortenUrl); }
string IUrlCommand.ConvertUrl(string url) { try { var shortenUrl = this.shortenUrlServiceQuery.GetByLongUrl(url); if (shortenUrl == null) { shortenUrl = new ShortenUrl() { LongUrl = url, ShortUrl = ShortUrl, CreatedDate = DateTime.Now }; this.shortenUrlServiceQuery.Add(shortenUrl); } return(FullShortUrl(this.shortenUrlSetting.DomainName, shortenUrl.ShortUrl)); } catch (Exception) { throw; } }
public async void GetStatsByCodeValid() { var createdAt = DateTime.UtcNow.AddDays(-5); var lastUsage = DateTime.UtcNow; var shortenUrl = new ShortenUrl { Code = "ABC123", CreatedAt = createdAt, LastUsage = lastUsage, ShortUrlId = 1, OriginalUrl = "http://google.com", UsageCount = 3 }; var expectedStats = new UrlStatsViewModel { CreatedAt = createdAt, LastUsage = lastUsage, UsageCount = 3 }; var ShortenUrlRepostory = new Mock <IShortenUrlRepository>(); ShortenUrlRepostory.Setup(p => p.GetShortenUrl(It.IsAny <string>())).Returns(Task.FromResult <ShortenUrl>(shortenUrl)); var shortenUrlService = new ShortenUrlService(ShortenUrlRepostory.Object, new CodeService()); var result = await shortenUrlService.GetStatsByCode("ABC123"); var expected = JsonConvert.SerializeObject(expectedStats); var resultStats = JsonConvert.SerializeObject(result); Assert.Equal(expected, resultStats); }
public ShortenUrl Create(ShortenUrl shortenUrl) { shortenUrl.Id = GetNextId(); _urls.InsertOne(shortenUrl); return(shortenUrl); }
public ShortenUrl InsertAsync(ShortenUrl model) { _repository.Add(model); return(model); }
public Task <ShortenUrl> ShortenUrl(string longUrl, string ip, string alias = "") { return(Task.Run(() => { using (var urlContext = new ShortenContext()) { ShortenUrl url; url = urlContext.ShortenUrl.Where(u => u.LongUrl == longUrl).FirstOrDefault(); if (url != null) { return url; } if (!longUrl.StartsWith("http://") && !longUrl.StartsWith("https://")) { throw new ArgumentException("URL com formato inválido!"); } Uri urlCheck = new Uri(longUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlCheck); request.Timeout = 10000; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); } catch (Exception) { throw new ShortenNotFoundException(); } int cap = 0; string capString = ConfigurationManager.AppSettings["MaxNumberShortUrlsPerHour"]; int.TryParse(capString, out cap); DateTime dataCriacao = DateTime.Now.Subtract(new TimeSpan(1, 0, 0)); int count = urlContext.ShortenUrl.Where(u => u.Ip == ip && u.Adicionado >= dataCriacao).Count(); if (cap != 0 && count > cap) { throw new ArgumentException("Você excedeu o limite diário."); } if (!string.IsNullOrEmpty(alias)) { if (urlContext.ShortenUrl.Where(u => u.Alias == alias).Any()) { throw new ShortenConflitoException(); } if (alias.Length > 20 || !Regex.IsMatch(alias, @"^[A-Za-z\d_-]+$")) { throw new ArgumentException("Alias com formato errado ou muito longo."); } } else { alias = this.NovoAlias(); } if (string.IsNullOrEmpty(alias)) { throw new ArgumentException("Alias vazio."); } url = new ShortenUrl() { Adicionado = DateTime.Now, Ip = ip, LongUrl = longUrl, NumeroDeClicks = 0, Alias = alias }; urlContext.ShortenUrl.Add(url); urlContext.SaveChanges(); return url; } })); }