IsMatch() public method

public IsMatch ( string input ) : bool
input string
return bool
        public override void DataSet(string myPath, string myPattern)
        {
            string[] fileList = Directory.GetFiles(myPath, myPattern, SearchOption.AllDirectories);

            Regex regexMov = new Regex(MovieContents.REGEX_MOVIE_EXTENTION, RegexOptions.IgnoreCase);
            Regex regexJpg = new Regex(@".*\.jpg$|.*\.jpeg$", RegexOptions.IgnoreCase);
            Regex regexLst = new Regex(@".*\.wpl$|.*\.asx$", RegexOptions.IgnoreCase);

            foreach (string file in fileList)
            {
                listFileInfo.Add(new common.FileContents(file, myPath));

                if (regexMov.IsMatch(file))
                    MovieCount++;
                if (regexJpg.IsMatch(file))
                    ImageCount++;
                if (regexLst.IsMatch(file))
                    ListCount++;

                if (regexJpg.IsMatch(file) && ImageCount == 1)
                    StartImagePathname = file;
            }
            ColViewListFileInfo = CollectionViewSource.GetDefaultView(listFileInfo);

            if (ColViewListFileInfo != null && ColViewListFileInfo.CanSort == true)
            {
                ColViewListFileInfo.SortDescriptions.Clear();
                ColViewListFileInfo.SortDescriptions.Add(new SortDescription("FileInfo.LastWriteTime", ListSortDirection.Ascending));
            }
        }
 private void addNumberItems(ToolStripMenuItem s, bool addSubchildren)
 {
     ToolStripMenuItem item;
     ((ToolStripDropDownMenu)s.DropDown).ShowImageMargin = false;
     if (s.DropDownItems.Count == 0)
     {
         Regex rx = new Regex("^[0-9]+$");
         int start = rx.IsMatch(s.Text) ? 0 : 1;
         for (int i = start; i < 10; i++)
         {
             item = new ToolStripMenuItem(string.Format("{0}{1}", rx.IsMatch(s.Text) ? s.Text : "", i));
             item.DisplayStyle = ToolStripItemDisplayStyle.Text;
             item.Padding = new Padding(0);
             item.Margin = new Padding(0);
             item.DropDownOpening += new EventHandler(ToolStripMenuItem_DropDownOpening);
             item.Click += new EventHandler(ToolStripMenuItem_Click);
             s.DropDownItems.Add(item);
         }
     }
     // Check sub-children.
     if (addSubchildren)
     {
         for (int i = 0; i < s.DropDownItems.Count; i++)
         {
             addNumberItems((ToolStripMenuItem)s.DropDownItems[i], false);
         }
     }
 }
        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            var regexItem = new Regex("^[a-zA-Z ]*$");
            String firstName = txtFirstName.Text;
            String lastName = txtLastName.Text;
            String team = cmbTeam.Text;
            int price = 0;

            if (regexItem.IsMatch(firstName) && regexItem.IsMatch(lastName) && Int32.TryParse(txtPrice.Text, out price))
            {
                if(!playerList.Any())
                {
                    playerList.Add(new Player(firstName, lastName, team, price));
                    lblStatusBox.Text = "Pelaaja lisätty.";
                }
                else if(!Exists(firstName, lastName))
                {
                    playerList.Add(new Player(firstName, lastName, team, price));
                    lblStatusBox.Text = "Pelaaja lisätty.";
                }
                else
                {
                    lblStatusBox.Text = "Virhe: Pelaaja löytyy jo luettelosta.";
                }

            }
            else
            {
                lblStatusBox.Text = "Virhe: Kentissä käytetty vääriä merkkejä!";
            }

        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string PrimerNumero = txtPrimerNumero.Text;
            string SegundoNumero = txtSegundoNumero.Text;

            string error = string.Empty;
            Regex r = new Regex(@"^\d+$");

            if (!r.IsMatch(PrimerNumero) && PrimerNumero[0] != '-')
            {
                error += " El primer valor introducido no es valido, verifique que sea un numero de menos de 500 digitos por favor/n";
            }

            if (!r.IsMatch(SegundoNumero) && SegundoNumero[0] != '-')
            {
                error += " El segundo valor introducido no es valido, verifique que sea un numero de menos de 500 digitos por favor/n";
            }

            if (error.Length > 0)
            {
                MessageBox.Show(error);
            }
            else
            {
                try
                {
                    lblRespuesta.Text = delegadoKaratsuba.Multiplicar(PrimerNumero, SegundoNumero);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }
 private void btnSave_Click(object sender, EventArgs e)
 {
     int messageShowSecond;
     if(!int.TryParse(txtSecond.Text, out messageShowSecond))
     {
         MessageBox.Show("你输入的整数是错误的");
         return;
     }
     Regex reg = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", RegexOptions.Compiled);
     if(!reg.IsMatch(txtTelecomDns.Text))
     {
         MessageBox.Show("你输入的电信DNS IP格式不对");
         return;
     }
     if (!reg.IsMatch(txtUnicomDns.Text))
     {
         MessageBox.Show("你输入的网通DNS IP格式不对");
         return;
     }
     string encode = radUTF8.Checked ? "UTF-8" : "GB2312";
     string linkQuickUse = radNoQuick.Checked ? "0" : "1";
     string addMicroComment = radNoComment.Checked ? "0" : "1";
     string saveComment = radDelComment.Checked ? "0" : "1";
     string saveToSysDir = radSysDir.Checked ? "1" : "0";
     string isFront = radFront.Checked ? "1" : "0";
     HostsDal.SaveConfig(encode, linkQuickUse, addMicroComment, saveComment, saveToSysDir,
         messageShowSecond, isFront, txtTelecomDns.Text, txtUnicomDns.Text);
     this.Close();
 }
        public static IGiveable Read(string url)
        {
            var rgxGoG = new Regex(@"(gog\.com/(?:en/)?gamecard/\w+)", RegexOptions.IgnoreCase);

            var rgxDesura = new Regex(@"(desura\.com/games/[\w-]+)/*");

            if (!rgxGoG.IsMatch(url) && !rgxSteamStore.IsMatch(url) && !rgxDesura.IsMatch(url))
            {
                return null;
            }

            if (rgxGoG.IsMatch(url))
            {
                return GoG(PageReader(rgxGoG.Match(url).Groups[1].Value));
            }

            if (rgxDesura.IsMatch(url))
            {
                return Desura(PageReader(rgxDesura.Match(url).Groups[1].Value));
            }

            if (!rgxSteamStore.IsMatch(url))
            {
                throw new ArgumentException("This url is not supported right now.", "url");
            }

            int steamId = Convert.ToInt32(rgxSteamStore.Match(url).Groups[2].Value);
            if (rgxSteamStore.Match(url).Groups[1].Value == "sub")
            {
                return SteamSub(steamId);
            }
            return SteamApp(steamId);
        }
        /// <summary>
        ///     Generates a url pointing to the website placehold.it.
        /// </summary>
        /// <param name="size">The size of the image</param>
        /// <param name="format">The format the image</param>
        /// <param name="backgroundColor">The image background color.</param>
        /// <param name="textColor">The image text/foreground color.</param>
        /// <param name="text">The text on the image.</param>
        /// <returns>The generated image.</returns>
        /// <exception cref="ArgumentException">
        ///     <para>
        ///         If the <paramref name="size" /> is not in the format '300' and not in the format '300x300'.
        ///     </para>
        ///     <para>
        ///         If the background color is not a hex color value without '#'
        ///     </para>
        ///     <para>
        ///         If the text color is not a hex color value without '#'
        ///     </para>
        /// </exception>
        public static string Placeholdit(
            string size = "300x300",
            PlaceholditImageFormat format = PlaceholditImageFormat.png,
            string backgroundColor = null,
            string textColor = null,
            string text = null)
        {
            if (!Regex.IsMatch(size, @"^[0-9]+(x[0-9]+)?$"))
                throw new ArgumentException("size should be specified in format '300' or '300x300", "size");
            var regex = new Regex("^(?:[A-Fa-f0-9]{3}|[A-fa-f0-9]{6})$");
            if (backgroundColor != null && !regex.IsMatch(backgroundColor))
                throw new ArgumentException("backgroundColor must be a hex value without '#'", "backgroundColor");
            if (textColor != null && !regex.IsMatch(textColor))
                throw new ArgumentException("textColor must be a hex value without '#'", "textColor");

            var imageUrl = "https://placehold.it/" + size;
            if (!string.IsNullOrEmpty(backgroundColor))
                imageUrl += "/" + backgroundColor;
            if (!string.IsNullOrEmpty(textColor))
            {
                if (string.IsNullOrEmpty(backgroundColor))
                    imageUrl += "/D3D3D3";
                imageUrl += "/" + textColor;
            }
            imageUrl += "." + format;
            if (!string.IsNullOrEmpty(text))
                imageUrl += "?text=" + text;

            return imageUrl;
        }
Beispiel #8
0
 public void Test6()
 {
     var regex = new Regex(@"^//{1}[^0-9]+\n{1}");
     Assert.Equal("//***\n", regex.Match("//***\n0***9***7").Value);
     Assert.False(regex.IsMatch("/***\n0***9***7"));
     Assert.False(regex.IsMatch("123//***\n0***9***7"));
 }
Beispiel #9
0
        /*
         * Ham kiem tra chuoi
         */
        public static bool functionCheck(string sNumber)
        {
            // Tach chuoi theo ' ' va dua vao mang moi
            string[] sArray = new string[] { };
            sArray = sNumber.Split(' ');

            // Kiem tra cu phap chuoi
            switch (sArray.Length)
            {
                case 2:     // Dung cu phap
                    Regex regex = new Regex(@"^[0-9]*$");
                    bool flag1 = regex.IsMatch(sArray[0]);
                    bool flag2 = regex.IsMatch(sArray[1]);
                    if (flag1 && flag2)                                                     // So thu nhat dung - So thu hai dung
                    {
                        return true;
                    }
                    else
                    {
                        string error = "Thong bao\t- Loi dau vao: <";
                        if (!flag1 && !flag2) { error += sArray[0] + "> , <" + sArray[1]; } // So thu nhat sai  - So thu hai sai
                        else if (!flag1) { error += sArray[0]; }                            // So thu nhat sai  - So thu hai dung
                        else { error += sArray[1]; }                                        // So thu nhat dung - So thu hai sai
                        error += "> khong hop le!";
                        Console.WriteLine(error);
                    }
                    break;
                default:    // Sai cu phap
                    Console.WriteLine("Thong bao\t- Loi dau vao: Sai cu phap!");
                    break;
            }
            return false;
        }
Beispiel #10
0
 private void Application_BeginRequest(object sender, EventArgs e)
 {
     var app = (HttpApplication)sender;
     foreach (var rule in GetRuleList())
     {
         var lookFor = "^" + ResolveUrl(app.Request.ApplicationPath, rule.LookFor) + "$";
         var re = new Regex(lookFor, RegexOptions.IgnoreCase);
         if (IsHttpUrl(rule.LookFor))
         {
             if (re.IsMatch(app.Request.Url.AbsoluteUri))
             {
                 var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Url.AbsoluteUri, rule.SendTo));
                 RewritePath(app.Context, sendTo);
                 break;
             }
         }
         else
         {
             if (re.IsMatch(app.Request.Path))
             {
                 var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Path, rule.SendTo));
                 RewritePath(app.Context, sendTo);
                 break;
             }
         }
     }
 }
        public EmailValidationResult Validate(EmailReport report, ReportRule rule)
        {
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(report.GetEmailMessage().Body);

            var body = htmlDocument.DocumentNode.Find(HtmlElementType.Body).FirstOrDefault();
            var blocks = htmlDocument.DocumentNode.Find("#block");
            var tables = htmlDocument.DocumentNode.Find(HtmlElementType.Table);
            var styleRegex = new Regex(@"background[\s]*:.*(!#fff|!#ffffff|white|transparent)");
            var isVisibleColor = new Func<string, bool>(x =>
                                                            {
                                                                var value = x.ToLower();
                                                                var hiddenValues = new string[] { "#fff", "#ffffff", "white", "transparent" };
                                                                return !string.IsNullOrEmpty(value) && !hiddenValues.Any(y => value.Contains(y));
                                                            });

            var valid = body == null ||
                        (body.Attributes.Any(x => x.Name.ToLower() == "bgcolor" && isVisibleColor(x.Value)) ||
                        body.Attributes.Any(x => x.Name.ToLower() == "style" && styleRegex.IsMatch(x.Value.ToLower())) ||
                        blocks.Any(block => block.Attributes.Any(x => x.Name.ToLower() == "style" && styleRegex.IsMatch(x.Value.ToLower()))) ||
                        blocks.Any(block => block.Attributes.Any(x => x.Name.ToLower() == "bgcolor" && isVisibleColor(x.Value))) ||
                        tables.Any(table => table.Attributes.Any(x => x.Name.ToLower() == "style" && styleRegex.IsMatch(x.Value.ToLower()))) ||
                        tables.Any(table => table.Attributes.Any(x => x.Name.ToLower() == "bgcolor" && isVisibleColor(x.Value))));

            return new EmailValidationResult
                       {
                           Valid = valid,
                           ReportRule = rule
                       };
        }
        public void TestCreditCardNumberRegex()
        {
            ContentPolicyReader cpr = new ContentPolicyReader();
            List<ContentRule> contentRules = cpr.Read(contentPolicy);
            Assert.AreEqual(4, contentRules.Count);

            ContentRule personalInformationRule = contentRules[0];
            Assert.AreEqual(3, personalInformationRule.Conditions.Count);

            ContentCondition ccCondition = personalInformationRule.Conditions[0];
            Assert.AreEqual(sReCCN, ccCondition.Regex);

            Regex reCCN = new Regex(sReCCN);

            // Ensure we correctly match valid credit card numbers
            foreach (string sValidCCN in CreditCardNumberTestData.Valid)
            {
                Assert.IsTrue(reCCN.IsMatch(sValidCCN), "Expected to match a valid credit card number");
            }

            // Ensure we don't false positive on non-valid numbers
            foreach (string sNonValidCCN in CreditCardNumberTestData.NonValid)
            {
                Assert.IsFalse(reCCN.IsMatch(sNonValidCCN), "Expected NOT to match a non-valid credit card number");
            }
        
        }
 private void MockDir(DirectoryItem item)
 {
     directoryMock.Exists(item.FullPath).Returns(true);
     var dirFiles = item.Children.OfType<FileItem>().ToList();
     List<DirectoryItem> subDirs = item.Children.OfType<DirectoryItem>().ToList();
     subDirs.ForEach(MockDir);
     dirFiles.ForEach(f=>MockFile(item, f));
     List<string> allFiles = dirFiles.Select(f => Path.Combine(item.FullPath, f.Name)).ToList();
     directoryMock.EnumerateFiles(item.FullPath).Returns(allFiles);
     directoryMock.EnumerateFiles(item.FullPath, Arg.Any<string>())
         .Returns
         ((callInfo)=>
              {
                  var searchPattern = (string)callInfo.Args()[1];
                  var regex = new Regex(WildcardToRegex(searchPattern));
                  return allFiles.Where(f => regex.IsMatch(f));
              }
         );
     directoryMock.EnumerateFiles(item.FullPath, Arg.Any<string>(), SearchOption.AllDirectories)
         .Returns(c =>
         {
             var files = new List<string>();
             var searchPattern = (string)c.Args()[1];
             var regex = new Regex(WildcardToRegex(searchPattern));
             GetSubDirs(item).ForEach(sd => files.AddRange(directoryMock.EnumerateFiles(sd.FullPath, searchPattern)
                 .Where(f => regex.IsMatch(f))));
             files.AddRange(allFiles.Where(f => regex.IsMatch(f)));
             return files;
         });
     directoryMock.EnumerateDirectories(item.FullPath).Returns(subDirs.Select(_=>_.FullPath).ToList());
 }
        private bool ValidClass(CreateClassModel aCreateClassModel)
        {
            if (string.IsNullOrEmpty(aCreateClassModel.UniversityId) || aCreateClassModel.UniversityId.Equals(Constants.SELECT)) {
                theValidationDictionary.AddError("UniversityId", aCreateClassModel.UniversityId, "A university is required.");
            }

            Regex myAlphaNumericRegex = new Regex("^[a-zA-Z0-9]+$");
            if (!myAlphaNumericRegex.IsMatch(aCreateClassModel.ClassSubject)) {
                theValidationDictionary.AddError("ClassSubject", aCreateClassModel.ClassSubject, "A class code must be provided and must be only letters and numbers.");
            }

            if (!myAlphaNumericRegex.IsMatch(aCreateClassModel.ClassCourse)) {
                theValidationDictionary.AddError("ClassCourse", aCreateClassModel.ClassCourse, "A class code must be provided and must be only letters and numbers.");
            }

            if (string.IsNullOrEmpty(aCreateClassModel.ClassTitle)) {
                theValidationDictionary.AddError("ClassTitle", aCreateClassModel.ClassTitle, "A class title must be provided.");
            }

            if (theClassRepository.GetClass(aCreateClassModel.ClassSubject, aCreateClassModel.ClassCourse) != null) {
                theValidationDictionary.AddError("Class", string.Empty, "That class already exists.");
            }

            return theValidationDictionary.isValid;
        }
        /// <summary>
        /// Authenticates the user
        /// </summary>
        /// <param name="user">user from login form</param>
        /// <param name="password">password from login form</param>
        public static bool Authenticate(String user,String password)
        {
            var positiveIntRegex = new Regex(@"^\w+$");
            if (!positiveIntRegex.IsMatch(user))
            {
                return false;
            }
            if (!positiveIntRegex.IsMatch(password))
            {
                return false;
            }

            String encryptedPass = Encrypt(password);
            string constr = Settings.Default.UserDbConnectionString;
            SqlConnection con = new SqlConnection(constr);
            SqlCommand command = new SqlCommand();
            command.Connection = con;
            command.Parameters.AddWithValue("@Username", user);
            command.CommandText = "SELECT Password FROM Users WHERE Name = @Username";
            command.CommandType = CommandType.Text;

            con.Open();
            string _password = "";
            if (command.ExecuteScalar() != null)
                _password = command.ExecuteScalar().ToString();
            else
                return false;
            con.Close();
            if (encryptedPass.Equals(_password))
            {
                return true;
            }
            return false;
        }
Beispiel #16
0
 /// <summary>
 /// Returns a randomly generated string of a specified length, containing
 /// only a set of characters, and at max a specified number of non alpha numeric characters.
 /// </summary>
 /// <param name="length">Length of the string</param>
 /// <param name="allowedCharacters">Characters allowed in the string</param>
 /// <param name="numberOfNonAlphaNumericsAllowed">Number of non alpha numeric characters allowed.</param>
 /// <returns>A randomly generated string of a specified length, containing only a set of characters, and at max a specified number of non alpha numeric characters.</returns>
 public string NextString(int length, string allowedCharacters, int numberOfNonAlphaNumericsAllowed)
 {
     if (length < 1)
         return "";
     var tempBuilder = new StringBuilder();
     var comparer = new Regex(allowedCharacters);
     var alphaNumbericComparer = new Regex("[0-9a-zA-z]");
     int counter = 0;
     while (tempBuilder.Length < length)
     {
         var tempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
         if (comparer.IsMatch(tempValue))
         {
             if (!alphaNumbericComparer.IsMatch(tempValue) && numberOfNonAlphaNumericsAllowed > counter)
             {
                 tempBuilder.Append(tempValue);
                 ++counter;
             }
             else if (alphaNumbericComparer.IsMatch(tempValue))
             {
                 tempBuilder.Append(tempValue);
             }
         }
     }
     return tempBuilder.ToString();
 }
        internal void BiosMotherBoard()
        {
            try
            {
                searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Manufacturer,SerialNumber FROM Win32_BIOS");
                ManagementObjectCollection bios = searcher.Get();
                //Log.WritWTime("bios info = " + bios.Count.ToString());
                foreach (ManagementObject queryObj in bios)
                {
                    if (queryObj.GetPropertyValue("SerialNumber") != null)
                        sysData.compSerialNum = queryObj.GetPropertyValue("SerialNumber").ToString().Trim();
                    Regex alpha = new Regex(@"^[A-Za-z\s]+$");
                    if (alpha.IsMatch(sysData.compSerialNum))
                    {// IS alphabetic or space therefore presumed not to be real serial number
                        sysData.compSerialNum = string.Empty;
                    }
                    Log.WritW("WMIbios: serial: " + sysData.compSerialNum);
                    if (sysData.compSerialNum == string.Empty)
                    {
                        ManagementObjectSearcher searcherbb = new ManagementObjectSearcher("root\\CIMV2", "SELECT Manufacturer,SerialNumber FROM Win32_Baseboard");
                        ManagementObjectCollection baseboard = searcherbb.Get();
                        foreach (ManagementObject item in baseboard)
                        {
                            if (alpha.IsMatch(sysData.compModel))
                            {//If we have a non useful serial we test the model to make sure that is useful
                                sysData.compModel = "Motherboard";
                            }
                            sysData.compManufacturer = item.GetPropertyValue("Manufacturer").ToString().Trim();
                            if (item.GetPropertyValue("SerialNumber") != null)
                            {
                                sysData.compSerialNum = item.GetPropertyValue("SerialNumber").ToString().Trim();
                                Log.WritW("Baseboard: serial: " + sysData.compSerialNum);
                            }
                        }
                    }
                    else
                        sysData.compSerialNum = queryObj.GetPropertyValue("SerialNumber").ToString().Trim();
                }
                sysData.compManufacturer = regExpCommaFind.Replace(sysData.compManufacturer, "").Trim();    // remove commas
                sysData.compModel = regExpCommaFind.Replace(sysData.compModel, "").Trim();
                sysData.compSerialNum = regExpCommaFind.Replace(sysData.compSerialNum, "").Trim();

                if (sysData.compManufacturer == "innotek GmbH" && (sysData.compSerialNum == "0" || sysData.compSerialNum == "")) //We have aVirtual Box systemtrue)
                {
                    VBoxSerial();   // setup serial number for virtual box
                }
                if (sysData.compSerialNum == string.Empty || sysData.compSerialNum.Contains("ÿÿÿÿÿ"))    //will get here for 6310 with intel wireless, or optiflex ydiaeresis
                {//use mac address since nothing else available
                    sysData.compSerialNum = macAddress;
                }
                Log.WritW("End of BiosBaseboard: serial: " + sysData.compSerialNum);
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An Error occurred while querying Baseboard or BIOS WMI data: " + e.Message, "Tax-Aide Inventory Data Collection");
                Log.WritW("An Error occurred while querying BIOS,Baseboard WMI data: " + e.Message);
                Environment.Exit(0);
            }
        }
        private void btnCreateNewPlayer_Click(object sender, RoutedEventArgs e)
        {
            int checkPlayer = 0;
            int fault = 1;

            Regex reg = new Regex("(^[1-9]+$)");
            Regex pattern = new Regex("(^[a-ö]+$)");

            if (!reg.IsMatch(txtPrice.Text) || !pattern.IsMatch(txtFname.Text) || !pattern.IsMatch(txtLname.Text))
            {
                fault = 0;
            }

            // tarkistetaan että käyttäjä on täyttänyt kaikki tarvittavat kentät ja että pelaajaa ei ole ennestään rekisterissä
            if (txtFname.Text != "" && txtLname.Text != "" && txtPrice.Text != "" && cmbTeam.Text != "" && fault == 1)
            {
                Player pelaaja = new Player(txtFname.Text, txtLname.Text, cmbTeam.Text, Double.Parse(txtPrice.Text));

                if (Players.Count != 0)
                {
                    for (int num = 0; num != Players.Count; num++)
                    {
                        if (Players[num].Get_KokoNimi() == pelaaja.Get_KokoNimi())
                        {
                            MessageBox.Show("Tämä pelaaja on jo olemassa!");
                            checkPlayer = 1;
                        }
                    }

                    if (checkPlayer == 0)
                    {
                        Players.Add(pelaaja);

                        lsbShowPlayers.Items.Add(pelaaja.Get_KokoNimi());

                        tbStatus.Items.Add("Player added");
                    }
                }
                else
                {
                    Players.Add(pelaaja);

                    lsbShowPlayers.Items.Add(pelaaja.Get_KokoNimi());

                    tbStatus.Items.Add("Player added");
                }
            }
            else
            {
                if (txtFname.Text == "" || txtLname.Text == "" || txtPrice.Text == "" || cmbTeam.Text == "")
                {
                    MessageBox.Show("Täytä kaikki tiedot");
                }
                else
                {
                    MessageBox.Show("Invalid input");
                }
            }
        }
Beispiel #19
0
        public void WordsTest()
        {
            var regex = new Regex(@"^(\w|-)*$");

            Assert.True(regex.IsMatch("bob"));
            Assert.True(regex.IsMatch("bob1"));
            Assert.True(regex.IsMatch("bob-bib"));
        }
		public void TestPostCode ()
		{
			Regex rx = new Regex(@"^[A-Z]{2}[0-9]\s?[0-9]{1,2}[A-Z]{2}$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

			Assert.IsTrue(rx.IsMatch("PL7 4EG"));
			Assert.IsTrue(rx.IsMatch("BS14PS"));
			Assert.IsTrue(rx.IsMatch("BS1 44PS"));
		}
        public override PackageValidationOutput is_valid(IPackage package)
        {
            if (string.IsNullOrWhiteSpace(package.Copyright) && package.Authors == null) return true;

            var regex = new Regex(EmailRegexPattern);

            return !regex.IsMatch(package.Copyright.to_lower()) && !regex.IsMatch(package.Authors.Join(" ").to_lower());
        }
Beispiel #22
0
 private bool IsBfInputGood()
 {
     Regex doubleReg = new Regex(@"^\d+\.?\d*$");
     if (doubleReg.IsMatch(inputWeight.Text) && doubleReg.IsMatch(inputWaist.Text))
         return true;
     else
         return false;
 }
		public void TestSurname ()
		{
			Regex rx = new Regex(@"^[A-Z][A-Za-z’-]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

			Assert.IsTrue(rx.IsMatch("Wickstead"));
			Assert.IsTrue(rx.IsMatch("Mcghee"));
			Assert.IsTrue(rx.IsMatch("ElMcGonzo"));
		}
Beispiel #24
0
        public void TestNameDoesntContainANumber()
        {
            var regex = new Regex(@"(\d)");

            Assert.True(regex.IsMatch("12ame"));
            Assert.True(regex.IsMatch("N12ame"));
            Assert.True(regex.IsMatch("N12"));
        }
Beispiel #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Regex noSpecChar = new Regex(@"^[a-zA-Z0-9_\s-]+$");
            if (IsPostBack)
            {
                if (txtTitle.Text == "" || txtDescription.Text == "" || !(noSpecChar.IsMatch(txtTitle.Text)))
                {
                    headerTag.InnerHtml = "Coleman University<br />There Are Errors In Your Channel";
                    if (txtTitle.Text == "")
                    {
                        lblTitleError.Text = "The title is required!";
                    }
                    else if(!(noSpecChar.IsMatch(txtTitle.Text)))
                    {
                        lblTitleError.Text = "There are illegal characters in your title";
                    }
                    else
                    {
                        lblTitleError.Text = "";
                    }

                    if (txtDescription.Text == "")
                    {
                        lblDescriptionError.Text = "The description is required!";
                    }
                    else
                    {
                        lblDescriptionError.Text = "";
                    }
                }
                else
                {
                    lblTitleError.Text = "";
                    lblDescriptionError.Text = "";
                    try
                    {
                        XDocument feed = new XDocument(
                            new XElement("rss",
                                new XAttribute("version", "2.0"),
                                new XElement("channel",
                                    new XElement("title", new XCData(txtTitle.Text)),
                                    new XElement("link", ""),
                                    new XElement("description", new XCData(txtDescription.Text)))));
                        feed.Save(Server.MapPath("~") + @"datafiles\" + txtTitle.Text + ".xml");

                        headerTag.InnerHtml = "Coleman University<br />Congrats! You made a new channel!";
                        txtTitle.Text = "";
                        txtDescription.Text = "";
                    }
                    catch (Exception error)
                    {
                        headerTag.InnerHtml = "Coleman University<br />Oh No! Error: " + error.Message;
                        txtTitle.Text = "";
                        txtDescription.Text = "";
                    }
                }
            }
        }
Beispiel #26
0
        public override string Execute(string[] args, UUID fromAgentID)
        {
            if (args.Length < 1)
                return "Usage: primregex [text predicat]";

            try
            {
                // Build the predicat from the args list
                string predicatPrim = string.Empty;
                for (int i = 0; i < args.Length; i++)
                    predicatPrim += args[i] + " ";
                predicatPrim = predicatPrim.TrimEnd();

                // Build Regex
                Regex regexPrimName = new Regex(predicatPrim.ToLower());

                // Print result
                Logger.Log(string.Format("Searching prim for [{0}] ({1} prims loaded in simulator)\n", predicatPrim,
                    Client.Network.CurrentSim.ObjectsPrimitives.Count), Helpers.LogLevel.Info, Client);

                Client.Network.CurrentSim.ObjectsPrimitives.ForEach(
                    delegate(Primitive prim)
                    {
                        bool match = false;
                        string name = "(unknown)";
                        string description = "(unknown)";


                        match = (prim.Text != null && regexPrimName.IsMatch(prim.Text.ToLower()));

                        if (prim.Properties != null && !match)
                        {
                            match = regexPrimName.IsMatch(prim.Properties.Name.ToLower());
                            if (!match)
                                match = regexPrimName.IsMatch(prim.Properties.Description.ToLower());
                        }

                        if (match)
                        {
                            if (prim.Properties != null)
                            {
                                name = prim.Properties.Name;
                                description = prim.Properties.Description;
                            }
                            Logger.Log(string.Format("\nNAME={0}\nID = {1}\nFLAGS = {2}\nTEXT = '{3}'\nDESC='{4}'", name,
                                prim.ID, prim.Flags.ToString(), prim.Text, description), Helpers.LogLevel.Info, Client);
                        }
                    }
                );
            }
            catch (System.Exception e)
            {
                Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e);
                return "Error searching";
            }

            return "Done searching";
        }
Beispiel #27
0
        public override void decodeCssString(string cssString)
        {
            Inset = false;

            char[] splitChars = { ' ' };
            string[] tokens = cssString.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);

            if (tokens.Length < 2)
            {
                Debug.WriteLine("Error in BoxShadow css rule need to have a h and v position");
                return;
            }
            string position = tokens[0] + " " + tokens[1];
            ShadowPosition = new CssPosition();
            ShadowPosition.decodeCssString(position);

            if (tokens.Length >= 3)
            {
                Regex regex = new Regex("\\d");
                string blurSpread = "";
                if (regex.IsMatch(tokens[2]))
                {
                    blurSpread = tokens[2];
                }
                else
                {
                    ShadowColor = CssHelpers.decodeColorString(tokens[2]);
                }

                if (tokens.Length >= 4)
                {
                    if (regex.IsMatch(tokens[3]))
                    {
                        blurSpread += " " + tokens[3];
                    }
                    else
                    {
                        ShadowColor = CssHelpers.decodeColorString(tokens[3]);
                    }
                }

                BlurSpread = new CssPosition();
                BlurSpread.decodeCssString(blurSpread);

                if (tokens.Length >= 6)
                {
                    ShadowColor = CssHelpers.decodeColorString(tokens[4]);
                    if (tokens[5] == "inset")
                    {
                        Inset = true;
                    }
                }
                else
                {
                    ShadowColor = CssHelpers.decodeColorString(tokens[4]);
                }
            }
        }
Beispiel #28
0
 private bool IsInputGood()
 {
     Regex ageRegex = new Regex(@"^[\d]{2}$");
     Regex doubleRegex = new Regex(@"^\d+[\.]?\d*$");
     if (ageRegex.IsMatch(bmiInputAge.Text) && doubleRegex.IsMatch(bmiInputHeight.Text) && doubleRegex.IsMatch(bmiInputWeight.Text))
         return true;
     else
         return false;
 }
Beispiel #29
0
 public void TestNumbers()
 {
     var re = new Regex("[.0-9]+");
     Assert.That(re.IsMatch("..."));
     Assert.That(re.IsMatch("123"));
     Assert.That(re.IsMatch("1.23"));
     Assert.That(re.IsMatch("1.2.3"));
     Assert.That(re.IsMatch("a.1.2.3"));
 }
Beispiel #30
0
        /// <summary>
        /// whether this category matches the target category
        /// </summary>
        // public bool Match(string targetCategory)
        public bool Match(Regex targetCategory)
        {
            if (null == targetCategory)
            {
                throw new ArgumentNullException("targetCategory");
            }

            return targetCategory.IsMatch(CATEGORY_ALL)
                || targetCategory.IsMatch(category);
        }
        /// <summary>
        /// 转换为日期时间
        /// </summary>
        public static DateTime?ToSafeDateTime(this string dateTime)
        {
            DateTime result;

            Text.RegularExpressions.Regex re = new Text.RegularExpressions.Regex(@"^\d+$");
            if (re.IsMatch(dateTime) && dateTime.Length == 18)
            {
                // 如果为18位的文件时间,那么在这里处理
                var tempDate = System.DateTime.FromFileTime(Convert.ToInt64(dateTime));
                return(tempDate);
            }
            else if (DateTime.TryParse(dateTime, out result))
            {
                return(result);
            }
            return(null);
        }
Beispiel #32
0
        /// <summary>
        /// Verify the VersionData complex type related requirements
        /// </summary>
        /// <param name="versionDataArray">An array of VersionData object.</param>
        /// <param name="isSchemaVerified">A Boolean value indicates whether the schema has been verified.</param>
        private void VerifyVersionDataComplexType(VersionData[] versionDataArray, bool isSchemaVerified)
        {
            #region Verify MS-VERSS_R56
            // Add the debug information
            Site.Log.Add(LogEntryKind.Debug, "Verify MS-VERSS_R56");

            // Verify MS-VERSS requirement: MS-VERSS_R56
            Site.CaptureRequirementIfIsTrue(
                isSchemaVerified,
                56,
                @"[In VersionData] The VersionData complex type specifies the details about a single version of a file.
<s:complexType name=""VersionData"">
  <s:attribute name=""version"" type=""s:string"" use=""required"" />
  <s:attribute name=""url"" type=""s:string"" use=""required"" />
  <s:attribute name=""created"" type=""s:string"" use=""required"" />
  <s:attribute name=""createdRaw"" type=""s:string"" use=""required"" />  
  <s:attribute name=""createdBy"" type=""s:string"" use=""required"" />
  <s:attribute name=""createdByName"" type=""s:string"" use=""optional"" />
  <s:attribute name=""size"" type=""s:unsignedLong"" use=""required"" />
  <s:attribute name=""comments"" type=""s:string"" use=""required"" />
</s:complexType>");
            #endregion

            #region Verify MS-VERSS_R58
            // According to MS-OFCGLOS,the current version is the latest version of a document.
            // Then current version is the most recent version of the file.
            // If the current version is preceded with an at sign (@),then R58 will be verified.
            string currentVersion = AdapterHelper.GetCurrentVersion(versionDataArray);

            // Add the debug information
            Site.Log.Add(LogEntryKind.Debug, "Verify MS-VERSS_R58, the value of current version is {0}", currentVersion);

            bool isR58Verified = currentVersion.StartsWith("@", System.StringComparison.CurrentCulture);

            // Verify MS-VERSS requirement: MS-VERSS_R58
            Site.CaptureRequirementIfIsTrue(
                isR58Verified,
                58,
                @"[In VersionData] version: The most recent version of the file MUST be preceded with an at sign (@).");
            #endregion

            #region Verify MS-VERSS_R59
            foreach (VersionData versionData in versionDataArray)
            {
                if (versionData.version != currentVersion)
                {
                    float versionNumber;
                    bool  isR59Verified = float.TryParse(versionData.version, out versionNumber);

                    // Add the debug information
                    Site.Log.Add(
                        LogEntryKind.Debug,
                        "Verify MS-VERSS_R59, the value of version is {0}",
                        versionData.version);

                    // Verify MS-VERSS requirement: MS-VERSS_R59
                    Site.CaptureRequirementIfIsTrue(
                        isR59Verified,
                        59,
                        @"[In VersionData] version: All the other versions MUST exist without any prefix. ");
                }
            }
            #endregion

            #region Verify MS-VERSS_R60101
            foreach (VersionData versionData in versionDataArray)
            {
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^@?\d+\.\d+$");

                bool isR60101Verified = regex.IsMatch(versionData.version);

                if (Common.IsRequirementEnabled(60101, this.Site))
                {
                    // Add the debug information
                    Site.Log.Add(
                        LogEntryKind.Debug,
                        "Verify MS-VERSS_R60101, the value of attribute version in VersionData is {0}",
                        versionData.version);

                    // Verify MS-VERSS requirement: MS-VERSS_R60101
                    Site.CaptureRequirementIfIsTrue(
                        isR60101Verified,
                        60101,
                        @"[In Appendix B: Product Behavior] Implementation does contain the version of the file, including the major version and minor version numbers connected by period, for example, ""1.0"". (Windows SharePoint Services 3.0 and above follow this behavior.)");
                }
            }
            #endregion

            #region Verify MS-VERSS_R61
            foreach (VersionData versionData in versionDataArray)
            {
                System.Uri versionDataUrl = new System.Uri(versionData.url);
                bool       isR61Verified  = AdapterHelper.ValidateAbsoluteUrlFormat(versionDataUrl);

                // Add the debug information
                Site.Log.Add(
                    LogEntryKind.Debug,
                    "Verify MS-VERSS_R61, the value of attribute URL in VersionData is {0}",
                    versionData.url);

                // Verify MS-VERSS requirement: MS-VERSS_R61
                Site.CaptureRequirementIfIsTrue(
                    isR61Verified,
                    61,
                    @"[In VersionData] url: The complete URL of the version of the file.");
            }
            #endregion

            #region Verify MS-VERSS_R164
            foreach (VersionData versionData in versionDataArray)
            {
                bool isR16401Enabled = Common.IsRequirementEnabled(16401, this.Site);
                bool isR16402Enabled = Common.IsRequirementEnabled(16402, this.Site);

                if (isR16401Enabled)
                {
                    // Add the debug information
                    Site.Log.Add(LogEntryKind.Debug, "Verify MS-VERSS_R16401");

                    // Verify MS-VERSS requirement: MS-VERSS_R16401
                    Site.CaptureRequirementIfIsNotNull(
                        versionData.createdRaw,
                        16401,
                        @"[In Appendix B: Product Behavior] Implementation does return this attribute. [In VersionData] createdRaw: The creation date and time for the version of the file in Datetime format, as specified in [ISO-8601]. (Microsoft SharePoint Foundation 2010 and above follow this behavior.)");
                }

                if (isR16402Enabled)
                {
                    // Add the debug information
                    Site.Log.Add(LogEntryKind.Debug, "Verify MS-VERSS_R16402");

                    // Verify MS-VERSS requirement: MS-VERSS_R16402
                    Site.CaptureRequirementIfIsNull(
                        versionData.createdRaw,
                        16402,
                        @"[In Appendix B: Product Behavior] Implementation does not return this attribute. [In VersionData] createdRaw: The creation date and time for the version of the file in Datetime format, as specified in [ISO-8601]. (<1> Section 2.2.4.3: Windows SharePoint Services 3.0 does not return this attribute.)");
                }
            }
            #endregion

            #region Verify MS-VERSS_R65
            foreach (VersionData versionData in versionDataArray)
            {
                // Add the debug information
                Site.Log.Add(
                    LogEntryKind.Debug,
                    "Verify MS-VERSS_R65, the value of attribute comments in VersionData is {0}",
                    versionData.comments);

                // Verify MS-VERSS requirement: MS-VERSS_R65
                Site.CaptureRequirementIfIsNotNull(
                    versionData.comments,
                    65,
                    @"[In VersionData] comments: The comment entered when the version of the file was replaced on the protocol server during check in.");
            }
            #endregion
        }
Beispiel #33
0
 public static bool IsMatch(this string s, string pattern)
 {
     System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);
     return(reg.IsMatch(s));
 }
Beispiel #34
0
 private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
 {
     System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("[^0-9.-]+");
     e.Handled = re.IsMatch(e.Text);
 }
Beispiel #35
0
        private void btnCheckUserName_Click(object sender, System.EventArgs e)
        {
            string pattern = "[\\u4e00-\\u9fa5a-zA-Z0-9]+[\\u4e00-\\u9fa5_a-zA-Z0-9]*";

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
            if (!regex.IsMatch(this.txtUserName.Text.Trim()) || this.txtUserName.Text.Trim().Length < 2 || this.txtUserName.Text.Trim().Length > 20)
            {
                this.ShowMessage("用户名不能为空,必须以汉字或是字母开头,且在2-20个字符之间", false);
            }
            else
            {
                if (this.txtUserName.Text.Contains(","))
                {
                    this.ShowMessage("用户名不能包含逗号", false);
                }
                else
                {
                    Hidistro.Membership.Core.IUser user = Hidistro.Membership.Context.Users.FindUserByUsername(this.txtUserName.Text.Trim());
                    if (user != null && user.UserRole != Hidistro.Membership.Core.Enums.UserRole.SiteManager && user.UserRole != Hidistro.Membership.Core.Enums.UserRole.Anonymous)
                    {
                        Hidistro.Membership.Core.IUser user2 = Hidistro.Membership.Context.Users.GetUser(0, this.txtUserName.Text.Trim(), false, true);
                        if (user.UserRole == Hidistro.Membership.Core.Enums.UserRole.Distributor)
                        {
                            if (Hidistro.Membership.Context.HiContext.Current.SiteSettings.IsDistributorSettings && user2.UserId != Hidistro.Membership.Context.HiContext.Current.SiteSettings.UserId.Value)
                            {
                                this.ShowMessage("分销商只能在自己的站点或主站上登录", false);
                                return;
                            }
                        }
                        else
                        {
                            if (Hidistro.Membership.Context.HiContext.Current.SiteSettings.IsDistributorSettings)
                            {
                                Hidistro.Membership.Context.Member member = user2 as Hidistro.Membership.Context.Member;
                                if (!member.ParentUserId.HasValue || member.ParentUserId.Value != Hidistro.Membership.Context.HiContext.Current.SiteSettings.UserId)
                                {
                                    this.ShowMessage("您不是本站会员,请您进行注册", false);
                                    return;
                                }
                            }
                            else
                            {
                                Hidistro.Membership.Context.Member member = user2 as Hidistro.Membership.Context.Member;
                                if (member.ParentUserId.HasValue && member.ParentUserId.Value != 0)
                                {
                                    this.ShowMessage("您不是本站会员,请您进行注册", false);
                                    return;
                                }
                            }
                        }
                        if (this.dropType.SelectedIndex == 0)
                        {
                            if (!string.IsNullOrEmpty(user.PasswordQuestion))
                            {
                                if (this.litUserQuestion != null)
                                {
                                    this.litUserQuestion.Text = user.PasswordQuestion.ToString();
                                }
                                this.panelShow("InputAnswer");
                            }
                            else
                            {
                                this.ShowMessage("您没有设置密保问题,无法找回密码,请自行联系管理员修改密码", false);
                            }
                        }
                        else
                        {
                            if (this.dropType.SelectedIndex == 1)
                            {
                                if (user is Hidistro.Membership.Context.Member)
                                {
                                    Hidistro.Membership.Context.Member member = user as Hidistro.Membership.Context.Member;
                                    if (!string.IsNullOrEmpty(member.CellPhone))
                                    {
                                        if (this.litMobile != null)
                                        {
                                            this.litMobile.Text = member.CellPhone.Substring(0, 3) + "****" + member.CellPhone.Substring(7);
                                        }
                                        this.panelShow("CellPhone");
                                    }
                                    else
                                    {
                                        this.ShowMessage("没有设置手机号码", false);
                                    }
                                }
                                else
                                {
                                    if (user is Hidistro.Membership.Context.Distributor)
                                    {
                                        Hidistro.Membership.Context.Distributor distributor = user as Hidistro.Membership.Context.Distributor;
                                        if (!string.IsNullOrEmpty(distributor.CellPhone))
                                        {
                                            if (this.litMobile != null)
                                            {
                                                this.litMobile.Text = distributor.CellPhone.Substring(0, 3) + "****" + distributor.CellPhone.Substring(7);
                                            }
                                            this.panelShow("CellPhone");
                                        }
                                        else
                                        {
                                            this.ShowMessage("没有设置手机号码", false);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (this.dropType.SelectedIndex == 2)
                                {
                                    if (!string.IsNullOrEmpty(user.Email))
                                    {
                                        if (this.litEmail != null)
                                        {
                                            this.litEmail.Text = user.Email;
                                        }
                                        this.panelShow("Email");
                                    }
                                    else
                                    {
                                        this.ShowMessage("没有设置电子邮箱", false);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        this.ShowMessage("该用户不存在", false);
                    }
                }
            }
        }
Beispiel #36
0
 public static bool IsNumeros(string texto)
 {
     System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex("[^0-9]");
     return(!oRegex.IsMatch(texto));
 }
Beispiel #37
0
 /// <summary>
 /// 2.限制折扣正则
 /// </summary> 只能输入0-1之间的两个小数,比如 0.0.~ 0.99
 /// /// <param name="str"></param>
 /// <returns></returns>/^(0|[1-9]\d*)(\s|$|.\d{1,2}\b)/
 public static bool IsDiscount(string str)
 {
     System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^((0\.[1-9]{1})|(([1-9]{1})(\.\d{1})?))$");
     return(reg1.IsMatch(str));
 }
Beispiel #38
0
 /// <summary>
 /// 判断是否含有除了字母及数字外的其他字符
 /// </summary>
 /// <param name="str">要验证的字符串</param>
 /// <returns>返回true代表不包含汉字或者特殊字符</returns>
 public static bool StrIsNumberOrLetters(string str)
 {
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-z0-9]+$");
     return(regex.IsMatch(str));
 }
        private void btnEditHotkeyword_Click(object sender, System.EventArgs e)
        {
            int hid = System.Convert.ToInt32(this.txtHid.Value);

            if (string.IsNullOrEmpty(this.txtEditHotKeyword.Text.Trim()) || this.txtEditHotKeyword.Text.Trim().Length > 60)
            {
                this.ShowMsg("热门关键字不能为空,长度限制在60个字符以内", false);
                return;
            }
            //if (!this.dropEditCategory.SelectedValue.HasValue)
            //{
            //    this.ShowMsg("请选择商品主分类", false);
            //    return;
            //}
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^(?!_)(?!.*?_$)(?!-)(?!.*?-$)[a-zA-Z0-9_一-龥-]+$");
            if (!regex.IsMatch(this.txtEditHotKeyword.Text.Trim()))
            {
                this.ShowMsg("热门关键字只能输入汉字,数字,英文,下划线,减号,不能以下划线、减号开头或结尾", false);
                return;
            }
            //if (string.Compare(this.txtEditHotKeyword.Text.Trim(), this.hiHotKeyword.Value) != 0 && this.IsSame(this.txtEditHotKeyword.Text.Trim(), System.Convert.ToInt32(this.dropEditCategory.SelectedValue.Value)))
            //{
            //    this.ShowMsg("存在相同的的关键字,编辑失败", false);
            //    return;
            //}
            //if (((string.Compare(this.dropEditCategory.SelectedValue.Value.ToString(), this.hicategory.Value) == 0 & string.Compare(this.txtEditHotKeyword.Text, this.hiHotKeyword.Value) != 0) && this.IsSame(this.txtEditHotKeyword.Text.Trim(), System.Convert.ToInt32(this.dropEditCategory.SelectedValue.Value))) || (string.Compare(this.txtEditHotKeyword.Text.Trim(), this.hiHotKeyword.Value) == 0 && string.Compare(this.dropEditCategory.SelectedValue.Value.ToString(), this.hicategory.Value) != 0 && this.IsSame(this.txtEditHotKeyword.Text.Trim(), System.Convert.ToInt32(this.dropEditCategory.SelectedValue.Value))))
            //{
            //    this.ShowMsg("同一分类型不允许存在相同的关键字,编辑失败", false);
            //    return;
            //}

            if (this.dropEditCategory.SelectedValue.HasValue)
            {
                if (string.Compare(this.txtEditHotKeyword.Text.Trim(), this.hiHotKeyword.Value) == 0 && string.Compare(this.dropEditCategory.SelectedValue.Value.ToString(), this.hicategory.Value) == 0)
                {
                    return;
                }
                if (this.IsSame(this.txtEditHotKeyword.Text.Trim(), System.Convert.ToInt32(this.dropEditCategory.SelectedValue.Value)))
                {
                    this.ShowMsg("同一分类型不允许存在相同的关键字,编辑失败", false);
                    return;
                }
                StoreHelper.UpdateHotWords(hid, this.dropEditCategory.SelectedValue.Value, this.txtEditHotKeyword.Text.Trim(), HiContext.Current.User.UserId);
                this.ShowMsg("编辑热门关键字成功!", true);
                this.hicategory.Value   = "";
                this.hiHotKeyword.Value = "";
                this.BindData();
            }
            else
            {
                if (string.Compare(this.txtEditHotKeyword.Text.Trim(), this.hiHotKeyword.Value) == 0 && string.Compare("", this.hicategory.Value) == 0)
                {
                    return;
                }

                if (this.IsSame(this.txtEditHotKeyword.Text.Trim(), null))
                {
                    this.ShowMsg("同一分类型不允许存在相同的关键字,编辑失败", false);
                    return;
                }

                StoreHelper.UpdateHotWords(hid, null, this.txtEditHotKeyword.Text.Trim(), HiContext.Current.User.UserId);
                this.ShowMsg("编辑热门关键字成功!", true);
                this.hicategory.Value   = "";
                this.hiHotKeyword.Value = "";
                this.BindData();
            }
        }
 private bool IsIPAddressValid()
 {
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^((0|1[0-9]{0,2}|2[0-9]?|2[0-4][0-9]|25[0-5]|[3-9][0-9]?)\.){3}(0|1[0-9]{0,2}|2[0-9]?|2[0-4][0-9]|25[0-5]|[3-9][0-9]?)$");
     return(regex.IsMatch(ConnectionString.Split(':')[0]));
 }
Beispiel #41
0
        // 立即注册
        private void Btn_Reg_Click(object sender, EventArgs e)
        {
            // 获取控件值
            MyMd5        md5            = new MyMd5();
            const string TableUsers     = "t_users";
            string       strRegUserName = textBox_RegUserName.Text;             // 用户名 长度3-15字符
            string       strRegAcc      = textBox_RegAccount.Text;              // 注册帐号 长度6-20字符
            // 注册密码 长度6-20字母,数字或符号,采用MD5加密
            string strRegPasswd1 = md5.Md5Encrypt(textBox_RegPasswd1.Text);
            // 确认注册密码
            string strRegPasswd2     = md5.Md5Encrypt(textBox_RegPasswd2.Text);
            string strRegEmail       = textBox_RegEmail.Text;                           // 注册邮箱
            string sql_query_t_users = string.Format("SELECT * FROM {0} WHERE ACC='{1}'", TableUsers, strRegAcc);

            string[] returnData = new string[5];
            returnData = connSqlite.SelectDataFromSqlite(sql_query_t_users, returnData, 5);


            // 用户名
            if (string.IsNullOrEmpty(strRegUserName))
            {
                MessageBox.Show("亲,用户名不能为空!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (strRegUserName.Length < 2)
            {
                MessageBox.Show("亲,用户名不能少于2个字符!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            // 帐号
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$");
            if (string.IsNullOrEmpty(strRegAcc))
            {
                MessageBox.Show("亲,帐号不能为空!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (!reg.IsMatch(strRegAcc))
            {
                MessageBox.Show("亲, 帐号只能由字母和数字组成!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (string.Equals(strRegAcc, returnData[2]))
            {
                MessageBox.Show("亲,该帐号已注册,请更换帐号或登录!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            // 密码
            if (string.IsNullOrEmpty(strRegPasswd1))
            {
                MessageBox.Show("亲,密码不能为空!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (strRegPasswd1.Length < 6)
            {
                MessageBox.Show("亲,密码不能少于6位!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (string.IsNullOrEmpty(strRegPasswd2))
            {
                MessageBox.Show("亲,确认密码不能为空!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (strRegPasswd2.Length < 6)
            {
                MessageBox.Show("亲,确认密码不能少于6位!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (!string.Equals(strRegPasswd1, strRegPasswd2))
            {
                MessageBox.Show("两次输入的密码不一致!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            // 邮箱
            string expression = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            if (string.IsNullOrEmpty(strRegEmail))
            {
                MessageBox.Show("亲,邮箱不能为空!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (!Regex.IsMatch(strRegEmail, expression, RegexOptions.Compiled))
            {
                MessageBox.Show("对不起,邮箱格式不正确!", "警示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string sql_insert_t_users = string.Format("INSERT INTO {0} VALUES(NULL, '{1}', '{2}', '{3}', '{4}')", TableUsers, strRegUserName, strRegAcc, strRegPasswd1, strRegEmail);

            connSqlite.ExecuteSql(sql_insert_t_users);
            MessageBox.Show("恭喜!注册成功,请用该帐号登录!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();               // 关闭注册窗体
        }
Beispiel #42
0
 public static bool MatchStringFromRegex(string str, string regexstr)
 {
     str = str.Trim();
     System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regexstr);
     return(pattern.IsMatch(str));
 }
Beispiel #43
0
 public static bool IsRegexMatch(string regexPattern, string input)
 {
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     return(regex.IsMatch(input));
 }
Beispiel #44
0
 /// <summary>
 /// 验证参数
 /// <para>返回值:{ OK : false , Msg : "错误消息" }</para>
 /// </summary>
 /// <param name="parameters">需要进行验证的参数集合</param>
 /// <returns>{OK:false,Msg:"错误消息"}</returns>
 public static dynamic CheckParameters(params Parameter[] parameters)
 {
     //枚举 正则表达式 验证方式
     System.Text.RegularExpressions.Regex regex;
     foreach (Parameter temp in parameters)
     {
         regex = new System.Text.RegularExpressions.Regex(temp?.Regex ?? "");
         if (temp.IsCheck)
         {
             if (string.IsNullOrWhiteSpace(temp?.Value) || (!string.IsNullOrEmpty(temp?.Regex) && !regex.IsMatch(temp?.Value)))
             {
                 return(new { OK = false, Msg = temp?.Msg });
             }
         }
     }
     return(new { OK = true });
 }
Beispiel #45
0
 public static bool IsEmail(string email)
 {
     System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
     return(oRegex.IsMatch(email));
 }
Beispiel #46
0
 /// <summary>
 /// 3.限制输入正整数
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static bool IsInteger(string str)
 {
     System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(/*@"^([0-9]{1,}[.][0-9]*)$"*/ @"^[0-9]*$");
     return(reg1.IsMatch(str));
 }
Beispiel #47
0
 public static bool IsLetras(string texto)
 {
     System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex("[^a-zA-Z]");
     return(!oRegex.IsMatch(texto));
 }
        public void BindFiles()
        {
            // Store current selection.
            KeyValuePair selection = null;

            if (GameComboBox.SelectedIndex > -1)
            {
                selection = (KeyValuePair)GameComboBox.SelectedItem;
            }
            _files = new List <System.Diagnostics.FileVersionInfo>();
            var names = Directory.GetFiles(".", "*.exe");
            var list  = new List <FileInfo>();

            foreach (var name in names)
            {
                if (name.EndsWith("\\x360ce.exe"))
                {
                    continue;
                }
                list.Add(new FileInfo(name));
            }
            var options = new List <KeyValuePair>();

            options.Add(new KeyValuePair("", ""));
            foreach (var item in list)
            {
                var vi = System.Diagnostics.FileVersionInfo.GetVersionInfo(item.FullName);
                _files.Add(vi);
                var productName = (item.Name + ": " + vi.ProductName).Trim(new char[] { ':', ' ' });
                options.Add(new KeyValuePair(productName, item.Length.ToString()));
            }
            GameComboBox.DataSource    = options;
            GameComboBox.DisplayMember = "Key";
            GameComboBox.ValueMember   = "Value";
            GameComboBox.Enabled       = GameComboBox.Items.Count > 1;
            if (selection == null)
            {
                // Select best option automatically.
                var rxUppercase = new System.Text.RegularExpressions.Regex("[A-Z]");
                var rxLowercase = new System.Text.RegularExpressions.Regex("[A-Z]");
                for (int i = 0; i < options.Count; i++)
                {
                    var s = options[i].Key;
                    var v = options[i].Value;
                    if (rxUppercase.IsMatch(s) && rxLowercase.IsMatch(s) && s.Contains(" "))
                    {
                        GameComboBox.SelectedIndex = i; break;
                    }
                    else if (rxLowercase.IsMatch(s) && s.Contains(" "))
                    {
                        GameComboBox.SelectedIndex = i; break;
                    }
                    else if (rxLowercase.IsMatch(s))
                    {
                        GameComboBox.SelectedIndex = i; break;
                    }
                    // Select if value is not empty.
                    else if (rxLowercase.IsMatch(v) || rxUppercase.IsMatch(v))
                    {
                        GameComboBox.SelectedIndex = i; break;
                    }
                }
            }
            else
            {
                // Restore selection.
                for (int i = 0; i < options.Count; i++)
                {
                    if (options[i].Key == selection.Key && options[i].Value == selection.Value)
                    {
                        GameComboBox.SelectedIndex = i;
                        break;
                    }
                }
            }
            UpdateActionButtons();
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="barCodeInfo">物品信息</param>
        /// <param name="businessType">业务状态</param>
        /// <param name="strDJH">业务编号</param>
        /// <param name="isEnteringState">是否为录入状态</param>
        /// <param name="dicInfo">字典信息(库房,业务类型(MarketingType(库房业务),SubsidiaryOperationType(车间业务)))</param>
        public 产品编号(BarCodeInfo barCodeInfo, CE_BusinessType businessType, string strDJH,
                    bool isEnteringState, Dictionary <string, string> dicInfo)
        {
            m_enumBusinessType = businessType;

            switch (m_enumBusinessType)
            {
            case CE_BusinessType.库房业务:

                foreach (KeyValuePair <string, string> item in dicInfo)
                {
                    m_dicMarkInfo.Add(item.Key,
                                      GeneralFunction.StringConvertToEnum <CE_MarketingType>(item.Value));
                }

                break;

            case CE_BusinessType.车间业务:

                foreach (KeyValuePair <string, string> item in dicInfo)
                {
                    m_dicWorkShopInfo.Add(item.Key,
                                          GeneralFunction.StringConvertToEnum <CE_SubsidiaryOperationType>(item.Value));
                }

                break;

            case CE_BusinessType.综合业务:
                System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$");

                if (dicInfo != null)
                {
                    foreach (KeyValuePair <string, string> item in dicInfo)
                    {
                        if (rex.IsMatch(item.Key))
                        {
                            m_dicMarkInfo.Add(item.Key,
                                              GeneralFunction.StringConvertToEnum <CE_MarketingType>(item.Value));
                        }
                        else
                        {
                            m_dicWorkShopInfo.Add(item.Key,
                                                  GeneralFunction.StringConvertToEnum <CE_SubsidiaryOperationType>(item.Value));
                        }
                    }
                }

                break;

            default:
                break;
            }

            InitializeComponent();

            if (!isEnteringState)
            {
                ProductCode.ReadOnly = true;
                btnAdd.Enabled       = false;
                btnDelete.Enabled    = false;
                btnAuditing.Enabled  = false;
            }

            m_barCodeInfo = barCodeInfo;
            m_strBillID   = strDJH;

            m_server = AsynSocketFactory.GetSingletonServer(m_currentPort);
            m_server.Begin();

            m_server.OnConnected += new GlobalObject.DelegateCollection.SocketConnectEvent(AsynServer_OnConnected);
            m_server.OnReceive   += new ReceiveEventHandler(AsynServer_OnReceive);
        }
Beispiel #50
0
        public static string insertdata2(string result, string datess)
        {
            SQLiteConnection sqlite_connect;
            SQLiteCommand    sqlite_cmd;

            sqlite_connect = new SQLiteConnection("Data source=db/myData.db");
            sqlite_connect.Open();                       // Open
            sqlite_cmd = sqlite_connect.CreateCommand(); //create command
            result     = result.Replace("\r", "");
            result     = result.Replace("\\", "");
            result     = result.Replace("font10", "");
            result     = result.Replace("font", "");
            result     = result.Replace("pre", "");
            result     = result.Replace("'", "");
            result     = result.Replace(">", "");
            result     = result.Replace("<", "");
            result     = result.Replace("/", "");
            result     = result.Replace("size=1", "");
            string[] abc    = result.Split(' ');
            string[] arr    = new string[100000];
            string   values = "";

            int x         = 1;
            int start     = 0;
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            using (var transaction = sqlite_connect.BeginTransaction())
            {
                for (int i = 0; i < abc.Length; i++)
                {
                    string val = abc[i].Trim();
                    if (val == string.Empty)
                    {
                        continue;
                    }

                    arr[x] = val;
                    arr[x] = arr[x].Replace(",", "");
                    arr[x] = arr[x].Replace("\n", "");
                    arr[x] = arr[x].Replace("\n", "");
                    arr[x] = arr[x].Replace("*", "");
                    arr[x] = arr[x].Replace("&amp;", " ");

                    System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z]+$");
                    bool s = reg1.IsMatch(arr[x]);
                    if (s == true)
                    {
                        if (x >= 3 + (start * 10))
                        {
                            for (int z = (3 + (start * 10)); z <= x; z++)
                            {
                                arr[2 + (start * 10)] = arr[2 + (start * 10)] + " " + arr[z];
                            }

                            x = 2 + (start * 10);
                        }
                    }


                    x++;

                    if (x > 6 + (start * 10))
                    {
                        double puta = Convert.ToInt64(arr[3 + (start * 10)]);
                        double putb = Convert.ToInt64(arr[4 + (start * 10)]);
                        double putc = Convert.ToInt64(arr[5 + (start * 10)]);
                        double putd = Convert.ToInt64(arr[6 + (start * 10)]);
                        arr[7 + (start * 10)] = (Math.Round((puta * 100 / putc), 2)).ToString();
                        string puts = (Math.Round((putb * 100 / putd), 2)).ToString();
                        for (int j = 1 + (start * 10); j <= 8 + (start * 10); j++)
                        {
                            values = values + arr[j] + j;
                        }
                        sqlite_cmd.CommandText = "INSERT INTO stockdata VALUES (null,'" + arr[10 * start + 1] + "','" + arr[10 * start + 2] + "','" + datess + "','" + puta + "','" + putb + "','" + putc + "','" + putd + "','" + puts + "');";
                        sqlite_cmd.ExecuteNonQuery();//using behind every write cmd
                        start++;
                        x = 1 + (start * 10);
                    }
                }
                transaction.Commit();
            }
            sqlite_connect.Close();
            return(values);
        }
Beispiel #51
0
        protected bool IsNumeric(string value)
        {
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^[-+]?\d+\.?\d*$|^[-+]?\d*\.?\d+$");

            return(re.IsMatch(value));
        }
Beispiel #52
0
        public static bool isMACValid(String oldMacAddress, String newChar, int caretPosition, int selectionStart, int selectionLength)
        {
            String macAddress = oldMacAddress;

            if (caretPosition > selectionStart)
            {
                caretPosition = selectionStart;
            }

            if (selectionLength != 0)
            {
                macAddress = macAddress.Remove(selectionStart, selectionLength);
            }

            macAddress = macAddress.Insert(caretPosition, newChar);

            Char delimiter    = '.';
            Char oldDelimiter = '.';

            if (oldMacAddress.IndexOf(":") != -1)
            {
                oldDelimiter = ':';
            }

            if (oldMacAddress.IndexOf("-") != -1)
            {
                oldDelimiter = '-';
            }

            if (macAddress.IndexOf(":") != -1)
            {
                delimiter = ':';
            }

            if (oldDelimiter != '.' && delimiter != '.' && oldDelimiter != delimiter)
            {
                return(false);
            }

            if (macAddress.IndexOf("-") != -1)
            {
                delimiter = '-';
            }

            if (oldDelimiter != '.' && delimiter != '.' && oldDelimiter != delimiter)
            {
                return(false);
            }

            if (macAddress.StartsWith(":") || macAddress.StartsWith("-"))
            {
                return(false);
            }

            if (delimiter == '.')
            {
                delimiter = ':';

                String m = macAddress;

                macAddress = String.Empty;

                for (int i = 0; i < m.Length; i += 2)
                {
                    String sub = String.Empty;

                    if (i + 2 <= m.Length)
                    {
                        sub = m.Substring(i, 2);
                    }
                    else
                    {
                        sub = m.Substring(i, 1);
                    }

                    sub = sub.PadLeft(2, '0');

                    if (macAddress.Length > 0)
                    {
                        macAddress = macAddress + delimiter + sub;
                    }
                    else
                    {
                        macAddress = sub;
                    }
                }
            }

            string[] parts = macAddress.Split(delimiter);

            if (parts.Length > 8)
            {
                return(false);
            }

            Regex regex = new System.Text.RegularExpressions.Regex("[^0-9a-f]+", RegexOptions.IgnoreCase);

            foreach (String part in parts)
            {
                if (part.Length > 2)
                {
                    return(false);
                }

                if (regex.IsMatch(part))
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #53
0
 public bool IsMatch(string input) => _regex.IsMatch(input);
Beispiel #54
0
        public static bool blockCharForMAC(String macAddress, String newChar, int selectionStart, int selectionLength)
        {
            bool blockCharacter = false;

            Char delimiter = '.';

            bool delimiterEntered = false;
            bool delimiterAllowed = true;

            if (macAddress.IndexOf('-') >= 0)
            {
                delimiter        = '-';
                delimiterEntered = true;
            }

            if (macAddress.IndexOf(':') >= 0)
            {
                delimiter        = ':';
                delimiterEntered = true;
            }

            if (delimiterEntered == true)
            {
                int numDelimiter = macAddress.Split(delimiter).Length - 1;

                if (numDelimiter == 7 && (newChar == ":" || newChar == "-"))
                {
                    blockCharacter = true;

                    return(blockCharacter);
                }
            }
            else
            {
                if (macAddress.Length > 2)
                {
                    delimiterAllowed = false;
                }
            }

            Regex regex = new System.Text.RegularExpressions.Regex("[^0-9a-f]+", RegexOptions.IgnoreCase);

            if (delimiterEntered == true)
            {
                int index = macAddress.LastIndexOf(delimiter);

                int numChar = macAddress.Length - index - 1;

                if (numChar == 0)
                {
                    blockCharacter = (newChar == ":") || (newChar == "-") || (regex.IsMatch(newChar) == true);

                    return(blockCharacter);
                }

                if (numChar == 1)
                {
                    blockCharacter = regex.IsMatch(newChar);

                    return(blockCharacter);
                }

                if (numChar == 2)
                {
                    blockCharacter = ((newChar != delimiter.ToString())) || (regex.IsMatch(newChar) == false);

                    return(blockCharacter);
                }
            }
            else
            {
                if (delimiterAllowed)
                {
                    if ((macAddress.Length < 2) && ((newChar == ":") || (newChar == "-")))
                    {
                        blockCharacter = true;

                        return(blockCharacter);
                    }
                }
            }


            macAddress = macAddress.Replace(":", String.Empty);
            macAddress = macAddress.Replace("-", String.Empty);

            if (selectionLength == 0 && macAddress.Length == 16)
            {
                blockCharacter = true;

                return(blockCharacter);
            }


            bool isMatch = regex.IsMatch(newChar);

            if (isMatch == true)
            {
                if (delimiterEntered && newChar[0] == delimiter)
                {
                    isMatch = false;
                }
                else if ((delimiterEntered == false) && (delimiterAllowed == true))
                {
                    isMatch = (newChar != ":") && (newChar != "-");
                }
            }

            blockCharacter = isMatch;

            return(blockCharacter);
        }
Beispiel #55
0
        static public short DefBR = 5; //DefaultBuadRate
        public void data_set()         //各コンボボックスに値をセットする
        {
            cmbPortName.Items.Clear();
            cmbPortName.Text = "";

            notice_textBox.AppendText("SerialPort Update\r\n");

            //シリアルポート名をセット
            var                        check_reg    = new System.Text.RegularExpressions.Regex("(COM[1-9][0-9]?[0-9]?)");//正規表現
            ManagementClass            mcPnPEntity  = new ManagementClass("Win32_PnPEntity");
            ManagementObjectCollection manageObjCol = mcPnPEntity.GetInstances();

            //全てのPnPデバイスを探索しシリアル通信が行われるデバイスを随時追加する
            foreach (ManagementObject manageObj in manageObjCol)
            {
                //Nameプロパティを取得
                var namePropertyValue    = manageObj.GetPropertyValue("Name");
                var CaptionPropertyValue = manageObj.GetPropertyValue("PNPDeviceID");

                /*
                 * PowerShell
                 * Get-WmiObject -Class Win32_SerialPort
                 */

                if (namePropertyValue == null)
                {
                    continue;
                }

                //Nameプロパティ文字列の一部が"(COM1)~(COM999)"と一致するときリストに追加"
                string name = namePropertyValue.ToString();
                if (check_reg.IsMatch(name))
                {
                    cmbPortName.Items.Add(name);
                    if (cmbPortName.Items.Count > 0)
                    {
                        cmbPortName.SelectedIndex = 0;
                    }
                }
            }


            cmbBaudRate.Items.Clear();

            // ボーレート選択コンボボックスに選択項目をセットする.
            SerialClass.BuadRateItem baud;

            baud          = new SerialClass.BuadRateItem();
            baud.NAME     = "1200bps(リセット用)";
            baud.BAUDRATE = 1200;
            cmbBaudRate.Items.Add(baud);

            baud          = new SerialClass.BuadRateItem();
            baud.NAME     = "9600bps";
            baud.BAUDRATE = 9600;
            cmbBaudRate.Items.Add(baud);

            baud          = new SerialClass.BuadRateItem();
            baud.NAME     = "19200bps";
            baud.BAUDRATE = 19200;
            cmbBaudRate.Items.Add(baud);

            baud          = new SerialClass.BuadRateItem();
            baud.NAME     = "38400bps";
            baud.BAUDRATE = 38400;
            cmbBaudRate.Items.Add(baud);

            baud          = new SerialClass.BuadRateItem();
            baud.NAME     = "67600bps";
            baud.BAUDRATE = 57600;
            cmbBaudRate.Items.Add(baud);

            baud          = new SerialClass.BuadRateItem();
            baud.NAME     = "115200bps";
            baud.BAUDRATE = 115200;
            cmbBaudRate.Items.Add(baud);

            cmbBaudRate.SelectedIndex = DefBR;

            cmbHandShake.Items.Clear();

            // フロー制御選択コンボボックスに選択項目をセットする.
            SerialClass.HandShakeItem ctrl;
            ctrl           = new SerialClass.HandShakeItem();
            ctrl.NAME      = "NONE";
            ctrl.HANDSHAKE = Handshake.None;
            cmbHandShake.Items.Add(ctrl);

            ctrl           = new SerialClass.HandShakeItem();
            ctrl.NAME      = "XON/XOFF";
            ctrl.HANDSHAKE = Handshake.XOnXOff;
            cmbHandShake.Items.Add(ctrl);

            ctrl           = new SerialClass.HandShakeItem();
            ctrl.NAME      = "RTS/CTS";
            ctrl.HANDSHAKE = Handshake.RequestToSend;
            cmbHandShake.Items.Add(ctrl);

            ctrl           = new SerialClass.HandShakeItem();
            ctrl.NAME      = "XON/XOFF + RTS/CTS";
            ctrl.HANDSHAKE = Handshake.RequestToSendXOnXOff;
            cmbHandShake.Items.Add(ctrl);
            cmbHandShake.SelectedIndex = 0;
        }
 private static bool IsTextNumeric(String str)
 {
     System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
     return(reg.IsMatch(str));
 }
        void Main(string s)
        {
            Regex r;

            r = new Regex("");                                                              // Compliant, less than 3 characters
            r = new Regex("**");                                                            // Compliant, less than 3 characters
            r = new Regex("+*");                                                            // Compliant, less than 3 characters
            r = new Regex("abcdefghijklmnopqrst");                                          // Compliant, does not have the special characters
            r = new Regex("abcdefghijklmnopqrst+");                                         // Compliant, has only 1 special character
            r = new Regex("{abc}+defghijklmnopqrst");                                       // Noncompliant
            r = new Regex("{abc}+{a}");                                                     // Noncompliant {{Make sure that using a regular expression is safe here.}}
//              ^^^^^^^^^^^^^^^^^^^^^^
            r = new Regex("+++");                                                           // Noncompliant
            r = new Regex(@"\+\+\+");                                                       // Noncompliant FP (escaped special characters)
            r = new Regex("{{{");                                                           // Noncompliant
            r = new Regex(@"\{\{\{");                                                       // Noncompliant FP (escaped special characters)
            r = new Regex("***");                                                           // Noncompliant
            r = new Regex(@"\*\*\*");                                                       // Noncompliant FP (escaped special characters)
            r = new Regex("(a+)+s", RegexOptions.Compiled);                                 // Noncompliant
            r = new Regex("(a+)+s", RegexOptions.Compiled, TimeSpan.Zero);                  // Noncompliant
            r = new Regex("{ab}*{ab}+{cd}+foo*");                                           // Noncompliant

            Regex.IsMatch("", "(a+)+s");                                                    // Noncompliant
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
            Regex.IsMatch(s, "(a+)+s", RegexOptions.Compiled);                              // Noncompliant
            Regex.IsMatch("", "{foo}{bar}", RegexOptions.Compiled, TimeSpan.Zero);          // Noncompliant

            Regex.Match(s, "{foo}{bar}");                                                   // Noncompliant
            Regex.Match("", "{foo}{bar}", RegexOptions.Compiled);                           // Noncompliant
            Regex.Match("", "{foo}{bar}", RegexOptions.Compiled, TimeSpan.Zero);            // Noncompliant

            Regex.Matches(s, "{foo}{bar}");                                                 // Noncompliant
            Regex.Matches("", "{foo}{bar}", RegexOptions.Compiled);                         // Noncompliant
            Regex.Matches("", "{foo}{bar}", RegexOptions.Compiled, TimeSpan.Zero);          // Noncompliant

            Regex.Replace(s, "ab*cd*", match => "");                                        // Noncompliant
            Regex.Replace("", "ab*cd*", "");                                                // Noncompliant
            Regex.Replace("", "ab*cd*", match => "", RegexOptions.Compiled);                // Noncompliant
            Regex.Replace("", "ab*cd*", s, RegexOptions.Compiled);                          // Noncompliant
            Regex.Replace("", "ab*cd*", match => "", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant
            Regex.Replace("", "ab*cd*", "", RegexOptions.Compiled, TimeSpan.Zero);          // Noncompliant
            Regex.Replace("", "ab\\*cd\\*", "", RegexOptions.Compiled, TimeSpan.Zero);      // Noncompliant FP (escaped special characters)

            Regex.Split("", "a+a+");                                                        // Noncompliant
            Regex.Split("", "a+a+", RegexOptions.Compiled);                                 // Noncompliant
            Regex.Split("", "a+a+", RegexOptions.Compiled, TimeSpan.Zero);                  // Noncompliant

            new System.Text.RegularExpressions.Regex("a+a+");                               // Noncompliant
            new RE("a+b+");                                                                 // Noncompliant
            System.Text.RegularExpressions.Regex.IsMatch("", "{}{}");                       // Noncompliant
            RE.IsMatch("", "a**");                                                          // Noncompliant
            IsMatch("", "b**");                                                             // Noncompliant

            // Non-static methods are compliant
            r.IsMatch("a+a+");
            r.IsMatch("{ab}*{ab}+{cd}+foo*", 0);

            r.Match("{ab}*{ab}+{cd}+foo*");
            r.Match("{ab}*{ab}+{cd}+foo*", 0);
            r.Match("{ab}*{ab}+{cd}+foo*", 0, 1);

            r.Matches("{ab}*{ab}+{cd}+foo*");
            r.Matches("{ab}*{ab}+{cd}+foo*", 0);

            r.Replace("{ab}*{ab}+{cd}+foo*", match => "{ab}*{ab}+{cd}+foo*");
            r.Replace("{ab}*{ab}+{cd}+foo*", "{ab}*{ab}+{cd}+foo*");
            r.Replace("{ab}*{ab}+{cd}+foo*", match => "{ab}*{ab}+{cd}+foo*", 0);
            r.Replace("{ab}*{ab}+{cd}+foo*", "{ab}*{ab}+{cd}+foo*", 0);
            r.Replace("{ab}*{ab}+{cd}+foo*", match => "{ab}*{ab}+{cd}+foo*", 0, 0);
            r.Replace("{ab}*{ab}+{cd}+foo*", "{ab}*{ab}+{cd}+foo*", 0, 0);

            r.Split("{ab}*{ab}+{cd}+foo*");
            r.Split("{ab}*{ab}+{cd}+foo*", 0);
            r.Split("{ab}*{ab}+{cd}+foo*", 0, 0);

            // not hardcoded strings are compliant
            r = new Regex(s);
            r = new Regex(s, RegexOptions.Compiled, TimeSpan.Zero);
            Regex.Replace("{ab}*{ab}+{cd}+foo*", s, "{ab}*{ab}+{cd}+foo*", RegexOptions.Compiled, TimeSpan.Zero);
            Regex.Split("{ab}*{ab}+{cd}+foo*", s, RegexOptions.Compiled, TimeSpan.Zero);
        }
Beispiel #58
0
        public static bool IsTextNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9.]");
            return reg.IsMatch(str);

        }
Beispiel #59
0
 /// <summary>
 /// 验证输入的数据是不是正整数
 /// </summary>
 /// <param name="str">输入字符串</param>
 /// <returns>返回true或者false</returns>
 public static bool IsNumeric(string str)
 {
     System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
     return(reg1.IsMatch(str));
 }
Beispiel #60
0
 /// <summary>
 /// Checks if a string is in a valid time format.
 /// Can be used for DateTime objects for example.
 /// </summary>
 /// <param name="time">The string with a time format.</param>
 /// <returns>Returns true if the string contains a valid time format.</returns>
 public static bool IsValidTime(string time)
 {
     System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
     return(r.IsMatch(time));
 }