예제 #1
0
        public ShortUrl Execute(ShortUrl entity)
        {
            entity.LastUsage  = DateTime.Now;
            entity.UsageCount = ++entity.UsageCount;

            return(entity);
        }
예제 #2
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));
        }
예제 #3
0
        public bool Exists(ShortUrl candidate)
        {
            var count = _dbContext.ShortUrls
                        .CountDocuments(url => url.Id == candidate.Id);

            return(count > 0);
        }
예제 #4
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));
        }
예제 #5
0
        public async Task <string> CreateShortUrlForUser(Guid userId, string url)
        {
            var isExistUser = await ShortenURlDbContext.UserUrl.FirstOrDefaultAsync(c => c.UserId == userId);

            var shortUrl    = createShortUrlService.MakeShortURL();
            var newShortUrl = new ShortUrl()
            {
                ShortUrlString = shortUrl,
                Url            = url
            };

            if (isExistUser != null)
            {
                isExistUser.ShortUrls.Add(newShortUrl);
                await ShortenURlDbContext.SaveChangesAsync();
            }
            else
            {
                var newUserUrl = new UserUrl()
                {
                    UserId = userId
                };
                newUserUrl.ShortUrls.Add(newShortUrl);
                ShortenURlDbContext.UserUrl.Add(newUserUrl);
                await ShortenURlDbContext.SaveChangesAsync();
            }
            return(shortUrl);
        }
예제 #6
0
        public async Task <string> CreateShortUrlForIp(string userIp, string url)
        {
            var isExistUserIp = await ShortenURlDbContext.UserIp.FirstOrDefaultAsync(c => c.Ip == userIp);

            var shortUrl    = createShortUrlService.MakeShortURL();
            var newShortUrl = new ShortUrl()
            {
                ShortUrlString = shortUrl,
                Url            = url
            };

            if (isExistUserIp != null)
            {
                isExistUserIp.ShortUrls.Add(newShortUrl);
                await ShortenURlDbContext.SaveChangesAsync();
            }
            else
            {
                var newUserIp = new UserIp()
                {
                    Ip = userIp,
                };
                newUserIp.ShortUrls.Add(newShortUrl);
                ShortenURlDbContext.UserIp.Add(newUserIp);
                await ShortenURlDbContext.SaveChangesAsync();
            }
            return(shortUrl);
        }
예제 #7
0
        public ActionResult NewProgram(Program newProgram)
        {
            if (string.IsNullOrWhiteSpace(newProgram.Email))
            {
                return(Json(new { success = false }));
            }

            newProgram.ShortUrl = ShortUrl.Create();
            newProgram.Created  = DateTime.Now;

            Ownership.Assign(newProgram, this);

            if (!LoggedInUser.OnboardingTasks.Contains(OnboardingTask.CreatedProgram.ToString()))
            {
                LoggedInUser.OnboardingTasks.Add(OnboardingTask.CreatedProgram.ToString());
            }

            RavenSession.Store(newProgram);
            RavenSession.SaveChanges();

            new Emailer(this).SendEmail(EmailEnum.SendToPatient, newProgram.Email, newProgram.ShortUrl, newProgram.Id);

            // new ProgramEmailer(this).SendToPatient(newProgram.Id, newProgram.Email, newProgram.ShortUrl);

            return(Json(true));
        }
예제 #8
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            bool isUri = Uri.IsWellFormedUriString(LongUrl, UriKind.Absolute);

            if (!isUri)
            {
                return(Page());
            }

            var shortUrl = new ShortUrl
            {
                LongUrl    = LongUrl,
                Expiration = DateTime.UtcNow.AddMinutes(2)
            };

            HttpStatusCode code = HttpStatusCode.BadRequest;

            (code, shortUrl) = await _urlShortenerService.UpsertShortUrlAsync("1", shortUrl);

            if (code == HttpStatusCode.OK)
            {
                this.ShortUrl = $"{Request.Scheme}://{Request.Host}/s/{shortUrl.Id}";
            }
            else
            {
                this.ShortUrl = $"Error:{code}";
            }

            return(Page());
        }
예제 #9
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));
        }
예제 #10
0
        public IActionResult Create(string originalUrl, string provider, string memo, bool isPrivate)
        {
            var urlPerview = new UrlPerview();

            try
            {
                urlPerview = _urlPerviewService.GetUrlPerview(originalUrl);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            var shortUrl = new ShortUrl
            {
                OriginalUrl     = originalUrl,
                Provider        = provider,
                Memo            = memo,
                IsPrivate       = isPrivate,
                MetaTitle       = urlPerview?.Title,
                MetaDescription = urlPerview?.Description,
                PreviewImageUrl = urlPerview?.ListImages?.FirstOrDefault()
            };

            TryValidateModel(shortUrl);
            if (ModelState.IsValid)
            {
                _shortUrlService.Save(shortUrl);

                return(RedirectToAction(actionName: nameof(CreateSuccess), routeValues: new { path = shortUrl.Path }));
            }

            return(View(shortUrl));
        }
예제 #11
0
        public int Save(ShortUrl url)
        {
            context.ShortUrls.Add(url);
            context.SaveChanges();

            return(url.Id);
        }
예제 #12
0
        public ShortUrl Generate(string fullUrl)
        {
            try
            {
                ShortUrl shortUrl;
                while (true)
                {
                    shortUrl = new ShortUrl(fullUrl);
                    if (_shortenerRepository.Exists(shortUrl))
                    {
                        continue;
                    }
                    break;
                }

                _shortenerRepository.Add(shortUrl);

                _logger.LogInformation("New {@shortUrl} created.", shortUrl);

                return(shortUrl);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating new {@shortUrl}", fullUrl);

                throw;
            }
        }
예제 #13
0
        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);
        }
예제 #14
0
        public static void ShortUrl()
        {
            ShortUrl url      = new ShortUrl();
            string   urlShort = url.GetShortUrl(123123123);

            Assert.That(url.GetIdFromShortUrl(urlShort) == 123123123);
        }
예제 #15
0
 public bool add(Agenda _agenda, string baseUrl = "")
 {
     using (var context = getContext())
     {
         try
         {
             if (_agenda.IdAgenda == 0)
             {
                 var urlToEncode = baseUrl + "/" + _agenda.Uri;
                 _agenda.ShortUrl = ShortUrl.Shorten(urlToEncode);
                 _agenda.Estado   = true;
                 context.Agenda.Add(_agenda);
             }
             else
             {
                 Agenda agenda = context.Agenda.Where(x => x.IdAgenda == _agenda.IdAgenda).SingleOrDefault();
                 agenda.Titulo  = _agenda.Titulo;
                 agenda.Texto   = _agenda.Texto;
                 agenda.Uri     = _agenda.Uri;
                 agenda.Resumen = _agenda.Resumen;
                 agenda.Lugar   = _agenda.Lugar;
                 agenda.Hora    = _agenda.Hora;
                 agenda.Fecha   = _agenda.Fecha;
                 agenda.Estado  = _agenda.Estado;
             }
             context.SaveChanges();
             return(true);
         }
         catch (Exception e) {
             throw e;
         }
     }
 }
예제 #16
0
        public IActionResult Create([FromBody] ShortUrl shortUrl)
        {
            if (!string.IsNullOrEmpty(shortUrl.Slug))
            {
                var url = _shortUrlService.Get(shortUrl.Slug);
                if (url != null)
                {
                    return(Conflict($"Slug '{url.Slug}' is in use"));
                }
            }

            if (string.IsNullOrEmpty(shortUrl.Slug))
            {
                var xeger = new Xeger("[a-z0-9]{5}", new Random());
                shortUrl.Slug = xeger.Generate();
            }

            shortUrl.Slug = shortUrl.Slug.ToLower();

            try
            {
                var res = _shortUrlService.Create(shortUrl);
                return(Ok(res));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(StatusCode(500));
            }
        }
예제 #17
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, new string[] { "get", "post" }, Route = "Redireciona/{shortUrl}")] HttpRequestMessage req,
            [Microsoft.Azure.WebJobs.Table("shortlinks", Connection = "AzureWebJobsStorage")] CloudTable cloudTable,
            string shortUrl,
            TraceWriter log)
        {
            string empty = string.Empty;

            if (string.IsNullOrWhiteSpace(shortUrl))
            {
                throw new Exception("O ShortLink não existe");
            }

            string partitionKey = shortUrl.Substring(0, 1) ?? "";

            log.Info("Busca pela PartitionKey " + partitionKey + " e RowKey " + shortUrl + ".", (string)null);

            ShortUrl result = (await cloudTable.ExecuteAsync(TableOperation.Retrieve <ShortUrl>(partitionKey, shortUrl, (List <string>)null))).Result as ShortUrl;

            if (result == null)
            {
                throw new Exception("O ShortLink não existe");
            }

            string str = WebUtility.UrlDecode(result.Url);
            HttpResponseMessage response = req.CreateResponse(HttpStatusCode.Found);

            response.Headers.Add("Location", str);

            return(response);
        }
예제 #18
0
    public override void OnInspectorGUI()
    {
        EditorStyles.textField.wordWrap      = true;
        EditorStyles.label.wordWrap          = true;
        EditorStyles.miniLabel.wordWrap      = true;
        EditorStyles.miniTextField.wordWrap  = true;
        EditorStyles.whiteMiniLabel.wordWrap = true;
        EditorStyles.miniButton.wordWrap     = true;

        EditorStyles.textField.fontStyle      = FontStyle.Normal;
        EditorStyles.label.fontStyle          = FontStyle.Normal;
        EditorStyles.miniLabel.fontStyle      = FontStyle.Normal;
        EditorStyles.miniTextField.fontStyle  = FontStyle.Normal;
        EditorStyles.whiteMiniLabel.fontStyle = FontStyle.Normal;
        EditorStyles.miniButton.fontStyle     = FontStyle.Normal;

        DrawDefaultInspector();
        group.DrawEditor();

        GUI.color = Color.cyan;
        EditorGUILayout.LabelField(new GUIContent("---Unique ID testing---"));
        if (string.IsNullOrEmpty(GroupTest))
        {
            GroupTest = group.Path;
        }
        GroupTest = EditorGUILayout.TextField(GroupTest);
        if (GUILayout.Button("Test Unique ID"))
        {
            UniqueIDTest = ShortUrl.GetUniqueID(GroupTest);
        }
        EditorGUILayout.LabelField(new GUIContent(UniqueIDTest));
    }
예제 #19
0
        public string SaveUrl(string originalUrl)
        {
            if (!_utilities.IsValidUri(originalUrl).Result)
            {
                return("Sorry the URL you entered is not live");
            }

            var supposedShortUrl = _utilities.GetRandomUrl();

            while (_unitOfWork.ShortUrlRepository.IsShortUrlExists(supposedShortUrl))
            {
                supposedShortUrl = _utilities.GetRandomUrl();
            }

            var shortUrl = new ShortUrl
            {
                OriginalUrl = originalUrl,
                ShortenUrl  = supposedShortUrl,
                InsertDate  = DateTime.Now.Date
            };

            _unitOfWork.Add(shortUrl);
            _unitOfWork.Complete();



            return("");
        }
예제 #20
0
        public async Task TestMethod_SimpleItemDbContext_Insert()
        {
            var store = _fixture.GetService <ISimpleItemDbContext <ShortUrlCosmosDocument> >();

            store.Should().NotBeNull();
            var shortUrl = new ShortUrl
            {
                Expiration = DateTime.UtcNow.AddSeconds(2),
                Id         = "1234",
                LongUrl    = "https://www.google.com"
            };
            var document = new ShortUrlCosmosDocument(shortUrl.ToShortUrlCosmosDocument());
            var response = await store.UpsertItemAsync(document);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
            var read = await store.GetItemAsync(document.Id);

            read.Should().NotBeNull();
            read.Id.Should().Be(document.Id);

            // wait 2 seconds.
            Thread.Sleep(2000);
            read = await store.GetItemAsync(document.Id);

            read.Should().BeNull();
        }
예제 #21
0
        public async Task <IActionResult> Submit(string longUrl)
        {
            string newUrl = tidyUrl(longUrl);

            if (!validateUrlInput(newUrl))
            {
                ViewData["ErrorText"] = "Invalid url " + newUrl;
                return(View("UrlError"));
            }

            //get existing or create
            ShortUrl urlReturn = await _context.ShortUrl
                                 .FirstOrDefaultAsync(m => m.longUrl == newUrl);

            if (urlReturn == null)
            {
                urlReturn = new ShortUrl(newUrl);
                while (!keyUnique(urlReturn.key))
                {
                    urlReturn = new ShortUrl(newUrl);
                }
                if (ModelState.IsValid)
                {
                    _context.Add(urlReturn);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    ViewData["ErrorText"] = "Fatal Error";
                    return(View("UrlError"));
                }
            }
            ViewData["UrlReturn"] = String.Format("{0}://{1}{2}", Request.Scheme, Request.Host, Request.PathBase) + "/" + urlReturn.key;
            return(View());
        }
예제 #22
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);
            }
        }
예제 #23
0
        public Task <Stat> Click(string segment, string referer, string ip)
        {
            return(Task.Run(() =>
            {
                using (var ctx = new ShortnrContext())
                {
                    ShortUrl url = ctx.ShortUrls.Where(u => u.Segment == segment).FirstOrDefault();
                    if (url == null)
                    {
                        throw new ShortnrNotFoundException();
                    }

                    url.NumOfClicks = url.NumOfClicks + 1;

                    Stat stat = new Stat()
                    {
                        ClickDate = DateTime.Now,
                        Ip = ip,
                        Referer = referer,
                        ShortUrl = url
                    };

                    ctx.Stats.Add(stat);

                    ctx.SaveChanges();

                    return stat;
                }
            }));
        }
        public async Task Handle_WhenFoundRandom_ReturnsSuccessfulResponse()
        {
            var expectedUrl = new ShortUrl
            {
                Adjective = new Adjective {
                    Value = "Adj"
                },
                Adverb = new Adverb {
                    Value = "Adv"
                },
                Noun = new Noun {
                    Value = "Nou"
                },
                BaseDomain  = "https://localhost/",
                DateCreated = DateTimeOffset.UtcNow,
                TargetUrl   = "https://localhost/"
            };

            _shortUrlRepositoryMock.Setup(m => m.GetRandomAsync(It.IsAny <string>()))
            .ReturnsAsync(expectedUrl);

            var handler = new GetRandomUrlQueryHandler(_shortUrlRepositoryMock.Object);
            var actual  = await handler.Handle(new GetRandomUrlQuery { LanguageCode = "en" }, CancellationToken.None);

            Assert.True(actual.IsSuccessful);
            Assert.Equal(expectedUrl.DateCreated, actual.DateCreated);
            Assert.Equal(expectedUrl.TargetUrl, actual.TargetUrl);
            Assert.Equal("en", actual.Language);
            Assert.Equal($"https://localhost/AdvAdjNou", actual.Url);
        }
예제 #25
0
        public async Task <IActionResult> Edit(int id, [Bind("id,longUrl,key")] ShortUrl shortUrl)
        {
            if (!loggedIn())
            {
                return(View("Login"));
            }

            if (id != shortUrl.id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(shortUrl);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ShortUrlExists(shortUrl.id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(shortUrl));
        }
        public SpamStatus CheckStatus(ShortUrl shortUrl)
        {
            Check.Argument.IsNotNull(shortUrl, "shortUrl");

            int phishingCount;
            int malwareCount;

            googleSafeBrowsing.Verify(shortUrl.Url, out phishingCount, out malwareCount);

            SpamStatus status = SpamStatus.None;

            if ((phishingCount > 0) || (malwareCount > 0))
            {
                if (phishingCount > 0)
                {
                    status |= SpamStatus.Phishing;
                }

                if (malwareCount > 0)
                {
                    status |= SpamStatus.Malware;
                }
            }
            else
            {
                status = SpamStatus.Clean;
            }

            return(status);
        }
예제 #27
0
        public int Save(ShortUrl shortUrl)
        {
            _context.ShortUrls.Add(shortUrl);
            _context.SaveChanges();

            return(shortUrl.Id);
        }
예제 #28
0
        public int Save(ShortUrlCreationRequest request)
        {
            ShortUrlHost host = HostByName(request.HostName);

            if (host == null)
            {
                throw new Exception($"Host name '{request.HostName}' does not exist!");
            }

            var url = new ShortUrl
            {
                HostId      = host.Id,
                Path        = request.Path,
                OriginalUrl = request.OriginalUrl,
                LetterLink  = request.LetterLink,
                Note        = request.Note,
                UserName    = request.UserName,
                Subject     = request.Subject,
                Created     = DateTime.Now
            };

            context.ShortUrls.Add(url);
            context.SaveChanges();

            return(url.Id);
        }
예제 #29
0
        public async Task <IActionResult> Create([FromBody] ShortUrl shortUrl)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid input"));
            }

            if (!IsUrlValid(shortUrl.Url))
            {
                return(BadRequest("Invalid url"));
            }

            if (string.IsNullOrWhiteSpace(shortUrl.Slug))
            {
                shortUrl.Slug = RandomIdGenerator.GetBase62(8);
            }

            try
            {
                await context.ShortUrls.AddAsync(shortUrl);

                await context.SaveChangesAsync();
            }
            catch (Exception)
            {
                return(BadRequest("Failed to create short url"));
            }


            return(Created(Url.Action("Index", "UrlShortener", new
            {
                slug = shortUrl.Slug
            }, Request.Scheme),
                           shortUrl));
        }
예제 #30
0
 public void QueueShortUrl(ShortUrl shortUrl)
 {
     if (Enabled)
     {
         string message = CreateShortUrlEmbed(shortUrl);
         WebhookQueue.Add(message);
     }
 }
예제 #31
0
        public Task<ShortUrl> ShortenUrl(string longUrl, string ip, string segment = "")
        {
            return Task.Run(() =>
            {
                using (var ctx = new ShorturlContext())
                {
                    ShortUrl url;

                    url = ctx.ShortUrls.Where(u => u.LongUrl == longUrl).FirstOrDefault();
                    if (url != null)
                    {
                        return url;
                    }

                    if (!string.IsNullOrEmpty(segment))
                    {
                        if (ctx.ShortUrls.Where(u => u.Segment == segment).Any())
                        {
                            throw new ShorturlConflictException();
                        }
                    }
                    else
                    {
                        segment = this.NewSegment();
                    }

                    if (string.IsNullOrEmpty(segment))
                    {
                        throw new ArgumentException("Segment is empty");
                    }

                    url = new ShortUrl()
                    {
                        Added = DateTime.Now,
                        Ip = ip,
                        LongUrl = longUrl,
                        NumOfClicks = 0,
                        Segment = segment
                    };

                    ctx.ShortUrls.Add(url);

                    ctx.SaveChanges();

                    return url;
                }
            });
        }
예제 #32
0
        public ActionResult Index(FormCollection collection)
        {
            //TODO check for valid URL

            ShortUrl shortUrl = new ShortUrl();
            UrlRepository repo = new UrlRepository();

            string url = collection["url"];

            string shortName = repo.GetShortName(url);

            shortUrl.URL = url;
            shortUrl.ShortName = shortName;
            if (string.IsNullOrEmpty(shortName)) {
                shortUrl.ShortName = repo.GetNewShortName();
                repo.SaveUrl(shortUrl);
            }

            shortUrl.URL = string.Format("http://uurl.co/{0}", shortUrl.ShortName);
            return View(shortUrl);
        }
예제 #33
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync execution of \short_url\share\counts rest call. 
		/// It returns JsonResponse&lt;ShortUrl.Share.CountsResponse&gt;
		/// Here comes request Comments:
		///<para>取得一个短链接在微博上的微博分享数(包含原创和转发的微博) </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/share/counts.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<ShortUrl.Share.CountsResponse> ExecuteShortUrlShareCounts(ShortUrl.Share.CountsRequest request)
		{
			return ExecuteShortUrlShareCountsAsync(request).Result;
		}
예제 #34
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync execution of \short_url\share\statuses rest call. 
		/// It returns JsonResponse&lt;ShortUrl.Share.StatusesResponse&gt;
		/// Here comes request Comments:
		///<para>取得包含指定单个短链接的最新微博内容 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/share/statuses.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	true  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<ShortUrl.Share.StatusesResponse> ExecuteShortUrlShareStatuses(ShortUrl.Share.StatusesRequest request)
		{
			return ExecuteShortUrlShareStatusesAsync(request).Result;
		}
예제 #35
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync request of \short_url\expand rest call.
		///It returns JsonResponse&lt;Stream&gt;
		/// Here comes request Comments:
		///<para>将一个或多个短链接还原成原始的长链接 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/expand.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<Stream> RequestShortUrlExpand(ShortUrl.ExpandRequest request)
		{
			return RequestShortUrlExpandAsync(request).Result;
		}
예제 #36
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync request of \short_url\shorten rest call.
		///It returns JsonResponse&lt;Stream&gt;
		/// Here comes request Comments:
		///<para>将一个或多个长链接转换成短链接 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/shorten.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<Stream> RequestShortUrlShorten(ShortUrl.ShortenRequest request)
		{
			return RequestShortUrlShortenAsync(request).Result;
		}
예제 #37
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a async request of \short_url\comment\counts rest call. 
		///It returns JsonResponse&lt;Stream&gt;
		/// Here comes request Comments:
		///<para>取得一个短链接在微博上的微博评论数 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/comment/counts.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public async Task<JsonResponse<Stream>> RequestShortUrlCommentCountsAsync (
			ShortUrl.Comment.CountsRequest request,
			CancellationToken cancellationToken =default(CancellationToken),
			IProgress<ProgressReport> progress=null 
			)			
		{
			return await _requestShortUrlCommentCountsMethod.GetResponseAsync(request, cancellationToken, progress);
		}
예제 #38
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync request of \short_url\comment\counts rest call.
		///It returns JsonResponse&lt;Stream&gt;
		/// Here comes request Comments:
		///<para>取得一个短链接在微博上的微博评论数 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/comment/counts.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<Stream> RequestShortUrlCommentCounts(ShortUrl.Comment.CountsRequest request)
		{
			return RequestShortUrlCommentCountsAsync(request).Result;
		}
예제 #39
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync request of \short_url\share\counts rest call.
		///It returns JsonResponse&lt;Stream&gt;
		/// Here comes request Comments:
		///<para>取得一个短链接在微博上的微博分享数(包含原创和转发的微博) </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/share/counts.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<Stream> RequestShortUrlShareCounts(ShortUrl.Share.CountsRequest request)
		{
			return RequestShortUrlShareCountsAsync(request).Result;
		}
예제 #40
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a async request of \short_url\share\statuses rest call. 
		///It returns JsonResponse&lt;Stream&gt;
		/// Here comes request Comments:
		///<para>取得包含指定单个短链接的最新微博内容 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/share/statuses.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	true  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public async Task<JsonResponse<Stream>> RequestShortUrlShareStatusesAsync (
			ShortUrl.Share.StatusesRequest request,
			CancellationToken cancellationToken =default(CancellationToken),
			IProgress<ProgressReport> progress=null 
			)			
		{
			return await _requestShortUrlShareStatusesMethod.GetResponseAsync(request, cancellationToken, progress);
		}
예제 #41
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync request of \short_url\share\statuses rest call.
		///It returns JsonResponse&lt;Stream&gt;
		/// Here comes request Comments:
		///<para>取得包含指定单个短链接的最新微博内容 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/share/statuses.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	true  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<Stream> RequestShortUrlShareStatuses(ShortUrl.Share.StatusesRequest request)
		{
			return RequestShortUrlShareStatusesAsync(request).Result;
		}
예제 #42
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a async execution of \short_url\share\counts rest call. 
		/// It returns JsonResponse&lt;ShortUrl.Share.CountsResponse&gt;
		/// Here comes request Comments:
		///<para>取得一个短链接在微博上的微博分享数(包含原创和转发的微博) </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/share/counts.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public async Task<JsonResponse<ShortUrl.Share.CountsResponse>> ExecuteShortUrlShareCountsAsync (
			ShortUrl.Share.CountsRequest request,
			CancellationToken cancellationToken =default(CancellationToken),
			IProgress<ProgressReport> progress=null 
			)			
		{
			return await _executeShortUrlShareCountsMethod.GetResponseAsync(request, cancellationToken, progress);
		}
예제 #43
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync execution of \short_url\shorten rest call. 
		/// It returns JsonResponse&lt;ShortUrl.ShortenResponse&gt;
		/// Here comes request Comments:
		///<para>将一个或多个长链接转换成短链接 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/shorten.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<ShortUrl.ShortenResponse> ExecuteShortUrlShorten(ShortUrl.ShortenRequest request)
		{
			return ExecuteShortUrlShortenAsync(request).Result;
		}
예제 #44
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync execution of \short_url\comment\counts rest call. 
		/// It returns JsonResponse&lt;ShortUrl.Comment.CountsResponse&gt;
		/// Here comes request Comments:
		///<para>取得一个短链接在微博上的微博评论数 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/comment/counts.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<ShortUrl.Comment.CountsResponse> ExecuteShortUrlCommentCounts(ShortUrl.Comment.CountsRequest request)
		{
			return ExecuteShortUrlCommentCountsAsync(request).Result;
		}
예제 #45
0
		public Task<ShortUrl> ShortenUrl(string longUrl, string ip, string segment = "")
		{
			return Task.Run(() =>
			{
				using (var ctx = new ShortnrContext())
				{
					ShortUrl url;

					url = ctx.ShortUrls.Where(u => u.LongUrl == longUrl).FirstOrDefault();
					if (url != null)
					{
						return url;
					}

					if (!longUrl.StartsWith("http://") && !longUrl.StartsWith("https://"))
					{
						throw new ArgumentException("Invalid URL format");
					}
					Uri urlCheck = new Uri(longUrl);
					HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlCheck);
					request.Timeout = 10000;
					try
					{
						HttpWebResponse response = (HttpWebResponse)request.GetResponse();
					}
					catch (Exception)
					{
						throw new ShortnrNotFoundException();
					}

					int cap = 0;
					string capString = ConfigurationManager.AppSettings["MaxNumberShortUrlsPerHour"];
					int.TryParse(capString, out cap);
					DateTime dateToCheck = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
					int count = ctx.ShortUrls.Where(u => u.Ip == ip && u.Added >= dateToCheck).Count();
					if (cap != 0 && count > cap)
					{
						throw new ArgumentException("Your hourly limit has exceeded");
					}

					if (!string.IsNullOrEmpty(segment))
					{
						if (ctx.ShortUrls.Where(u => u.Segment == segment).Any())
						{
							throw new ShortnrConflictException();
						}
						if (segment.Length > 20 || !Regex.IsMatch(segment, @"^[A-Za-z\d_-]+$"))
						{
							throw new ArgumentException("Malformed or too long segment");
						}
					}
					else
					{
						segment = this.NewSegment();
					}

					if (string.IsNullOrEmpty(segment))
					{
						throw new ArgumentException("Segment is empty");
					}

					url = new ShortUrl()
					{
						Added = DateTime.Now,
						Ip = ip,
						LongUrl = longUrl,
						NumOfClicks = 0,
						Segment = segment
					};

					ctx.ShortUrls.Add(url);

					ctx.SaveChanges();

					return url;
				}
			});
		}
예제 #46
0
파일: SinaWeiboTest1.cs 프로젝트: JDCB/JDCB
		/// <summary>
		/// This is a sync execution of \short_url\expand rest call. 
		/// It returns JsonResponse&lt;ShortUrl.ExpandResponse&gt;
		/// Here comes request Comments:
		///<para>将一个或多个短链接还原成原始的长链接 </para>
		///<para>URL:</para>
		///<para>	http://api.t.sina.com.cn/short_url/expand.(json|xml)</para>
		///<para>支持格式:</para>
		///<para>	XML/JSON</para>
		///<para>HTTP请求方式:</para>
		///<para>	GET</para>
		///<para>是否需要登录:</para>
		///<para>	false  关于授权机制,参见授权机制声明</para>
		///<para>请求数限制:</para>
		///<para>	true  关于请求数限制,参见接口访问权限说明</para>
		///<para></para>
		/// </summary>
		public JsonResponse<ShortUrl.ExpandResponse> ExecuteShortUrlExpand(ShortUrl.ExpandRequest request)
		{
			return ExecuteShortUrlExpandAsync(request).Result;
		}