Beispiel #1
0
        public UrlValidationResult Validate(UrlModel urlModel)
        {
            var url = urlModel.Url;

            if (url is null)
            {
                return(UrlValidationResult.Malformed);
            }

            var isValid = Uri.TryCreate(url, UriKind.Absolute, out var uri) &&
                          (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);

            if (!isValid)
            {
                return(UrlValidationResult.Malformed);
            }

            var hasDuplicate = databaseContext.Urls.Any(i => i.Value == url);

            if (hasDuplicate)
            {
                return(UrlValidationResult.Duplicate);
            }

            return(UrlValidationResult.Ok);
        }
Beispiel #2
0
        public static List <UrlModel> GetHaveContentUrls(string rootUrl)
        {
            if (string.IsNullOrEmpty(rootUrl))
            {
                return(null);
            }

            List <UrlModel> urls = new List <UrlModel>();

            RedisUtils.CollectionInstance.Exec(AppConfigManager.COLLECTION_HREFS_DB, db =>
            {
                HashEntry[] items         = db.HashGetAll(GetBeforeUrlKey(rootUrl));
                UrlModel model            = null;
                Tuple <int, string> value = null;
                foreach (HashEntry item in items)
                {
                    value = ParseHashValue(item.Value.ToString());
                    model = new UrlModel()
                    {
                        Url           = item.Name.ToString(),
                        Level         = value.Item1,
                        localFileName = value.Item2
                    };

                    if (model.IsLocalization())
                    {
                        urls.Add(model);
                    }
                }
            });

            return(urls);
        }
Beispiel #3
0
        /// <summary>
        /// 获取基础数据地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private SyncResponse GetUrlStr(SyncRequest request)
        {
            UrlModel submitData = JsonHelper.DecodeJson <UrlModel>(request.Data);
            string   url        = ConfigurationManager.AppSettings[submitData.Type].ToString();

            return(SyncResponse.GetResponse(request, url));
        }
Beispiel #4
0
        // GET: Url/Edit/5
        public ActionResult Edit(int id)
        {
            UrlModel  urlModel = new UrlModel();
            DataTable dtblUrl  = new DataTable();

            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();
                string         query = "SELECT* FROM URL WHERE Id = @Id";
                SqlDataAdapter sqlDa = new SqlDataAdapter(query, sqlCon);
                sqlDa.SelectCommand.Parameters.AddWithValue("@Id", id);
                sqlDa.Fill(dtblUrl);
            }
            if (dtblUrl.Rows.Count == 1)
            {
                urlModel.Id    = Convert.ToInt32(dtblUrl.Rows[0][0].ToString());
                urlModel.Surl  = Convert.ToString(dtblUrl.Rows[0][1].ToString());
                urlModel.Url   = Convert.ToString(dtblUrl.Rows[0][2].ToString());
                urlModel.Date  = Convert.ToDateTime(dtblUrl.Rows[0][3].ToString());
                urlModel.Count = Convert.ToInt32(dtblUrl.Rows[0][4].ToString());
                return(View(urlModel));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Beispiel #5
0
        /// <summary>
        /// Создаёт и заполняет экземпляр "DateRates" данными из DOM исходника
        /// </summary>
        /// <param name="document"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        private DateRates GetDateRates(IDocument document, UrlModel url)
        {
            var       blocks = GetParseElements(in document, "tr", "js-rt-block-row "); // получаем блоки с категориями номеров и ценами
            DateRates result = new DateRates(url.ParentLink, url.Date);

            if (blocks.Count() == 0)
            {
                result.WithoutAnyRate();
                return(result);
            }
            foreach (var item in blocks)
            {
                var priceLine = new Rate();
                // парсим названия категорий
                var category = GetParseElements(in item, "span", "hprt-roomtype-icon-link ");
                foreach (var _item in category)
                {
                    priceLine.Category = _item.TextContent.Trim();
                }
                // парсим цены
                var price = GetParseElements(in item, "div", "bui-price-display__value prco-inline-block-maker-helper prco-f-font-heading ");
                foreach (var _item in price)
                {
                    priceLine.Price = _item.TextContent.Trim();
                }
                var meal = GetParseElements(in item, "li", "jq_tooltip  rt_clean_up_options");
                foreach (var _item in meal)
                {
                    priceLine.Meal = _item.TextContent.Trim();
                }
                result.Rates.Add(priceLine);
            }
            return(result);
        }
Beispiel #6
0
        public static UrlModel ToWellFormattedObject(this UrlModel model)
        {
            var serviceBase = ConfigurationManager.AppSettings.Get("ServiceBase");

            model.ShortUrl = $"{serviceBase}/st/{model.ShortUrl}";
            return(model);
        }
Beispiel #7
0
 public UrlModel Add(UrlModel urlModel)
 {
     urlModel.Time = DateTime.UtcNow;
     _context.Add(urlModel);
     _context.SaveChanges();
     return(urlModel);
 }
Beispiel #8
0
        public static iAFWebHost.Entities.Url Map(UrlModel model)
        {
            iAFWebHost.Entities.Url entity = new iAFWebHost.Entities.Url();
            entity.Id                = model.Id;
            entity.Href              = model.Href;
            entity.HrefActual        = model.HrefActual;
            entity.Flag              = model.Flag;
            entity.Title             = model.Title;
            entity.Summary           = model.Summary;
            entity.UtcDate           = model.UtcDate;
            entity.HttpTimeStamp     = model.HttpTimeStamp;
            entity.HttpContentLength = model.HttpContentLength;
            entity.HttpContentType   = model.HttpContentType;
            entity.HttpResponseCode  = model.HttpResponseCode;
            entity.HttpResponseIP    = model.HttpResponseIP;

            if (model.Users != null)
            {
                entity.Users = model.Users;
            }

            if (model.Tags != null)
            {
                entity.Tags = model.Tags;
            }

            return(entity);
        }
Beispiel #9
0
        public static UrlModel Map(iAFWebHost.Entities.Url entity)
        {
            UrlModel model = new UrlModel();

            model.Id                = entity.Id;
            model.Href              = entity.Href;
            model.HrefActual        = entity.HrefActual;
            model.Flag              = entity.Flag;
            model.Title             = entity.Title;
            model.Summary           = entity.Summary;
            model.UtcDate           = entity.UtcDate;
            model.HttpResponseCode  = entity.HttpResponseCode;
            model.HttpTimeStamp     = entity.HttpTimeStamp;
            model.HttpContentLength = entity.HttpContentLength;
            model.HttpContentType   = entity.HttpContentType;
            model.HttpResponseIP    = entity.HttpResponseIP;

            if (entity.Users != null)
            {
                model.Users = entity.Users;
            }

            if (entity.Tags != null)
            {
                model.Tags = entity.Tags;
            }

            return(model);
        }
Beispiel #10
0
        // POST api/url
        public void Post([FromBody] string value)
        {
            string urlReal  = "http://www.teste.com/23/234";
            string urlShort = "pd";

            MapallDBContext db           = new MapallDBContext();
            UrlModel        urlshortener = new UrlModel();

            urlshortener = db.Urls.Where(x => x.Urlshortener == urlReal).FirstOrDefault();

            try
            {
                if (urlshortener.Urlshortener == "")
                {
                    urlshortener.Url = urlReal;
                    urlshortener.CreateShortenerURL(urlShort);

                    db.Urls.Add(urlshortener);
                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("304 - URL já existe");
                }
            }
            catch (Exception ex)
            {
                BadRequest(ex.Message);
            }
        }
Beispiel #11
0
        public async Task <ActionResult> Edit(UrlInfo model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            using (UrlModel entity = new UrlModel())
            {
                if (entity.UrlInfo.Any(a => a.ShortName == model.ShortName && a.Id != model.Id))
                {
                    ModelState.AddModelError("ShortName", "Short name already in used.");
                    return(View(model));
                }
                if (model.Id != 0)
                {
                    var urlInfo = entity.UrlInfo.FirstOrDefault(f => f.Id == model.Id);
                    if (urlInfo != null)
                    {
                        urlInfo.ShortName = model.ShortName;
                        urlInfo.Url       = model.Url;
                    }
                }
                else
                {
                    entity.UrlInfo.Add(model);
                }
                await entity.SaveChangesAsync();

                return(Redirect("/"));
            }
        }
Beispiel #12
0
        //// GET api/url
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}

        // GET api/url/5
        public string Get(string url)
        {
            MapallDBContext db           = new MapallDBContext();
            string          urlReturn    = "";
            UrlModel        urlshortener = new UrlModel();

            try
            {
                urlshortener = db.Urls.Where(x => x.Urlshortener == url).FirstOrDefault();

                if (urlshortener.Urlshortener == "")
                {
                    throw new Exception("404 - URL Not found");
                }
            }
            catch (Exception ex)
            {
                BadRequest(ex.Message);
                urlReturn = ex.Message;
            }

            if (urlshortener.Urlshortener != "")
            {
                urlReturn = urlshortener.Urlshortener;
            }

            return(urlReturn);
        }
Beispiel #13
0
        public ActionResult ModalDetailsPrintable(String id, String urlBack, String redirectUrl)
        {
            DataController controllerData = new DataController();

            ViewBag.id = id;
            if (id != null)
            {
                ViewBag.id = id;
            }
            UrlModel mode = new UrlModel();

            if (id != null)
            {
                mode.EmpId = id;
            }
            mode.URLBack          = urlBack;
            mode.RedirectUrl      = redirectUrl;
            mode.employeeProgress = controllerData.GetEmployeeDetails(id);
            var emplo = entities.EmployeeDCR_Vw.Where(emp => emp.Employee_ID == id).FirstOrDefault();

            if (emplo != null)
            {
                mode.employeeProgress.Medal = emplo.Medal;
            }
            return(View(mode));
        }
Beispiel #14
0
      public ActionResult Index()
      {
          var model = new UrlModel(new UrlContext());

          var longUrl = Request.Form["Url.LongUrl"];
          var tinyUrl = Request.Form["TinyUrlLookup"];


          if (!string.IsNullOrEmpty(tinyUrl))
          {
              model.Retrieve(FromTinyUrl(tinyUrl));
              if (model.Url != null)
              {
                  model.TinyUrl = "";
              }
          }
          else if (!string.IsNullOrEmpty(longUrl))
          {
              if (!IsUrlValid(longUrl))
              {
                  model.Message = "Please provide valid Url";
                  return(View(model));
              }
              model.Retrieve(longUrl);
              if (model.Url != null)
              {
                  model.TinyUrl = $"{Request.Url}{ToTinyUrl(model.Url.Id)}";
              }
              model.Url = new Url();
          }

          return(View(model));
      }
Beispiel #15
0
        /// <summary>
        /// Shortens the URL.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        protected UrlModel ShortenUrl(UrlModel model)
        {
            Url entity = Mapper.Map(model);

            entity = urlService.ShortenUrl(entity);
            return(Mapper.Map(entity));
        }
            /**
             * This probably should be in the TweetStatModel.
             *
             */
            public TweetStatModel GetStats()
            {
                var           Now            = DateTimeOffset.Now.ToUnixTimeSeconds();
                var           PreviousMinute = 60;
                var           PreviousHour   = (60 * 60);
                TwitterAPIDAO dao            = new TwitterAPIDAO();
                string        command        = "SELECT Count(*) AS total";

                command += ", (SELECT SUM(`LIKE`) FROM tweets) AS 'totalLikes'";
                command += ", (SELECT SUM(`reTweet`) FROM tweets) AS 'totalRetweets'";
                command += ", (SELECT COUNT(*) FROM tweets WHERE hasEmoji = 1) AS 'totalEmojis'";
                command += ", (SELECT COUNT(*) FROM tweets WHERE hasImage = 1) AS 'totalImages'";
                command += ", (SELECT COUNT(*) FROM tweets WHERE hasUrl = 1) AS 'totalUrls'";
                command += ", (SELECT COUNT(*) FROM tweets WHERE `date` >= (SELECT MAX(`date`) FROM tweets) - 1) AS 'lastSecond'";
                command += ", (SELECT COUNT(*) FROM tweets WHERE `date` >= (SELECT MAX(`date`) FROM tweets) - " + PreviousMinute + ") AS 'lastMinute'";
                command += ", (SELECT COUNT(*) FROM tweets WHERE `date` >= (SELECT MAX(`date`) FROM tweets) - " + PreviousHour + ") AS 'lastHour'";
                command += "FROM tweets";

                TweetStatModel tweetStats = dao.GetSingleObject(command);

                tweetStats.Emojis    = EmojiModel.GetEmojis();
                tweetStats.Hashtags  = HashtagModel.GetHashtags();
                tweetStats.Languages = LanguageModel.GetLanguages();
                tweetStats.Mentions  = MentionModel.GetMentions();
                tweetStats.Urls      = UrlModel.GetUrls();

                return(tweetStats);
            }
        public async Task <Response> CreateUrl(UrlModel model)
        {
            if (!await IsShortUrlPathTaken(model.ShortUrlPath))
            {
                return(ResponseFactory.InitializeResponseFailed($"ShortUrlPath {model.ShortUrlPath} already taken", model));
            }

            var path = string.IsNullOrWhiteSpace(model.ShortUrlPath)
                ? Utilities.GenerateRandomPath(
                Convert.ToInt32(_configuration["Path:Length"]),
                _configuration["Path:Characters"]
                )
                : model.ShortUrlPath;

            var hashedIpAddress = Utilities.HashIpAddress(
                "",
                _configuration["Hashing:Pepper"],
                Convert.ToInt32(_configuration["Hashing:Iterations"])
                );

            var newUrl = UrlFactory.InitializeUrl(
                model.OriginalUrl,
                path,
                hashedIpAddress
                );

            await _repository.CreateUrl(newUrl);

            return(ResponseFactory.InitializeResponseSuccess($"New Short Url {newUrl.ShortUrlPath}", newUrl));
        }
        public async Task <IActionResult> UrlConverter(string url)
        {
            if (url == null)
            {
                return(Content("Указанный URL невалиден!"));
            }

            Regex regex = new Regex(@"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$");

            if (!regex.IsMatch(url))
            {
                return(Content("Указанный URL невалиден!"));
            }

            if (!ContainsUrl(url))
            {
                string   shorten = Crc32.Compute(Encoding.ASCII.GetBytes(url)).ToString("X");
                UrlModel model   = new UrlModel()
                {
                    OriginalURL = url,
                    ShortURL    = shorten,
                    Created     = DateTime.Now,
                    Counter     = 0
                };
                db.URLs.Add(model);
                await db.SaveChangesAsync();
            }
            else
            {
                return(Content("Указанный URL уже существует в базе!"));
            }
            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> Index(UrlModel urlModel)
        {
            if (urlModel.ProvidedUrl == null)
            {
                return(View(_viewModel));
            }

            this._apiFactory            = new MercuryApiFactory(ApiUris.MercuryApiUri + urlModel.ProvidedUrl, ContentTypes.Json, ApiNames.MercuryApiName, AuthorizationTypes.xKey);
            this._httpRequestController = new HttpRequestController(_apiFactory.GetApi());
            this._httpRequestController.AddContentTypeHeader();
            this._httpRequestController.AddAutorizationHeader(_parser.GetObject(ApiNames.MercuryApiName));

            var result = await _httpRequestController.Send();

            var response = JsonConvert.DeserializeObject <ResponseModel>(result);

            if (response.content == null)
            {
                TempData["Error"] = "Site is not available or doesn't exist";
                return(View(_viewModel));
            }
            if (_viewModel.ResponseModels.Count == 5)
            {
                _viewModel.ResponseModels.RemoveAt(0);
            }
            _viewModel.ResponseModels.Insert(0, response);

            HtmlCounter counter = new HtmlCounter(_viewModel.ResponseModels.Last().content);

            _viewModel.ResponseModels.Last().TagsOccurrences = counter.CountOccurrence();


            return(View(_viewModel));
        }
Beispiel #20
0
        public ActionResult Stats(string id)
        {
            if (id.IsShortCode())
            {
                // display individual url stats
                UrlModel urlModel = ExpandUrl(id);
                if (urlModel != null && !String.IsNullOrEmpty(urlModel.Href))
                {
                    UrlPageModel model = new UrlPageModel();
                    model.UrlModel          = urlModel;
                    model.HourlyDataPoints  = GetLast24HourStats(id);
                    model.DailyDataPoints   = GetLast30DaysStats(id);
                    model.MonthlyDataPoints = GetLast12MonthStats(id);
                    return(View(model));
                }
            }
            else
            {
                //display global system stats
                UrlPageModel model = new UrlPageModel();
                model.HourlyDataPoints  = GetLast24HourSystemStats();
                model.DailyDataPoints   = GetLast30DaysSystemStats();
                model.MonthlyDataPoints = GetLast12MonthSystemStats();
                return(View("SystemStats", model));
            }

            return(RedirectPermanent("/"));
        }
Beispiel #21
0
        public string ShortUrl(string Url)
        {
            if (Url.Trim() != "")
            {
                string shortUrl = GetRandomUrl();
                using (UrlContext dbContext = new UrlContext())
                {
                    try
                    {
                        while (dbContext.Urls.Any(ur => ur.Surl == shortUrl))
                        {
                            shortUrl = GetRandomUrl();
                        }

                        UrlModel data = new UrlModel();
                        data.Surl = shortUrl;
                        data.Url  = Url;
                        dbContext.Urls.Add(data);
                        dbContext.SaveChanges();
                    }
                    catch { }
                    return(shortUrl);
                }
            }
            return("");
        }
Beispiel #22
0
        private async void IconFromUrl(object param)
        {
            UrlModel urlModel = Controller.GetUrlFromUser();

            if (urlModel == null || urlModel.DialogResult == false)
            {
                return;
            }
            string url = urlModel.Url;

            const string errorMessage = "There was an issue connecting to the internet. Please try again";

            try {
                using (var client = new HttpClient()) {
                    Stream stream = await client.GetStreamAsync(url);

                    var bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = stream;
                    bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    Icon = bitmap;
                }
            }
            catch (WebException) {
                Controller.ShowError(errorMessage);
            }
            catch (HttpRequestException) {
                Controller.ShowError(errorMessage);
            }
        }
Beispiel #23
0
        public async Task <IActionResult> Cloud(UrlModel model)
        {
            try
            {
                var wordList             = _wordService.Get(model.Url);
                var sortedWordDictionary = _wordService.CalculateAndSortToDictionary(wordList);

                foreach (var w in sortedWordDictionary)
                {
                    var word = new Word {
                        Value = w.Key, Count = w.Value
                    };
                    var existing = await _repository.Get(word.Value);

                    if (existing != null)
                    {
                        existing.Count += word.Count;
                        _repository.Update(existing);
                    }
                    else
                    {
                        word.Id = _hashService.Hash(word.Value);
                        _repository.Add(word);
                    }
                }

                ViewBag.Words = sortedWordDictionary.ToDictionary(w => w.Key, w => w.Value);;
            }
            catch
            {
                return(RedirectToAction("Error"));
            }

            return(View("Index"));
        }
        void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            UrlModel deserializedUrlModel = JsonConvert.DeserializeObject <UrlModel>(e.Result);

            //  MessageBox.Show(deserializedUrlModel.id + deserializedUrlModel.kind + deserializedUrlModel.longUrl);
            ShortUrl = deserializedUrlModel.id;
            ShortUrlChanged(EventArgs.Empty);
        }
Beispiel #25
0
        public static void CreateNew(UrlModel model)
        {
            model.ID = Guid.NewGuid();
            var taskmodel = new TaskModel(model);

            taskmodel.client = new WebClient();
            DownloaderManager.TryAdd(model.ID, taskmodel);
        }
        public async Task <bool> UpdateBanner([FromBody] UrlModel urlm)
        {
            var user = await userHandler.GetUserByEmail(HttpContext.User.Identity.Name);

            var url = urlm.Url;

            return(await userHandler.UpdateProfileBannerPictureAsync(user, url));
        }
        public static bool IsCurrentRoute(this RequestContext context, string areaName, string controllerName, string actionName)
        {
            var url = new UrlModel {
                ActionName = actionName, ControllerName = controllerName, AreaName = areaName
            };

            return(context.IsCurrentRoute(url));
        }
 private async Task <CheckModel> CheckAsync(UrlModel model)
 {
     return(new CheckModel()
     {
         Identifier = model,
         Information = await CheckAsync(model.Url)
     });
 }
Beispiel #29
0
        public ActionResult ModalMessage(String message, String urlBack)
        {
            ViewBag.message = message;
            UrlModel mode = new UrlModel();

            mode.URLBack = urlBack;
            return(View(mode));
        }
Beispiel #30
0
        public string Redirect(string code, string serie)
        {//serie=ABC123456789
            ProductModel p = _productBusiness.GetBySerie(code, serie);
            BrandModel   b = _brandBusiness.GetByBrand(p.Brand);
            CountryModel c = _countryBusiness.GetByAlpha2(p.SapClientAlpha_2Code);
            UrlModel     u = _urlBusiness.GetByCompany(p.Company);

            return(_urlBusiness.Arrange(p, b, c, u));
        }
Beispiel #31
0
        public static UrlModel CreateModel(string url, string desc)
        {
            UrlModel model = new UrlModel();

            model.Url = url;
            model.Desc = desc;

            return model;
        }
 public UrlModelCreateOrUpdateCommand(UrlModel ent)
 {
     this.ent = ent;
 }