예제 #1
0
        public void IsValidShouldReturnFalseWhenTheSpecifiedValueIsNotString()
        {
            UrlValidator urlValidator = new UrlValidator();

            Assert.AreEqual(false, urlValidator.IsValid(100));
            Assert.AreEqual(false, urlValidator.IsValid(new object()));
        }
예제 #2
0
        public async Task UrlValidator()
        {
            var em1 = await TestFns.NewEm(_serviceName);

            var custType   = em1.MetadataStore.GetEntityType(typeof(Customer));
            var validator  = new UrlValidator(null, UrlOptions.RequireProtocol);
            var validators = custType.GetDataProperty("Address").Validators;

            try {
                validators.Add(validator);
                var cust = new Customer()
                {
                    CompanyName = "Foo"
                };
                em1.AddEntity(cust);
                var valErrors = cust.EntityAspect.ValidationErrors;
                CustPropValAssert(cust, "asdf", 1);
                Assert.IsTrue(valErrors.First().Message.Contains("url"));
                CustPropValAssert(cust, "Pennsylvania 6500", 1);
                CustPropValAssert(cust, "1234567", 1);
                CustPropValAssert(cust, "traband.contuso.com", 1); // protocol missing

                CustPropValAssert(cust, null, 0);
                CustPropValAssert(cust, "http://traband", 0);
                CustPropValAssert(cust, "http://traband.contoso.com", 0);
                CustPropValAssert(cust, "https://traband.contoso.com", 0);
                CustPropValAssert(cust, "ftp://traband.contoso.com", 0);
                CustPropValAssert(cust, "http://traband.contoso.commiepinko", 0);
            } finally {
                validators.Remove(validator);
            }
        }
예제 #3
0
        public void Expect_valid_url_to_be_ok()
        {
            var validator = new UrlValidator();

            //Topper was here again
            validator.Validate("http://www.dn.se");
        }
예제 #4
0
 protected void CancelButton_Click(object sender, EventArgs e)
 {
     if (UrlValidator.IsUrlLocalToHost(Request, ReturnUrl))
     {
         Response.RedirectUser(ReturnUrl);
     }
 }
예제 #5
0
        private bool ValidateRequiredFields()
        {
            string message = string.Empty;

            if (String.IsNullOrWhiteSpace(textTitle.Text))
            {
                message += "Title is required.\n";
            }

            if (String.IsNullOrWhiteSpace(textLink.Text))
            {
                message += "Link is required.\n";
            }

            if (!UrlValidator.ValidateUrl(textLink.Text))
            {
                message += "Link Url is not valid!";
            }

            if (String.IsNullOrWhiteSpace(textDesc.Text))
            {
                message += "Description is required.\n";
            }

            if (message != String.Empty)
            {
                MessageBox.Show(message);
                return(false);
            }

            return(true);
        }
        private bool ValidateRequiredFields(Channel channel)
        {
            string message = String.Empty;

            if (String.IsNullOrWhiteSpace(channel.Title))
            {
                message += "Title is required.\n";
            }

            if (String.IsNullOrWhiteSpace(channel.Description))
            {
                message += "Description is required.\n";
            }

            if (String.IsNullOrWhiteSpace(channel.Link))
            {
                message += "Link is required.\n";
            }

            if (!UrlValidator.ValidateUrl(channel.Link))
            {
                message += "Link Url is not valid!";
            }

            if (message != String.Empty)
            {
                MessageBox.Show(message);
                return(false);
            }

            return(true);
        }
예제 #7
0
        public async Task <UserIdentificationResultDto> IdentifyUser(IdentityUrlDto urlDto)
        {
            var url = await urlRepository.GetByIdAsync(id : urlDto.Id);

            var urlValidator        = new UrlValidator();
            var urlValidationResult = urlValidator.Validate(url);

            UserIdentificationResultDto userIdentificationResult;

            if (!urlValidationResult.IsValid)
            {
                userIdentificationResult            = mapper.Map <UserIdentificationResultDto>(urlValidationResult);
                userIdentificationResult.IsUrlValid = false;
                return(userIdentificationResult);
            }

            if (url.NumberOfRuns.HasValue && url.NumberOfRuns > 0)
            {
                --url.NumberOfRuns;
                urlRepository.Update(url);
                await unitOfWork.SaveAsync();
            }

            var intervieweeNameValidator        = new UrlIntervieweeNameValidator(urlDto.IntervieweeName);
            var intervieweeNameValidationResult = intervieweeNameValidator.Validate(url);

            userIdentificationResult            = mapper.Map <UserIdentificationResultDto>(intervieweeNameValidationResult);
            userIdentificationResult.IsUrlValid = true;
            return(userIdentificationResult);
        }
예제 #8
0
        public void ValidateUrlTest()
        {
            _urlValidator = new UrlValidator();

            Assert.AreEqual(_urlValidator.Validate(_hotels[0]).Uri, _hotels[0].Uri);
            Assert.AreEqual(_urlValidator.Validate(_hotels[2]).Uri, null);
        }
        public ActionResult <string> Post([FromBody] UrlRequest urlRequest)
        {
            string longUrl;

            if (!(urlRequest.LongUrl.StartsWith("http://") || urlRequest.LongUrl.StartsWith("https://") || urlRequest.LongUrl.StartsWith("ftp://") || urlRequest.LongUrl.StartsWith("file://")))
            {
                longUrl = "http://" + urlRequest.LongUrl;
            }
            else
            {
                longUrl = urlRequest.LongUrl;
            }
            Console.WriteLine("im here!");
            if (UrlValidator.validator(longUrl))
            {
                UrlRequest request = new UrlRequest()
                {
                    LongUrl = longUrl
                };
                UrlResorce shortUrl = urlMapper.setShortUrl(request);
                return(Ok(shortUrl));
            }
            else
            {
                return(BadRequest());
            }
        }
예제 #10
0
        public void ShouldHaveValidationErrors(string wrongUrl)
        {
            // Arrange
            var validator = new UrlValidator();

            // Act & Assert
            validator.ShouldHaveValidationErrorFor(x => x, wrongUrl);
        }
예제 #11
0
        public void ValidationFailsForInvalidUrls()
        {
            UrlValidator validator = new UrlValidator();

            Assert.IsFalse(validator.IsValid(this, "http://www"));
            Assert.IsFalse(validator.IsValid(this, ".www.bbc.co.uk"));
            Assert.IsFalse(validator.IsValid(this, "ftp:///my.ftp.site"));
        }
예제 #12
0
        public void GetValidUrl_ActionExecutes_ReturnValidUrl(string input, string expected)
        {
            var validator = new UrlValidator();

            var result = validator.GetValidUrl(input);

            Assert.Equal(expected, result);
        }
예제 #13
0
        public override IValidator Build()
        {
            IValidator validator = new UrlValidator();

            ConfigureValidatorMessage(validator);

            return(validator);
        }
예제 #14
0
        public void IsValid_ActionExecutes_TrueOrFalse(string input, bool expected)
        {
            var validator = new UrlValidator();

            var result = validator.IsValid(input);

            Assert.Equal(expected, result);
        }
예제 #15
0
        public void SetUp()
        {
            _validator = new UrlValidator();

            _modelStub = new Mock<Url>();
            _modelStub.Setup(m => m.Address).Returns("http://jroliveira.net");
            _modelStub.Setup(e => e.Account.Id).Returns(1);
        }
예제 #16
0
        public async Task <UrlValidationResultDto> CheckIsUrlValid(int urlId)
        {
            var url = await urlRepository.GetByIdAsync(id : urlId);

            var urlValidator = new UrlValidator();
            var result       = urlValidator.Validate(url);

            return(mapper.Map <UrlValidationResultDto>(result));
        }
예제 #17
0
        public void ValidationPassesForValidUrls()
        {
            UrlValidator validator = new UrlValidator();

            Assert.IsTrue(validator.IsValid(this, "http://www.castleproject.org"));
            Assert.IsTrue(validator.IsValid(this, "http://www.bbc.co.uk"));
            Assert.IsTrue(validator.IsValid(this, "ftp://my.ftp.site"));
            Assert.IsTrue(validator.IsValid(this, "http://www.tickets.com/file.extension?id=something"));
        }
예제 #18
0
        public static bool Create(Address address, List <string> urlsCollection)
        {
            bool urlExists = UrlValidator.Validate(address.LongUrl);

            if (urlExists)
            {
                address.ShortUrl     = UrlGenerator.Generate(urlsCollection);
                address.CreationData = DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
            }
            return(urlExists);
        }
예제 #19
0
        /// <summary>
        /// Constructs a new instance of the <see cref="frmBannedHosts"/> form.
        /// </summary>
        public frmBannedHosts()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            globals   = Globals.Instance();
            validator = UrlValidator.Instance();
            globals.LoadedForms[this.Name] = this;
        }
예제 #20
0
        public static IRuleBuilderOptions <T, string> IsValidUrl <T>([NotNull] this IRuleBuilder <T, string> ruleBuilder)
        {
            if (ruleBuilder == null)
            {
                throw new ArgumentNullException(nameof(ruleBuilder));
            }

            var urlValidator = new UrlValidator();

            return(ruleBuilder.SetValidator(urlValidator));
        }
예제 #21
0
        /// <summary>
        /// Constructs a new instance of the <see cref="frmBannedHosts"/> form.
        /// </summary>
        public frmBannedHosts()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            globals = Globals.Instance();
            validator = UrlValidator.Instance();
            globals.LoadedForms[this.Name] = this;
        }
예제 #22
0
        public void IsValidTest()
        {
            var validator = new UrlValidator();

            Assert.IsFalse(validator.IsValid("htp://google.com"));
            Assert.IsFalse(validator.IsValid("www.google.com"));
            Assert.IsFalse(validator.IsValid("bing.com"));
            Assert.IsTrue(validator.IsValid("http://www.bing.com"));
            Assert.IsTrue(validator.IsValid("https://duckduckgo.com/"));
            Assert.IsTrue(validator.IsValid("https://abc.xyz/"));
        }
 public void AssertInvalidUrls(
     [Values(
         "google.com",
         "www.google.com",
         "google",
         "http://google",
         "amqp://google.com")]
         string url)
 {
     UrlValidator urlValidator = new UrlValidator();
     Assert.AreEqual(false, urlValidator.IsValid(url), string.Format(CultureInfo.CurrentCulture, "The url '{0}' should be invalid", url));
 }
예제 #24
0
        /// <summary>
        /// Creates a new instance of the <see cref="frmInsertUrl"/> form.
        /// </summary>
        public frmInsertUrl()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            globals        = Globals.Instance();
            sessionIDRegex = new Regex(@"([0-9a-fA-F]{40,64})|([\{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|\}]?)$", RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);       //@"^([0-9a-f]{32})|(\{?[0-9a-f]{8}-([0-9a-f]{4}-){3}-[0-9a-f]{12}\}?)$"
            validator      = UrlValidator.Instance();
            globals.LoadedForms[this.Name] = this;
        }
예제 #25
0
        /// <summary>
        /// Creates a new instance of the <see cref="frmInsertUrl"/> form.
        /// </summary>
        public frmInsertUrl()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            globals = Globals.Instance();
            sessionIDRegex = new Regex(@"([0-9a-fA-F]{40,64})|([\{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|\}]?)$", RegexOptions.CultureInvariant|RegexOptions.Multiline|RegexOptions.IgnoreCase|RegexOptions.Compiled); //@"^([0-9a-f]{32})|(\{?[0-9a-f]{8}-([0-9a-f]{4}-){3}-[0-9a-f]{12}\}?)$"
            validator = UrlValidator.Instance();
            globals.LoadedForms[this.Name] = this;
        }
예제 #26
0
        static void Main(string[] args)
        {
            // Create an instance of the custom URL redirection validator.
            UrlValidator validator = new UrlValidator();

            // Get the user's email address and password from the console.
            IUserData userData = UserDataFromConsole.GetUserData();

            // Create an ExchangeService object with the user's credentials.
            ExchangeService myService = new ExchangeService();

            myService.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password);


            Console.WriteLine("Getting EWS URL using custom validator...");

            // Call the Autodisocer service with the custom URL validator.
            myService.AutodiscoverUrl(userData.EmailAddress, validator.ValidateUrl);
            TimeSpan    ts              = new TimeSpan(0, -1, 0, 0);
            DateTime    date            = DateTime.Now.Add(ts);
            PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);

            itempropertyset.RequestedBodyType = BodyType.Text;
            SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

            if (myService != null)
            {
                ItemView itemview = new ItemView(1000);
                itemview.PropertySet = itempropertyset;

                FindItemsResults <Item> findResults = myService.FindItems(WellKnownFolderName.Inbox, filter, itemview);
                List <News>             newsList    = new List <News>();
                if (findResults.Items.Count > 0)
                {
                    foreach (Item item in findResults)
                    {
                        item.Load(itempropertyset);
                        string   Body      = item.Body.Text.ToString().Replace("\r\n", "");
                        string[] emailBody = Body.Split('|');
                        Dictionary <string, string> dictionary = new Dictionary <string, string>();
                        foreach (var item11 in emailBody)
                        {
                            dictionary.Add(item11.Substring(0, item11.LastIndexOf(':')).Trim(), item11.Substring(item11.LastIndexOf(':') + 1).Trim());
                        }
                        dictionary.Add("IsPublish", item.Importance.ToString() == "High" ? "True" : "False");
                        var test = helper.GetObject <News>(dictionary);
                        newsList.Add(test);
                    }
                    Generation.process(newsList);
                }
            }
        }
예제 #27
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         BindAllDropDowns();
         SetCreditCardOnFileDetails(CurrentOrder);
         BindShippingDetailGrid();
         if (UrlValidator.IsUrlLocalToHost(Request, Request.UrlReferrer.PathAndQuery))
         {
             ReturnUrl = Request.UrlReferrer.PathAndQuery;
         }
     }
 }
예제 #28
0
        public void AssertInvalidUrls(
            [Values(
                 "google.com",
                 "www.google.com",
                 "google",
                 "http://google",
                 "amqp://google.com")]
            string url)
        {
            UrlValidator urlValidator = new UrlValidator();

            Assert.AreEqual(false, urlValidator.IsValid(url), string.Format(CultureInfo.CurrentCulture, "The url '{0}' should be invalid", url));
        }
예제 #29
0
        public ActionResult UrlShortener([FromBody] UrlShortenerRequest request)
        {
            if (!UrlValidator.IsValid(request.Url))
            {
                return(BadRequest("Not a valid URL"));
            }
            var id = GenerateShortUrl();
            var shortUrlDetails = new ShortUrlDetail {
                Id = id, OriginalUrl = request.Url, ShortUrl = $"https://localhost:5001/{id}"
            };

            _DB.Add(shortUrlDetails);

            return(Ok(shortUrlDetails));
        }
예제 #30
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="OpcDaServer" /> class.
        /// </summary>
        /// <param name="uri">The server URI.</param>
        public OpcDaServer(Uri uri)
        {
            UrlValidator.CheckOpcUrl(uri);

            Uri             = uri;
            ComProxyBlanket = ComProxyBlanket.Default;

            var shutdown = new OpcShutdown();

            shutdown.Shutdown    += OnShutdown;
            ComWrapper.RpcFailed += OnRpcFailed;

            _shutdownConnectionPoint = new ConnectionPoint <IOPCShutdown>(shutdown);
            _clientName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
        }
예제 #31
0
        /// <summary>
        /// Url
        /// </summary>
        /// <typeparam name="T">DataType</typeparam>
        public static void Url <T>(params ValidationField <T>[] fields)
        {
            string        validatorKey = string.Format("{0}", typeof(UrlValidator).FullName);
            DataValidator validator    = null;

            if (_validatorList.ContainsKey(validatorKey))
            {
                validator = _validatorList[validatorKey];
            }
            else
            {
                validator = new UrlValidator();
                _validatorList.Add(validatorKey, validator);
            }
            SetValidation <T>(validator, fields);
        }
        static void Main(string[] args)
        {
            FileRepository fileRepository = new FileRepository();

            fileRepository.Load("./Source.txt");

            UrlValidator validator = new UrlValidator();
            ILogger      logger    = LogManager.GetCurrentClassLogger();
            UrlConverter converter = new UrlConverter(validator, logger);

            XmlSerializer xmlSerializer = new XmlSerializer();

            xmlSerializer.Serialize(converter.Convert(fileRepository.Provide()), "./Result.txt");

            Console.ReadLine();
        }
        private void MenuGenerateReport_Click(object sender, RoutedEventArgs e)
        {
            // TODO  same as analyzeButton_Click ^
            var urlValidator = new UrlValidator();

            if (urlValidator.IsValid(UrlTextBox.Text))
            {
                var analyzer = new Analyzer(UrlTextBox.Text, KeywordTextBox.Text);
                analyzer.Analyze();
                ReportsGenerator.GenerateReport(analyzer);
            }
            else
            {
                MessageBox.Show(this, "Please enter valid url/keyword!", "Error", MessageBoxButton.OK,
                                MessageBoxImage.Warning);
            }
        }
        private void analyzeButton_Click(object sender, RoutedEventArgs e)
        {
            // TODO  make a function using the code below
            var urlValidator = new UrlValidator();

            if (urlValidator.IsValid(UrlTextBox.Text))
            {
                var analyzer = new Analyzer(UrlTextBox.Text, KeywordTextBox.Text);
                analyzer.Analyze();
                ReportsGenerator.GenerateReport(analyzer, ref ReportDataGrid);
            }
            else
            {
                MessageBox.Show(this, "Please enter valid url/keyword!", "Error", MessageBoxButton.OK,
                                MessageBoxImage.Warning);
            }
        }
 public void AssertValidUrls(
     [Values(
         "http://google.com",
         "http://apps.google.com",
         "http://www.google.com",
         "http://ms1.apps.google.com",
         "https://google.com",
         "https://apps.google.com",
         "https://www.google.com",
         "https://ms1.apps.google.com",
         "ftp://google.com",
         "ftp://ftp.google.com",
         "http://google.it")]
         string url)
 {
     UrlValidator urlValidator = new UrlValidator();
     Assert.AreEqual(true, urlValidator.IsValid(url), string.Format(CultureInfo.CurrentCulture, "The url '{0}' should be valid", url));
 }
예제 #36
0
        public UrlsModule(
            GetAll getAll,
            GetByUrl getByShortened,
            CreateCommand create,
            ExcludeCommand exclude,
            UrlValidator validator,
            IMapper mapper)
        {
            _getAll = getAll;
            _getByShortened = getByShortened;
            _create = create;
            _exclude = exclude;
            _validator = validator;
            _mapper = mapper;

            this.RequiresAuthentication();

            Get["urls/", true] = All;
            Get["accounts/{id}/urls/", true] = All;
            Get["urls/{url}", true] = ByUrl;
            Post["urls/", true] = Create;
            Delete["urls/{id}", true] = Exclude;
        }
예제 #37
0
    public async Task UrlValidator() {
      var em1 = await TestFns.NewEm(_serviceName);

      var custType = em1.MetadataStore.GetEntityType(typeof(Customer));
      var validator = new UrlValidator(null, UrlOptions.RequireProtocol);
      var validators = custType.GetDataProperty("Address").Validators;
      try {
        validators.Add(validator);
        var cust = new Customer() { CompanyName = "Foo" };
        em1.AddEntity(cust);
        var valErrors = cust.EntityAspect.ValidationErrors;
        CustPropValAssert(cust, "asdf", 1);
        Assert.IsTrue(valErrors.First().Message.Contains("url"));
        CustPropValAssert(cust, "Pennsylvania 6500", 1);
        CustPropValAssert(cust, "1234567", 1); 
        CustPropValAssert(cust, "traband.contuso.com", 1); // protocol missing
        
        CustPropValAssert(cust, null, 0);
        CustPropValAssert(cust, "http://traband", 0); 
        CustPropValAssert(cust, "http://traband.contoso.com", 0);
        CustPropValAssert(cust, "https://traband.contoso.com", 0);
        CustPropValAssert(cust, "ftp://traband.contoso.com", 0);
        CustPropValAssert(cust, "http://traband.contoso.commiepinko", 0);
        

      } finally {
        validators.Remove(validator);
      }
    }
 public void IsValidShouldReturnFalseWhenTheSpecifiedValueIsNotString()
 {
     UrlValidator urlValidator = new UrlValidator();
     Assert.AreEqual(false, urlValidator.IsValid(100));
     Assert.AreEqual(false, urlValidator.IsValid(new object()));
 }
 public void IsValidShouldReturnTrueWhenTheSpecifiedValueIsNull()
 {
     UrlValidator urlValidator = new UrlValidator();
     Assert.AreEqual(true, urlValidator.IsValid(null));
 }