Split() public method

public Split ( string input ) : string[]
input string
return string[]
        /// <summary>
        /// Browse button even handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "VCG files|*.vcg|All Files|*.*";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                textBoxInputFilePath.Text = fd.FileName;
                selectedFilePath = fd.FileName;

                if (selectedFilePath != "")
                {
                    myLogicLayer.identifyLoops(selectedFilePath);
                    richTextBoxBasicBlock.Text = "";
                    richTextBoxBackEdgesInCfg.Text = "";
                    richTextBoxLoopInformation.Text = myLogicLayer.getLoops();

                    Regex r = new Regex("\\n");
                    String[] lines = r.Split(myLogicLayer.getIntermidiateCodeAsBasicBlocks());
                    //Next, I take each line and process its contents like so.
                    foreach (string l in lines)
                    {
                        ParseLine(l);
                    }

                    lines = r.Split(myLogicLayer.getBackEdges());
                    //Next, I take each line and process its contents like so.
                    foreach (string l in lines)
                    {
                        parseBackEdges(l);
                    }
                }

            }
        }
Beispiel #2
0
        public Collection<MultiLineDiff> Diff(string originalStr, string newStr)
        {
            Regex reg = new Regex(@"\r\n");
            string[] originalLines = reg.Split(originalStr);
            string[] newLines = reg.Split(newStr);

            Collection<MultiLineDiff> trances = new Collection<MultiLineDiff>();

            int[][] tracesMatrix = new int[originalLines.Length + 1][];
            //Init matrix
            for (int i = 0; i < originalLines.Length + 1; i++)
            {
                tracesMatrix[i] = new int[newLines.Length + 1];
                for (int j = 0; j < newLines.Length + 1; j++)
                {
                    tracesMatrix[i][j] = -1;
                }
            }

            int minEditLength = MinEditLength(originalLines, newLines, 0, 0, tracesMatrix);
            trances = GetTraces(originalLines, newLines, tracesMatrix);

            string html = GenerateDiffHTML(trances, originalLines, newLines);

            return trances;
        }
        static void Main()
        {
            long currentIIndex = 0;
            const string SplitPattern = @"\s+";
            Regex splitter = new Regex(SplitPattern);

            string[] inputStringNumbers = splitter.Split(Console.ReadLine()).Where(s => s != string.Empty).ToArray();
            BigInteger[] numberArray = inputStringNumbers.Select(BigInteger.Parse).ToArray();
            long arrayLength = numberArray.Length;

            while (true)
            {
                string command = Console.ReadLine();

                if (command == "stop")
                {
                    break;
                }

                string[] commandArgs = splitter.Split(command).Where(s => s != string.Empty).ToArray();

                long operationIndex = CalculateOperationIndex(commandArgs, currentIIndex, arrayLength);

                ExecuteCommand(commandArgs, numberArray, operationIndex);

                currentIIndex = operationIndex;

            }

            string output = string.Format("[{0}]", string.Join(", ", numberArray));
            Console.WriteLine(output);
        }
        public TwoSPInstance(string file)
        {
            Regex regex = new Regex(@"\s+");

            using (StreamReader reader = File.OpenText(file)) {
                string line = "";

                // Getting the dimension.
                line = reader.ReadLine();
                while (line.Trim() == "") {
                    line = reader.ReadLine();
                }
                NumberItems = int.Parse(regex.Split(line.Trim())[0]);

                // Getting the width of the strip.
                line = reader.ReadLine();
                while (line.Trim() == "") {
                    line = reader.ReadLine();
                }
                StripWidth = int.Parse(regex.Split(line.Trim())[0]);

                // Getting height and width of each item.
                ItemsHeight = new int[NumberItems];
                ItemsWidth = new int[NumberItems];
                for (int i = 0; i < NumberItems; i++) {
                    line = reader.ReadLine();
                    while (line.Trim() == "") {
                        line = reader.ReadLine();
                    }
                    string[] parts = regex.Split(line.Trim());
                    ItemsHeight[i] = int.Parse(parts[0]);
                    ItemsWidth[i] = int.Parse(parts[1]);
                }
            }
        }
        public Logradouro GerarLogradouro(string cepDesejado, string tipoCEP = "ALL", string semelhante = "N")
        {
            var postData = string.Format("relaxation={0}&tipoCEP={1}&semelhante={2}", cepDesejado, tipoCEP, semelhante);
            
            var responseString = GetHtml(postData, _buscarLogradouroPeloCepLink);

            var pattern = @"<table class=""tmptabela"">(.*?)</table>";
            var regex = new Regex(pattern);
            var match = regex.Match(responseString);

            var rua = new Regex("<td width=\"150\">(.*?)&nbsp;</td>").Match(match.Groups[0].Value).Groups[0].Value;
            string stripTagsPattern = @"<(.|\n)*?>";
            rua = Regex.Replace(rua, stripTagsPattern, string.Empty).Replace("&nbsp;","");

            var bairro = new Regex("<td width=\"90\">(.*?)&nbsp;</td>").Match(match.Groups[0].Value).Groups[0].Value;
            bairro = Regex.Replace(bairro, stripTagsPattern, string.Empty).Replace("&nbsp;", "");

            var cidade = new Regex("<td width=\"80\">(.*?)</td>").Match(match.Groups[0].Value).Groups[0].Value;
            cidade = Regex.Replace(cidade, stripTagsPattern, string.Empty).Replace("&nbsp;", "");

            var logradouro = new Logradouro();
            logradouro.CEP = cepDesejado;
            logradouro.Endereco = rua.HtmlDecode();
            logradouro.BairroOuDistrito = bairro.HtmlDecode();
            logradouro.Localidade = cidade.Split('/')[0].HtmlDecode();
            logradouro.UF = cidade.Split('/')[1].HtmlDecode();
            return logradouro;
        }
Beispiel #6
0
        public string CreateDiffHtml(string originalStr, string newStr)
        {
            Regex reg = new Regex(@"\r\n");
            string[] originalLines = reg.Split(originalStr);
            string[] newLines = reg.Split(newStr);

            Collection<MultiLineDiff> trances = Diff(originalStr, newStr);

            string html = GenerateDiffHTML(trances, originalLines, newLines);

            return html;
        }
 public IGRequestChangeProperty(string sUser, string sFrameId, string sPropIds, string sPropVals)
     : base(sUser, IGREQUESTFRAMECHANGEPROPERTY_STRING, IGREQUEST_FRAME_CHANGEPROPERTY, sFrameId)
 {
     SetParameter(IGREQUEST_ISFRAME, sFrameId == "0" ? "0" : "1");
     SetParameter(IGREQUEST_PROPIDS, sPropIds);
     Regex RE = new Regex(@"[,]+");
     string[] tPropIds = RE.Split(sPropIds);
     string[] tPropVals = RE.Split(sPropVals);
     if (tPropIds.Count() == tPropVals.Count())
     {
         for (int idxPropId = 0; idxPropId < tPropIds.Count(); idxPropId++)
             SetParameter(tPropIds[idxPropId], tPropVals[idxPropId]);
     }
 }
		private string GetLiquidCodeOfParameter(string name)
		{
			var retVal = string.Empty;

			Regex regex = new Regex(
				@"(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])"
			);

			if(regex.Split(name).Length > 0)
			{
				retVal = "{{ context." + string.Join("_", regex.Split(name)).ToLower() + " }}";
			}

			return retVal;
		}
    private void FillSelectedLists(UserControl_SystemCodeWUCtrl listOrigin, HtmlSelect listSelected, String strListValue)
    {
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(";");
        String[] strItemCollection = regex.Split(strListValue);
        System.Collections.Generic.List <String[, ]> strOptionCollection = new System.Collections.Generic.List <string[, ]>();
        String strScript = String.Empty;

        listSelected.Items.Clear();
        listOrigin.FetchSystemCodeListData();
        foreach (String strItem in strItemCollection)
        {
            foreach (ListItem item in listOrigin.Items)
            {
                if ((strItem.Length > 0) && item.Value.Equals(strItem))
                {
                    strOptionCollection.Add(new String[, ] {
                        { item.Value, item.Text }
                    });
                }
            }
        }

        strScript  = "var objList = document.forms[0]." + listSelected.ClientID + ", option;";
        strScript += "objList.length = 0;";
        foreach (String[,] tempString in strOptionCollection)
        {
            strScript += "option = document.createElement('OPTION');";
            strScript += "option.value = '" + tempString[0, 0] + "';";
            strScript += "option.text = '" + tempString[0, 1] + "';";
            strScript += "objList.options.add(option);";
        }

        ScriptManager.RegisterStartupScript(linkBtnLoad, linkBtnLoad.GetType(), Guid.NewGuid().ToString(), strScript, true);
    }
        static string FromPascalCase(string input)
        {
            var pascalCaseWordBoundaryRegex = new Regex(@"
            (?# word to word, number or acronym)
            (?<=[a-z])(?=[A-Z0-9])|
            (?# number to word or acronym)
            (?<=[0-9])(?=[A-Za-z])|
            (?# acronym to number)
            (?<=[A-Z])(?=[0-9])|
            (?# acronym to word)
            (?<=[A-Z])(?=[A-Z][a-z])
            ", RegexOptions.IgnorePatternWhitespace);

            var result = pascalCaseWordBoundaryRegex
                .Split(input)
                .Select(word =>
                    word.ToCharArray().All(Char.IsUpper) && word.Length > 1
                        ? word
                        : word.ToLower())
                .Aggregate((res, word) => res + " " + word);

            result = Char.ToUpper(result[0]) +
                result.Substring(1, result.Length - 1);
            return result.Replace(" i ", " I "); // I is an exception
        }
Beispiel #11
0
        ///<summary>
        ///分析文件域,添加到请求流
        ///</summary>
        ///<param name="fileField">文件域</param>
        private void WriteFileField(string fileField)
        {
            string filePath = "";
            int    count    = 0;

            string[] strArr = RE.Split(fileField, "&");
            foreach (string var in strArr)
            {
                Match M = RE.Match(var, "([^=]+)=(.+)");
                filePath   = M.Groups[2].Value;
                fileField  = "--" + BOUNDARY + "\r\n";
                fileField += "Content-Disposition: form-data; name=\"" + M.Groups[1].Value + "\"; filename=\"" + Path.GetFileName(filePath) + "\"\r\n";
                fileField += "Content-Type: image/jpeg\r\n\r\n";

                byte[] buffer = encoding.GetBytes(fileField);
                postStream.Write(buffer, 0, buffer.Length);

                //添加文件数据
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                buffer = new byte[50000];

                do
                {
                    count = fs.Read(buffer, 0, buffer.Length);
                    postStream.Write(buffer, 0, count);
                } while (count > 0);

                fs.Close();
                fs.Dispose();
                fs = null;

                buffer = encoding.GetBytes("\r\n");
                postStream.Write(buffer, 0, buffer.Length);
            }
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            const string SplitPattern = @"\s*\|\s*";
            Regex regex = new Regex(SplitPattern);

            var countryData = new Dictionary<string, List<string>>();

            string input = Console.ReadLine();

            while (input != "report")
            {
                string[] tokens = regex.Split(input.Trim());
                string athlete = Regex.Replace(tokens[0].Trim(), @"\s+", " ");
                string country = Regex.Replace(tokens[1].Trim(), @"\s+", " ");

                if (!countryData.ContainsKey(country))
                {
                    countryData.Add(country, new List<string>());
                }
                countryData[country].Add(athlete);
                input = Console.ReadLine();
            }
            var orderedCountryData = countryData
                .OrderByDescending(x => x.Value.Count);

            foreach (var country in orderedCountryData)
            {
                Console.WriteLine(
                    "{0} ({1} participants): {2} wins",
                    country.Key,
                    country.Value.Distinct().Count(),
                    country.Value.Count);
            }
        }
Beispiel #13
0
		public string [] SplitHelper( string macroName, string splitOrRegex, bool usingRegex )
		{
			// ******
			//NmpStringList list = null;
			string [] list = null;

			if( usingRegex ) {
				try {
					Regex rx = new Regex( splitOrRegex );
					//list = new NmpStringList( rx.Split(theString, MaxParseItems) );
					list = rx.Split(theString, MaxParseItems );
				}
				catch ( ArgumentException e ) {
					ThreadContext.MacroError( "{0}: {1}", macroName, e.Message );
				}
			}
			else {
				try {
					//list = new NmpStringList( rx.Split(theString, MaxParseItems) );
					list = theString.Split(new string [] { splitOrRegex }, MaxParseItems, StringSplitOptions.None );
				}
				catch ( ArgumentException e ) {
					ThreadContext.MacroError( "{0}: {1}", macroName, e.Message );
				}
			}

			// ******
			return list;
		}
Beispiel #14
0
        public Args(string[] args)
        {
            argDict = new StringDictionary();
            Regex regEx = new Regex(@"^-", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regTrim = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            string arg = "";
            string[] chunks;

            foreach (string s in args)
            {
                chunks = regEx.Split(s, 3);

                if (regEx.IsMatch(s))
                {
                    arg = chunks[1];
                    argDict.Add(arg, "true");
                }
                else
                {
                if (argDict.ContainsKey(arg))
                {
                    chunks[0] = regTrim.Replace(chunks[0], "$1");
                    argDict.Remove(arg);
                    argDict.Add(arg, chunks[0]);
                    arg = "";
                }
                }
              }
        }
        public static List<object> TokenizeMessage(string message)
        {
            var tokens = new List<object>();

            try
            {
                //TODO - better Regex
                var r = new Regex("<(.|\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture);
                var split = r.Split(message);

                foreach (var t in split)
                {
                    if (!string.IsNullOrWhiteSpace(t))
                    {
                        Uri uri = null;
                        if (Uri.TryCreate(t, UriKind.Absolute, out uri))
                        {
                            tokens.Add(uri);
                        }
                        else
                        {
                            tokens.Add(t);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                tokens.Clear();
                tokens.Add(message);
            }

            return tokens;
        }
        public MFTestResults RegExpTest_1_Split_Test_0()
        {
            bool testResult = false;

            string[] expectedResults;

            string[] acutalResults;

            Regex regex;

            try
            {
                expectedResults = new string[]{ "xyzzy", "yyz", "123" };
                regex = new Regex("[ab]+");
                acutalResults = regex.Split("xyzzyababbayyzabbbab123");
                TestTestsHelper.AssertEquals(ref expectedResults, ref acutalResults, out testResult);

                expectedResults = new string[] { "xxxx", "xxxx", "yyyy", "zzz" };
                regex = new Regex("a*b");//match any amount of 'a' and 1 'b'
                acutalResults = regex.Split("xxxxaabxxxxbyyyyaaabzzz");
                TestTestsHelper.AssertEquals(ref expectedResults, ref acutalResults, out testResult);                

                // Grep Tests

                return RegExpTest_2_Grep_Test_0(ref acutalResults);

            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected Exception", ex);
                testResult = false;
            }

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
Beispiel #17
0
        public static void ReadCsvValues(String sourcePath)
        {
            var tempPath = Path.GetTempFileName();
            const string delimiter = ",";
            var splitExpression = new Regex(@"(" + delimiter + @")(?=(?:[^""]|""[^""]*"")*$)");

            using (var writer = new StreamWriter(tempPath, false, Encoding.Default))
            using (var reader = new StreamReader(sourcePath, Encoding.Default))
            {
                var lineNumber = 0;
                var lineContent = reader.ReadLine();

                if (lineContent != null)
                {
                    var csvHeader = splitExpression.Split(lineContent).Where(s => s != delimiter);

                    foreach (var header in csvHeader)
                    {
                        WriteValue(lineNumber, writer,
                            CsvPairs.Fields.ContainsKey(header) ? CsvPairs.Fields[header] : header);
                        lineNumber++;
                    }

                    writer.WriteLine();

                    while ((lineContent = reader.ReadLine()) != null)
                    {
                        writer.WriteLine(lineContent);
                    }
                }
            }
            File.Delete(sourcePath);
            File.Move(tempPath, sourcePath);
        }
        public IList<string> Core(string sentence)
        {
            var regex1 = new Regex(@"([\u4E00-\u9FA5]+)", RegexOptions.None);
            var regex2 = new Regex(@"(\d+\.\d+|[a-zA-Z0-9]+)", RegexOptions.None);

            var blocks = regex1.Split(sentence);
            var finalResult = new List<string>();

            foreach (var block in blocks)
            {
                if (string.IsNullOrEmpty(block)) continue;
                if (regex1.IsMatch(block))
                {
                    var path = ViterbiCore(block);
                    var result = new List<string>();
                    GetResult(block, path.Item1, path.Item2, block.Length - 1, result, string.Empty);
                    result.Reverse();
                    finalResult.AddRange(result);
                }
                else
                {
                    finalResult.AddRange(regex2.Split(block).Where(split => !string.IsNullOrEmpty(split)));
                }
            }
            return finalResult;
        }
        public PhotoUploadedInfo(string jsonstr)
        {
            // отрезаем скобки, убираем кавычки
            System.Windows.Forms.MessageBox.Show(jsonstr);
            jsonstr = jsonstr.Replace("{", "").Replace("}", "").Replace("\"", "");

            // разделяем строку на кусочки по  запятой с пробелами
            Regex r = new Regex(@"\,[\s]*");
            string[] json = r.Split(jsonstr);

            // далее каждый кусок обрабатываем как ключ: значение
            // и складываем их в таблицу
            Hashtable h = new Hashtable();
            r = new Regex(@"(\:[\s]+)");
            foreach (string str in json)
            {
                string[] kv = r.Split(str);
                h[kv[0]] = kv[2];
            }

            // присваиваем значения
            this.Server = (string)h["server"];
            this.Photo = (string)h["photo"];
            this.Hash = (string)h["hash"];
        }
Beispiel #20
0
        public static void bacafile(string file, string filecp,string hit)
        {
            string line;
            string pattern = @"\t+";
            Regex rgx = new Regex(pattern);
            //ini pake try catch
            StreamReader sr = new StreamReader(file);
            while ((line = sr.ReadLine()) != null)
            {

                string[] result = rgx.Split(line);
                int hasil = rumus(Convert.ToInt16(result[0]), Convert.ToInt16(result[1]), hit);
                //untuk rect
                if (!File.Exists(filecp))
                {

                    // Create a file to write to. kalau belom ada filenya
                    using (StreamWriter swnew = File.CreateText(filecp))
                    {
                        swnew.WriteLine(hasil + "\t\t" + result[0] + "\t\t\t\t" + result[1] + "\t" + "Rectangle");
                    }
                }
                //kalau ud ada file yang mau ditulis
                else
                {
                    using (FileStream fs = new FileStream(filecp, FileMode.Append, FileAccess.Write))
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine(hasil + "\t\t" + result[0] + "\t\t\t\t" + result[1] + "\t" + "Rectangle");
                    }
                }
            }
            sr.Close();
        }
Beispiel #21
0
		public IEnumerable<Morpheme> Parse(string input)
		{
			List<Morpheme> morphemes = new List<Morpheme>(128);
			Regex regex = new Regex(@".* rg");
			Regex ReplaceRegex = new Regex(@"\r\n");

			string lastItem = default(string);

			foreach (var item in regex.Split(input))
			{
				if ((item == String.Empty) ||
					(item == "\r\n"))
				{
					continue;
				}

				string str = ReplaceRegex.Replace(item, String.Empty);

				// Размер пишется двумя морфемами. Я считываю одну и вторую и для удобства записываю их в одну общую.
				if (Common.singatureRegex.Match(str).Success)
				{
					if (Common.singatureRegex.Match(lastItem).Success)
					{
						morphemes.Add(new Morpheme(lastItem + str));
					}
					lastItem = str;
					continue;
				}

				morphemes.Add(new Morpheme(str));
				lastItem = str;
			}

			return morphemes.AsReadOnly();
		}
        public Uri(string absoluteUri)
        {
            var regex = new Regex(@"(://)");
            var schemePartAndRest = regex.Split(absoluteUri);

            UriScheme = schemePartAndRest[0];

            var uriAndQueryString = schemePartAndRest[1].Split('?');

            if (uriAndQueryString.Length > 1)
            {
                QueryString = uriAndQueryString[1];
            }

            var hostPartLength = uriAndQueryString[0].IndexOf('/');
            if (hostPartLength != -1)
            {
                SetHostAndPort(uriAndQueryString[0].Substring(0, hostPartLength));
                AbsolutePath = uriAndQueryString[0].Substring(hostPartLength);
            }
            else
            {
                SetHostAndPort(uriAndQueryString[0]);
                AbsolutePath = "/";
            }
        }
		private static Dictionary<string, double> ParseFormula(string formula)
		{
			var parsedFormula = new Dictionary<string, double>();
			var regexSymbols = @"\d+"; //digit at least once
			var regexNumbers = @"[A-Z]{1}"; //not a digit

			var pSymbols = new Regex(regexSymbols);
			var pNumbers = new Regex(regexNumbers);

			var symbols = pSymbols.Split(formula).Where(s => !string.IsNullOrEmpty(s)).ToArray();
			var numbers = pNumbers.Split(formula);

			var numberCount = 1;
			for (var i = 0; i < symbols.Length; i++)
			{
				//create temporary atom with symbol and "configure" it
				IAtom a = new Atom(symbols[i]);

				var isofac = IsotopeFactory.getInstance(new ChemObject().getBuilder());
				isofac.configure(a);

				//fix if the digit is not written
				if (string.IsNullOrEmpty(numbers[numberCount]) && numberCount > 0)
				{
					numbers[numberCount] = "1";
				}

				var mass = a.getExactMass().doubleValue();
                mass = mass * double.Parse(numbers[numberCount], CultureInfo.InvariantCulture);
				numberCount++;
				parsedFormula[symbols[i]] = mass;
			}

			return parsedFormula;
		}
        private void RunScript(SqlConnection connection, string sql)
        {
            Regex regex = new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            string[] lines = regex.Split(sql);

            SqlTransaction transaction = connection.BeginTransaction();
            using (SqlCommand cmd = connection.CreateCommand())
            {
                cmd.Connection = connection;
                cmd.Transaction = transaction;

                foreach (string line in lines)
                {
                    if (line.Length > 0)
                    {
                        cmd.CommandText = line;
                        cmd.CommandType = CommandType.Text;

                        try
                        {
                            cmd.ExecuteNonQuery();
                        } // End Try
                        catch (SqlException)
                        {
                            transaction.Rollback();
                            throw;
                        } // End Catch
                    } // End If
                } // End Foreach
            } // End Using

            transaction.Commit();
        }
Beispiel #25
0
        public static string TransformLinkToken(string linkType, string identifier)
        {
            var link = string.Empty;
            if (linkType == "image")
            {
                link = $"./data/{linkType}s/{identifier}";
            }
            else if(linkType == "namespace")
            {
                link = $"#/{linkType}/{identifier}";
            }
            else if(linkType == "type")
            {
                link = $"#/{linkType}/{identifier.RemoveIllegalPathChars()}/index";
            }
            else if(linkType == "article")
            {
                link = $"#/{linkType}/{identifier}";
            }
            else // Member
            {
                var identifierWithoutPrefix = identifier
                    .Replace("field.", "")
                    .Replace("event.", "")
                    .Replace("property.", "");

                var regEx = new Regex(@"\.(?![^\(]*\))");
                var splittedId = regEx.Split(identifierWithoutPrefix);
                link = $"#/type/{string.Join(".", splittedId.Take(splittedId.Length - 1)).Trim('.').RemoveIllegalPathChars()}/{identifier.RemoveIllegalHtmlIdChars()}";
            }
            return link;
        }
Beispiel #26
0
        /// <summary>
        /// Gets data path so tests look for data files in correct place
        /// </summary>
        /// <returns>string including post pend slash</returns>
        public static string GetDataPath()
        {
            string finalPath = string.Empty;

            RssFeeds feeds = new RssFeeds();

            string binPath = AppDomain.CurrentDomain.BaseDirectory;
            string[] splitString = null;
            string basePath = string.Empty;

            // everything before the bin directory
            if (binPath.Contains("bin"))
            {
                Regex matchPattern = new Regex("bin");
                splitString = matchPattern.Split(binPath);
                basePath = splitString[0];
                finalPath = Path.Combine(basePath, @"App_Data\");
            }
            else if (binPath.Contains("TestResults"))
            {
                Regex matchPattern = new Regex("TestResults");
                splitString = matchPattern.Split(binPath);
                basePath = splitString[0];
                finalPath = Path.Combine(basePath, "XmlTestProject", @"App_Data\");
            }
            else
            {
                // don't know where the path is at this point
            }

            return finalPath;
        }
Beispiel #27
0
        public void FromString(string listString)
        {
            // remove existing list items
            Clear();

            if ( listString != null )
            {
                // remove leading and trailing whitespace
                // NOTE: Need to check if .NET whitespace = SVG (XML) whitespace
                listString = listString.Trim();

                if ( listString.Length > 0 )
                {
                    Regex delim = new Regex(@"\s+,?\s*|,\s*");
                    foreach ( string item in delim.Split(listString) )
                    {
                        // the following test is needed to catch consecutive commas
                        // for example, "one,two,,three"
                        if ( item.Length == 0 )
                            throw new DomException(DomExceptionType.SyntaxErr);

                        AppendItem(new SvgNumber(item));
                    }
                }
            }
        }
Beispiel #28
0
		/// <summary>
		/// Implements the following function 
		///		node-set tokenize(string, string, string)
		/// </summary>
		/// <param name="str"></param>
		/// <param name="regexp"></param>		
		/// <param name="flags"></param>
		/// <returns>This function breaks the input string into a sequence of strings, 
		/// treating any substring that matches the regexp as a separator. 
		/// The separators themselves are not returned. 
		/// The matching strings are returned as a set of 'match' elements.</returns>
		/// <remarks>THIS FUNCTION IS NOT PART OF EXSLT!!!</remarks>
		public XPathNodeIterator tokenize(string str, string regexp, string flags)
		{

			RegexOptions options = RegexOptions.ECMAScript;

			if (flags.IndexOf("m") != -1)
			{
				options |= RegexOptions.Multiline;
			}

			if (flags.IndexOf("i") != -1)
			{
				options |= RegexOptions.IgnoreCase;
			}

			XmlDocument doc = new XmlDocument();
			doc.LoadXml("<matches/>");

			Regex regex = new Regex(regexp, options);

			foreach (string match in regex.Split(str))
			{

				XmlElement elem = doc.CreateElement("match");
				elem.InnerText = match;
				doc.DocumentElement.AppendChild(elem);
			}

			return doc.CreateNavigator().Select("//match");
		}
        public string[] Partition(string input)
        {
            Regex r=new Regex("([ \\t{}():;])");

            Normalize_Casing(ref input);
            //normalization to the lower case
            input=input.ToLower() ;

            String [] tokens=r.Split(input);

            ArrayList filter=new ArrayList() ;

            for (int i=0; i < tokens.Length ; i++)
            {
                MatchCollection mc=r.Matches(tokens[i]);
                if (mc.Count <= 0 && tokens[i].Trim().Length > 0 )
                    filter.Add(tokens[i]) ;

            }

            tokens=new string[filter.Count] ;
            for(int i=0; i < filter.Count ; i++) tokens[i]=(string) filter[i];

            return tokens;
        }
Beispiel #30
0
 public static string[][] GetTorrents(string address, string username, string password)
 {
     WebClient wc = new WebClient();
     wc.Credentials = new NetworkCredential(username, password);
     string fullAddress = "http://" + address + "/gui/?list=1";
     //Fetch a raw listing of the current stuff from uTorrent==============================================
     byte[] rawResponse = wc.DownloadData(fullAddress);
     string response = Encoding.ASCII.GetString(rawResponse);
     Regex arrayBuilder = new Regex("\n");
     char[] delimiters = new char[] { '"', '[', ']' };
     int start = response.IndexOf('"' + "torrents" + '"' + ": [") + 16;
     int end = response.Length - (start + 29);
     response = response.Substring(start, end);
     //Clean the list text so its just the torrents=======================================================
     string[] rawTorrents = arrayBuilder.Split(response);
     string[][] torrents = new string[rawTorrents.Count()][];
     if (rawTorrents.Count() > 0)                //check for active torrents
     {
         for (int i = 0; i < rawTorrents.Count(); ++i)
         {
             string rawTorrent = rawTorrents[i];
             string[] tempTorrent = rawTorrent.Split(new Char[] { ',' });
             //now we fill the array torrents with: 0 = Hash, 1 = Status, 2 = Label, and 3 = Queue
             torrents[i] = new string[] { tempTorrent[0].ToString().Trim(delimiters), tempTorrent[1].ToString().Trim(delimiters), tempTorrent[11].ToString().Trim(delimiters), tempTorrent[17].ToString().Trim(delimiters), tempTorrent[2].ToString().Trim(delimiters) };
         }
     }
     return torrents;
 }
        private static void decodeLevel(ref int i, List<PlayingFieldInfo> playingFields, string[] description)
        {
            var rex = new Regex(@"^\*SCENE(\d+),(\d+)x(\d+)x(\d+)\*$");
            var split = rex.Split(description[i]);
            if (split.Length != 6)
                throw new Exception();

            var scene = int.Parse(split[1]);
            var height = int.Parse(split[2]);
            var width = int.Parse(split[3]);
            var floors = int.Parse(split[4]);

            if (scene - 1 != playingFields.Count)
                throw new Exception();

            var fields = new List<string[]>();
            for (var f = 0; f < floors; f++)
            {
                if (f != 0)
                {
                    var expected = "*Floor{0}*".Fmt(f + 1);
                    if (string.Compare(description[i], expected, StringComparison.OrdinalIgnoreCase) != 0)
                        throw new Exception("Expected \"{0}\" but was \"{1}\"".Fmt(expected, description[i]));
                }
                i++;
                fields.Add(getFloor(i, description, width, height));
                i += height;
            }

            var pfi = new PlayingFieldInfo();
            pfi.PlayingField = PlayingFieldBuilder.Create(fields, width, height, ref pfi.PlayerSerpentStart, ref pfi.EnemySerpentStart);
            playingFields.Add(pfi);
        }
 public static string[] DivideStringOnParagraph(string str)
 {
     var str1 = @"\s*" + Environment.NewLine + @"\s*" + Environment.NewLine + @"\s*";
     var regex = new Regex(str1);
     var result = regex.Split(str);
     return result;
 }
Beispiel #33
0
        static void Main(string[] args)
        {
            string fileToProcess = Console.ReadLine();


            var reg         = new System.Text.RegularExpressions.Regex(@"\s+");
            var hostEntries = new List <HostEntry>();

            using (var reader = new HostFileReader(fileToProcess))
            {
                for (string line = reader.ReadLine(); !reader.EndOfStream; line = reader.ReadLine())
                {
                    if (reader.IgnoreLine)
                    {
                        continue;
                    }

                    var parts = reg.Split(line.Trim());

                    var ip = parts[0].Trim();

                    //walk through each one
                    foreach (var d in parts.Skip(1).Where(x => !x.StartsWith("#") && x.Trim().Length > 0).Select(x => x.Trim()))
                    {
                        var entry = new HostEntry()
                        {
                            IP     = ip,
                            Domain = d
                        };

                        //if (string.IsNullOrWhiteSpace(entry.Domain))
                        //{
                        //    Console.WriteLine("^%^ " + line);
                        //}

                        hostEntries.Add(entry);
                    }
                }
            }

            string directory = Path.GetDirectoryName(fileToProcess);
            string filePath  = Path.Combine(directory, Path.GetRandomFileName());

            var stringBuilder = new StringBuilder();

            foreach (var hostEntry in hostEntries.OrderBy(x => x.IP).ThenBy(x => x.Domain))
            {
                stringBuilder.AppendFormat("{0}\t{1}", hostEntry.IP, hostEntry.Domain);
                stringBuilder.AppendLine();
            }

            File.WriteAllText(filePath, stringBuilder.ToString());

            //string directory2 = string.Concat(Path.GetDirectoryName(workbook.FullName), "\\", workbookName);
            System.Diagnostics.Process.Start("explorer.exe", directory);

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Beispiel #34
0
            public static string[] CSVLineToArray(string text)
            {
                string pattern = ",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))";

                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(pattern);
                string[] result = r.Split(text);
                result = TrimQuotes(result);
                result = TrimSpace(result);
                return(result);
            }
Beispiel #35
0
    static int Split(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 2 && LuaScriptMgr.CheckTypes(L, 1, typeof(System.Text.RegularExpressions.Regex), typeof(string)))
        {
            System.Text.RegularExpressions.Regex obj = (System.Text.RegularExpressions.Regex)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.Text.RegularExpressions.Regex");
            string   arg0 = LuaScriptMgr.GetString(L, 2);
            string[] o    = obj.Split(arg0);
            LuaScriptMgr.PushArray(L, o);
            return(1);
        }
        else if (count == 2 && LuaScriptMgr.CheckTypes(L, 1, typeof(string), typeof(string)))
        {
            string   arg0 = LuaScriptMgr.GetString(L, 1);
            string   arg1 = LuaScriptMgr.GetString(L, 2);
            string[] o    = System.Text.RegularExpressions.Regex.Split(arg0, arg1);
            LuaScriptMgr.PushArray(L, o);
            return(1);
        }
        else if (count == 3 && LuaScriptMgr.CheckTypes(L, 1, typeof(System.Text.RegularExpressions.Regex), typeof(string), typeof(int)))
        {
            System.Text.RegularExpressions.Regex obj = (System.Text.RegularExpressions.Regex)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.Text.RegularExpressions.Regex");
            string   arg0 = LuaScriptMgr.GetString(L, 2);
            int      arg1 = (int)LuaDLL.lua_tonumber(L, 3);
            string[] o    = obj.Split(arg0, arg1);
            LuaScriptMgr.PushArray(L, o);
            return(1);
        }
        else if (count == 3 && LuaScriptMgr.CheckTypes(L, 1, typeof(string), typeof(string), typeof(System.Text.RegularExpressions.RegexOptions)))
        {
            string arg0 = LuaScriptMgr.GetString(L, 1);
            string arg1 = LuaScriptMgr.GetString(L, 2);
            System.Text.RegularExpressions.RegexOptions arg2 = (System.Text.RegularExpressions.RegexOptions)LuaScriptMgr.GetLuaObject(L, 3);
            string[] o = System.Text.RegularExpressions.Regex.Split(arg0, arg1, arg2);
            LuaScriptMgr.PushArray(L, o);
            return(1);
        }
        else if (count == 4)
        {
            System.Text.RegularExpressions.Regex obj = (System.Text.RegularExpressions.Regex)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.Text.RegularExpressions.Regex");
            string   arg0 = LuaScriptMgr.GetLuaString(L, 2);
            int      arg1 = (int)LuaScriptMgr.GetNumber(L, 3);
            int      arg2 = (int)LuaScriptMgr.GetNumber(L, 4);
            string[] o    = obj.Split(arg0, arg1, arg2);
            LuaScriptMgr.PushArray(L, o);
            return(1);
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: System.Text.RegularExpressions.Regex.Split");
        }

        return(0);
    }
Beispiel #36
0
 public IEnumerable <string> Split(string text)
 {
     string[] lines = rx_split.Split(text);
     foreach (string line in lines)
     {
         if (line.Length > 1 && !".?!".Contains(line[0]))
         {
             yield return(line);
         }
     }
 }
Beispiel #37
0
    public IEnumerable <string> Tokenize(string sent)
    {
        // string[] words = line.ToLower().Split(" ,.?!-:\t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        foreach (string token in rx_splitter.Split(sent))
        {
            if (token.Length > 0)
            {
                yield return(Normalize(token));
            }
        }
    }
Beispiel #38
0
        public static string TidyHtml(string html)
        {
            TidyNet.Tidy tidy = new TidyNet.Tidy();

            /* Set the options you want */
            tidy.Options.DocType         = TidyNet.DocType.Strict;
            tidy.Options.DropFontTags    = true;
            tidy.Options.LogicalEmphasis = true;
            if (GlobalSettings.EditXhtmlMode == "true")
            {
                tidy.Options.Xhtml  = true;
                tidy.Options.XmlOut = true;
            }
            else
            {
                tidy.Options.XmlOut = false;
                tidy.Options.Xhtml  = false;
            }
            tidy.Options.MakeClean = true;
            tidy.Options.TidyMark  = false;

            // To avoid entity encoding
            tidy.Options.CharEncoding = (TidyNet.CharEncoding)Enum.Parse(typeof(TidyNet.CharEncoding), UmbracoSettings.TidyCharEncoding);


            /* Declare the parameters that is needed */
            TidyNet.TidyMessageCollection tmc = new TidyNet.TidyMessageCollection();
            MemoryStream input  = new MemoryStream();
            MemoryStream output = new MemoryStream();

            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(html);
            input.Write(byteArray, 0, byteArray.Length);
            input.Position = 0;
            tidy.Parse(input, output, tmc);

            string tidyed = System.Text.Encoding.UTF8.GetString(output.ToArray());

            // only return body
            string regex = @"</{0,1}body[^>]*>";

            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                                                                   | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
            string[] s = reg.Split(tidyed);
            if (s.Length > 1)
            {
                return(s[1]);
            }
            else
            {
                return("[tidy error]");
            }
        }
Beispiel #39
0
 ///<summary>
 ///分析文本域,添加到请求流
 ///</summary>
 ///<param name="textField">文本域</param>
 private void WriteTextField(string textField)
 {
     string[] strArr = RE.Split(textField, "&");
     textField = "";
     foreach (string var in strArr)
     {
         Match M = RE.Match(var, "([^=]+)=(.+)");
         textField += "--" + BOUNDARY + "\r\n";
         textField += "Content-Disposition: form-data; name=\"" + M.Groups[1].Value + "\"\r\n\r\n" + M.Groups[2].Value + "\r\n";
     }
     byte[] buffer = encoding.GetBytes(textField);
     postStream.Write(buffer, 0, buffer.Length);
 }
Beispiel #40
0
    void ParseFile()
    {
        var rx = new System.Text.RegularExpressions.Regex(AnimationGenerator.FILE_LINE_SEPARATOR);

        String[] splitText = rx.Split(animationFile.text);
        animationGenerator.serializedAnimation = splitText[0];
        String[] planeVector1Text = splitText[1].Split(',');
        Vector3  planeVector1     = new Vector3(float.Parse(planeVector1Text[0]), float.Parse(planeVector1Text[1]), float.Parse(planeVector1Text[2]));

        animationGenerator.model        = transform;
        animationGenerator.planeVector1 = planeVector1;
        animationGenerator.forceRestore = true;
        animationGenerator.RestoreAnimation();
    }
Beispiel #41
0
        static public Variable Tokenize(string data, string sep, string option = "", int max = int.MaxValue - 1)
        {
            if (sep == "\\t")
            {
                sep = "\t";
            }
            if (sep == "\\n")
            {
                sep = "\n";
            }

            string[] tokens;
            var      sepArray = sep.ToCharArray();

            if (sepArray.Count() == 1)
            {
                tokens = data.Split(sepArray, max);
            }
            else
            {
                List <string> tokens_ = new List <string>();
                var           rx      = new System.Text.RegularExpressions.Regex(sep);
                tokens = rx.Split(data);
                for (int i = 0; i < tokens.Length; i++)
                {
                    if (string.IsNullOrWhiteSpace(tokens[i]) || sep.Contains(tokens[i]))
                    {
                        continue;
                    }
                    tokens_.Add(tokens[i]);
                }
                tokens = tokens_.ToArray();
            }

            List <Variable> results = new List <Variable>();

            for (int i = 0; i < tokens.Length; i++)
            {
                string token = tokens[i];
                if (i > 0 && string.IsNullOrWhiteSpace(token) &&
                    option.StartsWith("prev", StringComparison.OrdinalIgnoreCase))
                {
                    token = tokens[i - 1];
                }
                results.Add(new Variable(token));
            }

            return(new Variable(results));
        }
Beispiel #42
0
 static public int Split__String(IntPtr l)
 {
     try {
         System.Text.RegularExpressions.Regex self = (System.Text.RegularExpressions.Regex)checkSelf(l);
         System.String a1;
         checkType(l, 2, out a1);
         var ret = self.Split(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #43
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var result    = new StringBuilder();
                var sourceStr = this.txtSourceTxt.Text;


                #region 处理注释
                var ss       = "Add comments to the columns";
                var sqlField = Regex.Split(sourceStr, ss, RegexOptions.IgnoreCase);
                var tmpStrA  = Regex.Split(sqlField[0], "\n(\n", RegexOptions.IgnoreCase);
                #endregion



                var lstSourceField = sourceStr.Split('\n');
                var lstFieldEntity = new List <FieldEntity>();
                foreach (var item in lstSourceField)
                {
                    var entity = new FieldEntity();
                    var tmpStr = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(item, " ");
                    tmpStr = tmpStr.TrimStart(' ').TrimEnd(',');
                    var tmpArr = tmpStr.Split('(')[0].Split(' ');
                    if (isUpper)
                    {
                        entity.FieldName = tmpArr[0].ToUpper();
                    }
                    else
                    {
                        entity.FieldName = tmpArr[0];
                    }

                    entity.FieldType = tmpArr[1];
                    lstFieldEntity.Add(entity);
                }

                CalResult(result, lstFieldEntity);
                this.txtResultTxt.Text         = result.ToString();
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #44
0
 public ArrayImpl Split(string inputString, int count = 0, int startAt = 0)
 {
     string[] arrParsed = _regex.Split(inputString, count, startAt);
     return(new ArrayImpl(arrParsed.Select(x => ValueFactory.Create(x))));
 }
Beispiel #45
0
        static void InsertOneVariable(OD_1_1_1DataSet.VariablesDataTable tblVariables,
                                      VariableInfoType varInfo, SqlConnection sqlConn)
        {
            string cond;

            OD_1_1_1DataSet.VariablesRow row = tblVariables.NewVariablesRow();

            string[] vars = Regex.Split(varInfo.variableCode[0].Value, "/");
            row.DataType = varInfo.dataType;
            //row.DataType = OD_Utils.ConvertToString(varInfo.dataType);
            row.VariableCode = vars[0] + "_" + row.DataType;

            // Check if the variable is already in the table or not
            //??? need to add ValueType filter
            cond = "VariableCode = '" + row.VariableCode + "'";
            if (OD_Utils.Exists(row.Table.TableName, cond, sqlConn))
            {
                return;
            }

            // VariableName is a tricky one too
            //??? I think VariableCode is enough to differentiate different variables
            cond = "Term = '" + varInfo.variableName + "'";
            if (OD_Utils.Exists("VariableNameCV", cond, sqlConn))
            {
                // Found it and use it
                row.VariableName = varInfo.variableName;
            }
            else
            {
                string myString = varInfo.variableName;
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\bas\b");
                string[] splitString = reg.Split(myString);

                // Refer to the document, e.g.,
                //    including "as", eg., "Nitrogen, nitrate (NO3) as N, filtered"
                //    fix ing "Calcium, filtered as Ca"
                if (splitString.Length == 2)
                {
                    row.VariableName = splitString[0];
                }
                else
                {
                    // Remove the string after ","
                    vars             = Regex.Split(varInfo.variableName, ",");
                    row.VariableName = vars[0];
                }
            }

            row.Speciation = varInfo.speciation; // "Not Applicable"; //?
            // Note: in DavtaValue Response Type units.unitsCode is actually unitsAbbreviation
            if (varInfo.unit.unitCode != null)
            {
                //cond = "UnitsName = '" + varInfo.unit.unitName + "'";
                //row.VariableUnitsID = OD_Utils.GetPrimaryKey("Units", "UnitsID", cond, sqlConn);
                //if (row.VariableUnitsID >= 143) row.VariableUnitsID = row.VariableUnitsID + 1;
                row.VariableUnitsID = Convert.ToInt32(varInfo.unit.unitCode);
            }
            else
            {
                row.VariableUnitsID = varInfo.unit.unitID;
            }


            row.SampleMedium = varInfo.sampleMedium;

            row.ValueType = varInfo.valueType;

            row.IsRegular = varInfo.timeScale.isRegular;

            row.TimeSupport = varInfo.timeScale.timeSupport;

            if (varInfo.timeScale.unit.unitCode != null)
            {
                row.TimeUnitsID = Convert.ToInt32(varInfo.timeScale.unit.unitCode);
            }
            else
            {
                row.TimeUnitsID = varInfo.timeScale.unit.unitID;
            }

            row.GeneralCategory = varInfo.generalCategory;

            if (varInfo.noDataValue != null)
            {
                row.NoDataValue = varInfo.noDataValue;
            }
            else
            {
                row.NoDataValue = -9999;
            }

            tblVariables.AddVariablesRow(row);
        }
Beispiel #46
0
    public override void Run(Context context)
    {
        var deleteScript = "if db_id('Dnn_Platform') is not null DROP DATABASE Dnn_Platform;";

        context.Information("Dropping LocalDb: {0}", ExecuteSqlScript(context, deleteScript));

        var createDbScript = string.Format(@"
        CREATE DATABASE
            [Dnn_Platform]
        ON PRIMARY (
           NAME=Dnn_data,
           FILENAME = '{0}\Dnn_Platform.mdf'
        )
        LOG ON (
            NAME=Dnn_log,
            FILENAME = '{0}\Dnn_Platform.ldf'
        )",
                                           context.tempDir
                                           );
        var createDbStatus = ExecuteSqlScript(context, createDbScript);

        context.Information("Created LocalDb: {0}", createDbStatus);

        if (createDbStatus)
        {
            connectionString = @"server=(localdb)\MSSQLLocalDB;Database=Dnn_Platform;Trusted_Connection=True;";

            var schemaScriptName = context.XmlPeek("./Website/Install/DotNetNuke.install.config.resources", "/dotnetnuke/scripts/script[@name='Schema']");
            var dataScriptName   = context.XmlPeek("./Website/Install/DotNetNuke.install.config.resources", "/dotnetnuke/scripts/script[@name='Data']");
            var schemaVersion    = context.XmlPeek("./Website/Install/DotNetNuke.install.config.resources", "/dotnetnuke/version");

            //#####################################################################
            //run initial schema first
            //#####################################################################
            var fileContents = System.IO.File.ReadAllText("./Website/Providers/DataProviders/SqlDataProvider/" + schemaScriptName.ToString() + ".SqlDataProvider");

            var      sqlDelimiterRegex = new System.Text.RegularExpressions.Regex("(?<=(?:[^\\w]+|^))GO(?=(?: |\\t)*?(?:\\r?\\n|$))", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
            string[] sqlStatements     = sqlDelimiterRegex.Split(fileContents);
            foreach (string statement in sqlStatements)
            {
                ExecuteSqlScript(context, statement);
            }
            context.Information("Initial Schema for v{0}", schemaVersion);

            //#####################################################################
            //populate with data next
            //#####################################################################
            fileContents = System.IO.File.ReadAllText("./Website/Providers/DataProviders/SqlDataProvider/" + dataScriptName.ToString() + ".SqlDataProvider");

            sqlStatements = sqlDelimiterRegex.Split(fileContents);
            foreach (string statement in sqlStatements)
            {
                context.Information("Test Data: {1}", schemaVersion, ExecuteSqlScript(context, statement));
            }

            var createDummyPortalStatement = "INSERT [dbo].[dnn_Portals] ([ExpiryDate], [UserRegistration], [BannerAdvertising], [AdministratorId], [Currency], [HostFee], [HostSpace], [AdministratorRoleId], [RegisteredRoleId], [GUID], [PaymentProcessor], [ProcessorUserId], [ProcessorPassword], [SiteLogHistory], [DefaultLanguage], [TimezoneOffset], [HomeDirectory], [PageQuota], [UserQuota], [CreatedByUserID], [CreatedOnDate], [LastModifiedByUserID], [LastModifiedOnDate], [PortalGroupID]) VALUES (NULL, 1, 0, 1, N'USD', 0.0000, 0, 0, 1, N'97debbc9-4643-4bd9-b0a0-b14170b38b0f', N'PayPal', NULL, NULL, 0, N'en-US', -8, N'Portals/0', 0, 0, -1, CAST(N'2015-02-05 14:49:37.873' AS DateTime), 1, CAST(N'2015-10-13 11:08:13.513' AS DateTime), -1)";

            context.Information("Test Portal: {1}", schemaVersion, ExecuteSqlScript(context, createDummyPortalStatement));

            //#####################################################################
            //now get all other SqlDataProvider files and run those....
            //#####################################################################
            var files = context.GetFiles("./Website/Providers/DataProviders/SqlDataProvider/*.SqlDataProvider");

            var currentFileToProcess = string.Empty;

            foreach (var file in files)
            {
                currentFileToProcess = file.GetFilenameWithoutExtension().ToString();
                var fileBits = currentFileToProcess.Split('.');

                int firstBit;
                int secondBit;
                int thirdBit;

                if (int.TryParse(fileBits[0], out firstBit) && int.TryParse(fileBits[1], out secondBit) && int.TryParse(fileBits[2], out thirdBit))
                {
                    var schemaVersionBits = schemaVersion.Split('.');

                    int schemaFirstBit  = int.Parse(schemaVersionBits[0]);
                    int schemaSecondBit = int.Parse(schemaVersionBits[1]);
                    int schemaThirdBit  = int.Parse(schemaVersionBits[2]);

                    if ((firstBit == schemaFirstBit && (secondBit >= schemaSecondBit && thirdBit >= schemaThirdBit)) || firstBit > schemaFirstBit)
                    {
                        context.Information("Updated to v{0}", currentFileToProcess);

                        fileContents = System.IO.File.ReadAllText(file.ToString());

                        sqlStatements = sqlDelimiterRegex.Split(fileContents);
                        foreach (string statement in sqlStatements)
                        {
                            var statementSuccess = ExecuteSqlScript(context, statement);
                        }
                    }
                }
            }
        }
        else
        {
            context.Information("An Error has occured. Please review and try again.");
        }
    }
Beispiel #47
0
 public static String[] Split(String Src, String SplitStr, System.Text.RegularExpressions.RegexOptions option)
 {
     System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(SplitStr, option);
     return(reg.Split(Src));
 }
Beispiel #48
0
 public static string[] SplitWithDoubleQuote(string str, char ch)
 {
     System.Text.RegularExpressions.Regex CSVParser = new System.Text.RegularExpressions.Regex(string.Format("{0}(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))", ch));
     return(CSVParser.Split(str));
 }