public JsonResult Zip(string url) { Uri uri = null; string result = string.Empty; if (string.IsNullOrEmpty(url) || url.Length > 4000 || !Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri || (uri.Scheme != "http" && uri.Scheme != "https")) { return(new JsonResult(null) { StatusCode = (int)HttpStatusCode.NotFound }); } else { try { Shortener sh = new Shortener(_configuration["connectionString"], _configuration["salt"]); return(new JsonResult("https" + Uri.SchemeDelimiter + Request.Host + "/" + sh.Shorten(uri.ToString()))); } catch (Exception ex) { return(new JsonResult(ex.Message) { StatusCode = (int)HttpStatusCode.NotFound }); } } }
public IActionResult Index(string url) { using (var context = new MyDbContext()) { if (context.Urls.Any(u => u.source_url == url)) { string result = string.Empty; var urls = context.Urls.Where(u => u.source_url == url).ToList(); foreach (var s in urls) { result = s.shortened_url; } var temp = "Link is already in the database"; var link = $"https://localhost:44393/{result}"; ViewData["Result"] = temp; ViewData["Url"] = link; return(View()); } else { Shortener shortURL = new Shortener(url); var temp = "Shorted URL:"; var link = $"https://localhost:44393/{shortURL.Token}"; ViewData["Result"] = temp; ViewData["Url"] = link; return(View()); } } }
//Action to redirect to public ActionResult Go(string id = null) { //Get the db instance var dbInstance = LinkDatabase.getInstance(); if (id != null) { int decoding = Shortener.GetLongDecoding(id); try { string longUrl = dbInstance.getLongUrl(decoding.ToString()); //Ideally, with the above ID we will query the DB and get the respective url and redirect to that page //Response.Redirect(longUrl); return(new RedirectResult(longUrl)); } catch (ArgumentException) { //If long url couldn't be found, redirect back to our homepage return(RedirectToAction("LinkShortener", "Home")); } } else { //Otherwise, redirect back to our homepage return(RedirectToAction("LinkShortener", "Home")); } }
public IActionResult PostUrl([FromBody] string url) { if (!url.StartsWith("http")) { url = "http://" + url; } var spatacoliUrl = _unitOfWork.SpatacoliUrls.GetByUrl(url); if (spatacoliUrl != null) { Response.StatusCode = 405; return(Json(new UrlResponse() { url = url, status = "Already shortened", token = spatacoliUrl.Token })); } Shortener shortener = new Shortener(url, _unitOfWork); return(Json(new UrlResponse() { url = "https://sptc.li/" + shortener.Token, status = "Ok", token = shortener.Token })); }
public IActionResult PostURL([FromBody] string url) { try { if (!url.Contains("http")) { url = "http://" + url; } if (new LiteDB.LiteDatabase("Data/Urls.db").GetCollection <NixURL>().Exists(u => u.ShortenedURL == url)) { Response.StatusCode = 405; return(Json(new URLResponse() { url = url, status = "already shortened", token = null })); } Shortener shortURL = new Shortener(url); return(Json(shortURL.Token)); }catch (Exception ex) { if (ex.Message == "URL already exists") { Response.StatusCode = 400; return(Json(new URLResponse() { url = url, status = "URL already exists", token = new LiteDB.LiteDatabase("Data/Urls.db").GetCollection <NixURL>().Find(u => u.URL == url).FirstOrDefault().Token })); } throw new Exception(ex.Message); } return(StatusCode(500)); }
static void Main(string[] args) { Console.WriteLine("Введите свое имя"); string name = Console.ReadLine(); Console.WriteLine("Введите свою фамилию"); string surname = Console.ReadLine(); Console.WriteLine("Сколько вам лет?"); byte age = Convert.ToByte(Console.ReadLine()); Console.WriteLine("Ваш рост?"); byte height = Convert.ToByte(Console.ReadLine()); Console.WriteLine("Ваш вес?"); short weight = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Ваша aнкета, способ 1"); Console.WriteLine("Имя: " + name + " Фамилия: " + surname + " Возраст: " + age + " Рост: " + height + " Вес: " + weight); Console.WriteLine("Ваша анкета, способ 2"); Console.WriteLine(String.Format("Имя: {0} Фамилия: {1} Возраст: {2} Рост: {3} Вес: {4}", name, surname, age, height, weight)); Console.WriteLine("Ваша анкета, способ 3"); Console.WriteLine($"Имя: {name} Фамилия: {surname} Возраст: {age} Рост: {height} Вес: {weight}"); Shortener.WaitKeyPressed(); }
public async Task <IActionResult> SaveLink(string url) { string token = Shortener.GenerateToken(); List <Link> links = await _context.Links.ToListAsync(); foreach (var l in links) { if (l.Url == url) { return(Content("This link has already been created")); } if (l.Token == token) { token = Shortener.GenerateToken(); } } Link link = new Link() { Url = url, Token = token }; _context.Links.Add(link); _context.SaveChanges(); return(RedirectToAction("Links")); }
public void Delete() { string b = HttpContext.Request.Url.Segments[3]; int ID = Convert.ToInt32(b); Shortener sh = new Shortener(); string path = sh.BaseConnection(); SqlConnection con = new SqlConnection(path); con.Open(); string command = string.Format("Delete From UrlTable Where ID='{0}'", ID); using (SqlCommand cmd = new SqlCommand(command, con)) { try { cmd.ExecuteNonQuery(); } catch (SqlException ex) { Exception error = new Exception("Удаление невозможно", ex); throw error; } } Response.Redirect("https://localhost:44302/Home/Index"); }
static void Main(string[] args) { Shortener.Print("Введите x1"); double x1 = Convert.ToDouble(Console.ReadLine()); Shortener.Print("Введите y1"); double y1 = Convert.ToDouble(Console.ReadLine()); Shortener.Print("Введите x2"); double x2 = Convert.ToDouble(Console.ReadLine()); Shortener.Print("Введите y2"); double y2 = Convert.ToDouble(Console.ReadLine()); // задание а) double resultA = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)); // задание б) double resultB = Distance(x1, y1, x2, y2); Console.WriteLine(String.Format("Расстояние, задание а) {0:F2}", resultA)); Console.WriteLine(String.Format("Расстояние, задание б) {0:F2}", resultB)); Shortener.WaitKeyPressed(); }
/// <summary> /// Generateurls the specified URL. /// </summary> /// <param name="url">The URL.</param> /// <returns>IActionResult.</returns> public IActionResult generateurl(PageURL url) { ModelState.Clear(); var _allKeys = _localCache.Get <AllPageUrls>("AllKeys"); if (_allKeys == null) { _allKeys = new AllPageUrls() { Id = Guid.NewGuid(), AllUrls = new List <PageURL>() }; } else if (_allKeys.AllUrls == null) { _allKeys.AllUrls = new List <PageURL>(); } var rtn = new PageURL() { Id = Guid.NewGuid(), FullURL = url.FullURL, ShortURL = Shortener.GetHash(url.FullURL) }; _localCache.Set(rtn.ShortURL.ToString(), url.FullURL, TimeSpan.FromHours(24)); _allKeys.AllUrls.Add(rtn); _localCache.Set("AllKeys", _allKeys, TimeSpan.FromHours(24)); PersistentStore.Store(_localCache, _persistentStore, _allrepository, _repository); return(View("ShortenURL", rtn)); }
static void Main(string[] args) { Console.WriteLine("Введите вес(в кг):"); double weight = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Введите рост (в метрах):"); double height = Convert.ToDouble(Console.ReadLine()); Console.WriteLine($"Индекс массы тела: {IMT(weight, height)}"); Shortener.WaitKeyPressed(); }
/// <summary> /// Init method called in the constructors /// </summary> private void Init() { worksheets = new List <Worksheet>(); styleManager = new StyleManager(); styleManager.AddStyle(new Style("default", 0, true)); Style borderStyle = new Style("default_border_style", 1, true); borderStyle.CurrentBorder = Style.BasicStyles.DottedFill_0_125.CurrentBorder; borderStyle.CurrentFill = Style.BasicStyles.DottedFill_0_125.CurrentFill; styleManager.AddStyle(borderStyle); workbookMetadata = new Metadata(); shortener = new Shortener(); }
public void Go(string id = null) { if (id != null) { int decoding = Shortener.GetLongDecoding(id); //Ideally, with the above ID we will squery the DB and get the respective url and redirect to that page Response.Redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ"); } else { //Otherwise, redirect back to our homepage Response.Redirect(Request.Host.ToString()); } }
public ActionResult Index() { strurl = new Uri(Request.Url.AbsoluteUri).ToString(); strurl = strurl.Trim(); Shortener sh = new Shortener(); string ss = sh.TransitionURL(strurl); if (ss != "") { Response.Redirect(ss); } Short datashort = new Short(); List <Short> listshort = sh.GetDataValue(); return(View(listshort)); }
public async Task <IActionResult> Get(string shortUrl) { var id = Shortener.Decode(shortUrl); if (id == -1) { return(NotFound()); } var mapping = await dbContext.Urls.FindAsync(id); if (mapping == null) { return(NotFound()); } return(new RedirectResult(mapping.Url)); }
public IActionResult Personalize(Link link) { if (ModelState.IsValid) { if (string.IsNullOrEmpty(link.Short)) { link.NumberOfClicks = 0; var linkIsInDatabase = Context.Links.SingleOrDefault(x => x.Long == link.Long); if (linkIsInDatabase == null) { link.NumberOfClicks = 0; link.Short = Shortener.Hash(link.Long); Context.Users.Include(x => x.Links).Single(x => x.UserName == User.Identity.Name).Links.Add(link); Context.SaveChanges(); ViewBag.Message = "http://localhost:59290/" + link.Short; return(View()); } else { ViewBag.Message = "http://localhost:59290/" + linkIsInDatabase.Short; return(View()); } } else { var linkIsInDatabase = Context.Links.SingleOrDefault(x => x.Short == link.Short); if (linkIsInDatabase == null) { link.NumberOfClicks = 0; Context.Users.Include(x => x.Links).Single(x => x.UserName == User.Identity.Name).Links.Add(link); Context.SaveChanges(); ViewBag.Message = "http://localhost:59290/" + link.Short; return(View()); } else { ViewBag.Message = "This personalized option is already in use!"; return(View()); } } } return(View("Index", link)); }
public async Task <IActionResult> Post([FromQuery] string longUrl) { if (longUrl.Length > 2048) { return(new BadRequestObjectResult("Url too long. Limit 2K")); } var mapping = new UrlMapping { Url = longUrl }; dbContext.Add(mapping); await dbContext.SaveChangesAsync(); string shortUrl = Shortener.Encode(mapping.Id); return(new OkObjectResult(new { Long = longUrl, Short = Url.Action("Get", new { shortUrl = shortUrl }) })); }
public async Task <string> CreateShortenerAsync(string sourceLink, string appUrl) { if (!LinkHelper.IsLinkValid(sourceLink) || sourceLink == null) { throw new BusinessRuleValidationException("Неправильный URL."); } string backHalf; do { backHalf = LinkHelper.GenerateBackHalf(sourceLink); }while ((await _shortenerRepository.GetByBackHalf(backHalf)) != null); var shortener = Shortener.Create(sourceLink, appUrl, backHalf); await _shortenerRepository .CreateShortenerAsync(shortener); return(shortener.ShortLink); }
public IActionResult Get(string route) { var id = Shortener.RecoverId(route); var realUrl = _urlShortenerRepository.FindById(id); if (realUrl == null) { return(NotFound()); } realUrl.Clicks++; realUrl.LastVisit = DateTime.Now; _urlShortenerRepository.Update(realUrl); if (!_urlShortenerRepository.Save()) { return(StatusCode(500, "A problem happened while handling your request")); } return(RedirectPermanent(realUrl.Url)); }
public IHttpActionResult AddUrl([FromBody] Url url) { try { //TODO: url.LongUrl should be validates Url newUrl = new Url() { LongUrl = url.LongUrl, ShortUrl = Shortener.CreateShortUrlToken(), CreationDate = DateTime.Now }; Url addedUrl = urlService.Add(newUrl); return(this.Ok(addedUrl)); } catch (Exception ex) { throw this.ThrowException(ex); } }
public IActionResult LinkShortener(string longURL = null) { string shortURL = longURL; ViewData["Title"] = "Link Shortener"; //If string from post was null, then this field isn't displayed if (longURL != null) { //Randomly choose and int... This will actually be the PK value in the DB Random rnd = new Random(); int value = rnd.Next(0, 100); //Algorithm for shortended link string encoding = Shortener.GetShortEncoding(value); int decoding = Shortener.GetLongDecoding(encoding); string urlHost = Request.Host.ToString(); shortURL = urlHost + "/Home/Go/" + encoding; } ViewData["shortURL"] = shortURL; return(View()); }
public IActionResult PostURL([FromBody] URLRequestModel request) { if (ModelState.IsValid) { if (!Captcha.ValidateCaptchaCode(request.CaptchaCode, HttpContext)) { return(View("Error")); } using (LiteDatabase db = new LiteDatabase(Constants.DB_NAME)) { ILiteCollection <NewUrlModel> urls = db.GetCollection <NewUrlModel>(); // Kiểm tra if (!Common.isValidUrl(request.URL)) { Response.StatusCode = 400; return(View("Error")); } NewUrlModel existed; // Kiểm tra trong csdl có bị trùng không if ((existed = urls.FindOne(u => u.URL == request.URL)) != null) { Response.StatusCode = 202; return(Json(new URLReponseModel() { Url = request.URL, Status = "Have already shortened", Token = existed.Token })); } // Nếu không bị trùng thì tạo một url mới } Shortener shortURL = new Shortener(request.URL); Response.StatusCode = 200; return(Json(shortURL)); } else { return(View("Error")); } }
public IActionResult Edit(int id, string @short) { if (string.IsNullOrEmpty(@short)) { Link link = Context.Links.Single(x => x.Id == id); if (Context.Links.Count(x => x.Long == link.Long) == 1) { link.Short = Shortener.Hash(link.Long); Context.Links.Update(link); Context.SaveChanges(); return(RedirectToAction("ShowLinks")); } else { ViewBag.Message = "This shorten form is already in database!"; return(View(link)); } } else { var linkIsInDatabase = Context.Links.SingleOrDefault(x => x.Short == @short); if (linkIsInDatabase == null) { var linkToChange = Context.Links.Single(x => x.Id == id); linkToChange.Short = @short; Context.Links.Update(linkToChange); Context.SaveChanges(); return(RedirectToAction("ShowLinks")); } else { ViewBag.Message = "This shorten form is already in database!"; return(View()); } } }
public IActionResult Index(string id) { string shortUrl = string.Empty; string result = string.Empty; Shortener shortener = new Shortener(_configuration["connectionString"], _configuration["salt"]); if (string.IsNullOrEmpty(id)) { //here we just show the Index try { shortener.TestConnect(); result = "OK"; } catch (Exception ex) { result = ex.Message; } ViewData["host"] = "https://" + Request.Host; ViewData["result"] = result; ViewData["connectionString"] = _configuration["connectionString"]; return(View()); } else { try { if (id.Length <= 12 && !string.IsNullOrEmpty(shortUrl = shortener.GetUrl(id))) { return(Redirect(shortUrl)); } } catch { } } Response.StatusCode = 404; //ViewData["id"] = Uri.EscapeDataString(id); return(View("NotFound")); }
public async Task <UrlDto> AddUrl(UrlCreate url) { // Add the new url to the database if (url == null || url.ActualUrl == null || url.ActualUrl.Trim() == string.Empty) { throw new Exception("Invalid url"); } // Now generate the short url. string shortenedUrl = string.Empty; while (shortenedUrl == string.Empty) { var shortenedValue = Shortener.CreateShortCode(); var existing = _context.Urls.Where(u => u.ShortenedUrl == shortenedValue).FirstOrDefault(); if (existing == null) { shortenedUrl = shortenedValue; } } _context.Urls.Add(new Url { ActualUrl = url.ActualUrl, FriendlyName = url.FriendlyName, ShortenedUrl = shortenedUrl, Created = DateTime.Now }); await _context.SaveChangesAsync(); return(new UrlDto { ActualUrl = url.ActualUrl, ShortenedUrl = shortenedUrl, AccessCount = 0 }); }
//Defualt action of home controller is linkshortener rather than index (changed in route config) //Action takes an optional parameter (longURL) - The url to be shortened public ActionResult LinkShortener(string longURL = null) { //Save the short url as the long url (currently) string shortURL = longURL; //Add the current title to the view bag (for display in the tab on a web broswer) ViewBag.Title = "Link Shortener"; //If string from post was null, then this if statement is never entered if (longURL != null) { //Get the DB instance (and if necessary the DB itself) var dbInstance = LinkDatabase.getInstance(); dbInstance.createDB(); //Save the longurl in the db and save the return as primary key string pk = dbInstance.saveLongURL(longURL); //Encode the PK string encoding = Shortener.GetShortEncoding(Int32.Parse(pk)); //Get the host and port parts of our website url string urlHost = HttpContext.Request.Url.Host; int urlPort = HttpContext.Request.Url.Port; //If no port, ignore adding it to the shortened url if (urlPort == 80) { //Short url looks like: <website name>:<port>/Home/Go/<encoded pk> shortURL = urlHost + "/Home/Go/" + encoding; } else { //Short url looks like: <website name>/Home/Go/<encoded pk> shortURL = urlHost + ":" + urlPort.ToString() + "/Home/Go/" + encoding; } } //Return the shortened (or null) short url to the view ViewBag.shortURL = shortURL; //Render the view return(View()); }
public IActionResult Result(Link link) { if (ModelState.IsValid) { var linkIsInDatabase = Context.Links.SingleOrDefault(x => x.Long == link.Long); if (linkIsInDatabase == null) { link.NumberOfClicks = 0; link.Short = Shortener.Hash(link.Long); Context.Links.Add(link); Context.SaveChanges(); ViewBag.Message = "http://localhost:59290/" + link.Short; return(View()); } else { ViewBag.Message = "http://localhost:59290/" + linkIsInDatabase.Short; return(View()); } } return(View("Index", link)); }
public JsonResult StartShort(Dat dt) { strurl = new Uri(Request.Url.AbsoluteUri).ToString(); string sub = strurl.Substring(0, strurl.Length - 10); string ss = dt.Longurl; Shortener sh = new Shortener(); string stoped = sh.ShortURL(ss); string str = sub + @"Index/" + stoped; if (stoped == "stopURL") { str = "stop"; } else { sh.TokenSave(ss, str); } var dat = new { name = str }; return(Json(dat, JsonRequestBehavior.AllowGet)); }
public void TestSetup() { _fakeDb = new FakeDb(); _shortener = new Shortener(_fakeDb); }
public void TestSetup() { _fakeDb = new FakeDb(); _shortener = new Shortener(_fakeDb); }
public async Task CreateShortenerAsync(Shortener shortener) { await Shorteners.InsertOneAsync(shortener); }