/// <summary> /// Main controller to create a shortened URL. /// </summary> /// <param name="link"></param> /// <returns>JsonpResult</returns> public JsonpResult Shorten(Link link) { if (!string.IsNullOrEmpty(link.DestinationUrl)) { if (IsUrlValid(link.DestinationUrl)) //Check to see if the URL is valid. { //This will test to see if the user wants to use a custom code by passing in an ID value in the URL //Example Shorten\mycode\callback? if (String.IsNullOrEmpty(link.ShortCode) && RouteData.Values["id"] != null) { link.ShortCode = RouteData.Values["id"].ToString(); } //Check to see if short code in use if (!String.IsNullOrEmpty(link.ShortCode)) { //If short code is found in database, notify the user. if (db.Links.Where(i => i.ShortCode == link.ShortCode).Count() > 0) return GetLinkAsJSONP(null, "The short code " + link.ShortCode + " already exists."); } Link ExistLink = db.Links.SingleOrDefault(l => l.DestinationUrl.Trim().ToLower() == link.DestinationUrl.Trim().ToLower()); if (ExistLink != null) { return GetLinkAsJSONP(ExistLink, ""); } else { Link newLink = new Link(); newLink.LinkID = Guid.NewGuid(); newLink.DestinationUrl = link.DestinationUrl; newLink.AccessCount = 0; newLink.DateCreated = DateTime.Now; newLink.LastAccessed = DateTime.Now; if (String.IsNullOrEmpty(link.ShortCode)) { newLink.ShortCode = CreateUnusedShortCode(); } else { newLink.ShortCode = link.ShortCode; } db.Links.Add(newLink); db.SaveChanges(); return GetLinkAsJSONP(newLink, ""); } } } return GetLinkAsJSONP(null, "Please provide a valid URL such as http://www.google.com."); }
/// <summary> /// Returns a link as JSONP /// </summary> /// <param name="link"></param> /// <param name="message"></param> /// <returns></returns> private JsonpResult GetLinkAsJSONP(Link link, string message) { JsonpResult result = new JsonpResult(); if (link != null) { var data = new { Success = true, ShortURL = this.BaseURL + link.ShortCode, AccessCount = link.AccessCount, OriginalURL = link.DestinationUrl }; return new JsonpResult(data); } else { var data = new { Success = false, Message = message }; return new JsonpResult(data); } }