Beispiel #1
0
        public async void GetLongShouldReturnNotFoundIfExists()
        {
            var shortUrl = "XJF4FR";

            //Arrange
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <UrlShortenerContext>()
                              .UseSqlite(connection)
                              .Options;

                using (var context = new UrlShortenerContext(options))
                {
                    context.Database.EnsureCreated();
                }

                using (var context = new UrlShortenerContext(options))
                {
                    //Act
                    ShortenerController controller = new ShortenerController(context);

                    ActionResult result = (await controller.GetLong(shortUrl)).Result;

                    Assert.IsType <NotFoundResult>(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public AjaxResponseData AddNew(string text)
        {
            var response = new AjaxResponseData();

            if (IsValidUrl(text))
            {
                Uri    requestUrl  = HttpContext.Current.Request.Url;
                string requesthost = string.Format("{0}{1}{2}{3}",
                                                   requestUrl.Scheme,
                                                   Uri.SchemeDelimiter,
                                                   requestUrl.Authority,
                                                   "/");
                var entities = new UrlShortenerContext();
                var data     = new ShortenedUrl();
                data.OriginalUrl = text;
                entities.ShortUrls.Add(data);
                entities.SaveChanges();
                response.Success = true;
                response.Data    = requesthost + data.Id;
            }
            else
            {
                response.Success = false;
                response.Data    = "Please enter valid URL";
            }
            return(response);
        }
        /// <summary>
        /// Создание сжатой ссылки
        /// </summary>
        /// <param name="userUrl"><seealso cref="UserUrl"/></param>
        /// <param name="userGuid">гуид пользователя</param>
        /// <returns></returns>
        public async Task <string> AddUserUrlAsync(UserUrl userUrl, Guid userGuid)
        {
            using (var context = new UrlShortenerContext())
            {
                if (userUrl == null || userGuid == Guid.Empty)
                {
                    throw new NullReferenceException();
                }

                //есть такой пользователь в Бд?
                var user = await context.Users.FirstOrDefaultAsync(x => x.UserGuid == userGuid);

                var userId = user?.Id;
                if (userId == null)
                {
                    //добавляем в БД пользователя
                    var result = context.Users.Add(new User()
                    {
                        UserGuid = userGuid
                    });
                    userId = result.Id;
                }

                userUrl.UserId = (long)userId;

                var newUrl = context.UserUrls.Add(userUrl);
                await context.SaveChangesAsync();

                return(newUrl.CompactUrl);
            }
        }
 /// <summary>
 /// Получить оригинальную ссылку по сжатой
 /// </summary>
 /// <param name="compactUrl">сжатая ссылка</param>
 /// <returns></returns>
 public async Task <string> GeOriginUrlByCompactUrlAsync(string compactUrl)
 {
     using (var context = new UrlShortenerContext())
     {
         var result = await(context.UserUrls.FirstOrDefaultAsync(x => x.CompactUrl == compactUrl));
         return(result?.OriginUrl);
     }
 }
 /// <summary>
 /// Получение всех созданных ссылков текущего пользователя
 /// </summary>
 /// <param name="userGuid">гуид пользователя</param>
 /// <returns></returns>
 public async Task <List <UserUrl> > GetUserUrlAsync(Guid userGuid)
 {
     using (var context = new UrlShortenerContext())
     {
         return(await(context.Users.Where(p => p.UserGuid == userGuid)?.Join(context.UserUrls,
                                                                             p => p.Id, userUrl => userUrl.UserId, (p, userUrl) => userUrl)).ToListAsync());
     }
 }
Beispiel #6
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            using (var db = new UrlShortenerContext())
            {
                db.Database.EnsureCreated();
            }
        }
        /// <summary>
        /// Инкремент кол-во переходов по ссылке
        /// </summary>
        /// <param name="compactUrl">ключ компактной ссылки</param>
        /// <returns></returns>
        public async Task IncrementNumberOfViewAsync(string compactUrl)
        {
            using (var context = new UrlShortenerContext())
            {
                var userUrl = await context.UserUrls.FirstOrDefaultAsync(x => x.CompactUrl == compactUrl);

                if (userUrl != null)
                {
                    userUrl.NumberOfViews += 1;
                    await context.SaveChangesAsync();
                }
            }
        }
Beispiel #8
0
        public async void GetLongShouldReturnSuccessIfExists()
        {
            var longUrl =
                "https://www.google.com/search?q=url+shortener&oq=google+u&aqs=chrome.0.69i59j69i60l3j0j69i57.1069j0j7&sourceid=chrome&ie=UTF-8";
            var shortUrl = "XJF4FR";

            //Arrange
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <UrlShortenerContext>()
                              .UseSqlite(connection)
                              .Options;

                using (var context = new UrlShortenerContext(options))
                {
                    context.Database.EnsureCreated();
                }

                using (var context = new UrlShortenerContext(options))
                {
                    context.Urls.Add(new Url()
                    {
                        created = DateTime.Now, long_url = longUrl, short_url = shortUrl, updated = DateTime.Now
                    });
                    context.SaveChanges();
                }

                using (var context = new UrlShortenerContext(options))
                {
                    //Act
                    ShortenerController controller = new ShortenerController(context);
                    string result = (await controller.GetLong(shortUrl)).Value;

                    //Assert
                    Assert.Equal(longUrl, result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #9
0
        private static string GetUniquePart(UrlShortenerContext context)
        {
            var uniquePart = string.Empty;

            for (var i = 0; i < 10; i++)
            {
                uniquePart = Guid.NewGuid().ToString("N").Replace('-', ' ').Substring(0, 10);
                var existingPart = context.ShortUrlDatas.FirstOrDefault(sud => sud.UniquePart.Equals(uniquePart));
                if (existingPart == null)
                {
                    break;
                }
            }

            if (uniquePart.Equals(string.Empty))
            {
                throw new ShortUrlCreationException();
            }

            return(uniquePart);
        }
Beispiel #10
0
        public void OnBeginRequest(Object source, EventArgs e)
        {
            var context = (HttpApplication)source;

            if (context.Request.Url.AbsolutePath.Contains("/url/"))
            {
                var path = context.Request.Url.AbsolutePath.Remove(0, 1);
                var id   = ShortUrlHelper.Decode(path);
                using (var DBcontext = new UrlShortenerContext())
                {
                    var query = from item in DBcontext.ShortUrls
                                where item.Id == id
                                select item.OriginalUrl;

                    var redirectPath = query.FirstOrDefault();
                    if (redirectPath != null)
                    {
                        context.Response.Redirect(redirectPath);
                    }
                }
            }
        }
Beispiel #11
0
        public static Task <ShortUrlData> ShortUrl(HttpRequest request, UrlShortenerContext context, string longUrl)
        {
            return(Task.Run(() =>
            {
                bool isUrl = Uri.TryCreate(longUrl, UriKind.Absolute, out Uri uriResult) &&
                             (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

                if (!isUrl)
                {
                    throw new ShortUrlNotUrlException();
                }

                var existingUrl = context.ShortUrlDatas.FirstOrDefault(sud => sud.LongUrl.Equals(uriResult.AbsoluteUri));
                if (existingUrl != null)
                {
                    throw new ShortUrlExistsException();
                }

                var uniquePart = GetUniquePart(context);
                var shortUrl = GetShortUrl(request, uniquePart);

                var shortUrlData = new ShortUrlData
                {
                    LongUrl = uriResult.AbsoluteUri,
                    ShortUrl = shortUrl,
                    UniquePart = uniquePart,
                    Statistic = new Statistic()
                };

                context.ShortUrlDatas.Add(shortUrlData);

                context.SaveChanges();

                return shortUrlData;
            }));
        }
Beispiel #12
0
 public UrlShortenerService(UrlShortenerContext urlShortenerContext)
 {
     _urlShortenerContext = urlShortenerContext;
 }
 public UrlShortenerRepository(UrlShortenerContext context)
 {
     _context = context ?? throw new ArgumentNullException(nameof(context));
 }
Beispiel #14
0
 public UrlsController(UrlShortenerContext context)
 {
     _context = context;
 }
Beispiel #15
0
 public LinkRepo(UrlShortenerContext context) : base(context)
 {
 }
Beispiel #16
0
 public GetUrlFromLongUrlQueryHandler(UrlShortenerContext context)
 {
     _context = context;
 }
 public UrlController(UrlShortenerContext c)
 {
     Context = c;
 }
Beispiel #18
0
 public AccountService(UrlShortenerContext context)
 {
     _context = context;
 }
 public UrlAliasesRepository(UrlShortenerContext context)
 {
     _context = context;
 }
 public ShortUrlService(UrlShortenerContext context)
 {
     _context = context;
 }
Beispiel #21
0
 public StatisticsController(UrlShortenerContext c)
 {
     Context = c;
 }