Пример #1
0
        public static string ClearComments(this string html)
        {
            html = html.CleanHeader();

            var starts = new List <int>();

            for (var i = 0; i < html.Length; i++)
            {
                if (i >= html.Length - 4)
                {
                    break;
                }

                i = html.IndexOf(@"<!--", i, StringComparison.Ordinal);
                if (i == -1)
                {
                    break;
                }
                starts.Add(i);
            }

            var ends = starts.Select(start => html.IndexOf(@"-->", start, StringComparison.Ordinal) + 3).ToList();

            var content = new StringBuilder(html).ToString();

            //Enable cleaning mso styling
            content = starts.Select((t, i) => html.Substring(t, ends[i] - t)).Aggregate(content, (current, comment) => current.Replace(comment, ""));

            content = content.Replace(@"<![if !vml]>", "");
            content = content.Replace(@"<![endif]>", "");



            content = content.Substring(content.IndexOf("<body"));
            content = content.Substring(content.IndexOf(">") + 1);
            content = content.Remove(content.LastIndexOf("</body>"), content.Length - content.LastIndexOf("</body>"));


            //deleting index from description
            if (content.Contains("<div style='mso-element:comment-list'>"))
            {
                content = content.Remove(content.IndexOf("<div style='mso-element:comment-list'>"));
            }

            for (int i = 0; ; i++)
            {
                if (!content.Contains(">["))
                {
                    break;
                }
                //content = content.Remove(content.IndexOf(">[")+1, 5);
                content = content.Remove(content.IndexOf(">[") + 1, (content.IndexOf("]</a>") + 1) - (content.IndexOf(">[") + 1));
            }
            return(content.Trim());
        }
        /// <summary>
        /// 添加QQ好友,必须依次完成VcodeStream、Vcode、SearchQQ的调用或设置才能成功
        /// </summary>
        /// <param name="qqnumber">要添加的QQ号码</param>
        /// <param name="mname">备注名称</param>
        /// <param name="groupid">添加到分组ID</param>
        /// <returns></returns>
        public Boolean AddFriends(String qqnumber, String mname, Int16 groupid)
        {
            var token = HttpRuntime.Cache.Get(qqnumber) as String;

            if (!String.IsNullOrEmpty(token))
            {
                //{"account":17008888,"myallow":1,"groupid":0,"mname":"马化腾","token":"9bd2771e072f288660638ed51daa5250854f5315bca7bfb4","vfwebqq":"9b262a4ed3b590fd5f71340a7ee686c1229b930b2a92e1c063c7a946913f497f5895e75d8410bfad"}//URLDECODE
                var postserializer = new {
                    account = qqnumber,
                    myallow = 1,
                    groupid = groupid,
                    mname   = mname,
                    token   = token,
                    vfwebqq = Vfwebqq
                };
                var result = new JavaScriptSerializer();

                token = new StringBuilder("r=").Append(HttpUtility.UrlEncode(result.Serialize(postserializer))).ToString();
                token = CreateRequest("http://s.web2.qq.com/api/add_no_verify2", token, true);
                if (token.Contains(qqnumber))
                {
                    HttpRuntime.Cache.Remove(qqnumber);     //移除token
                    HttpRuntime.Cache.Remove("AllFriends"); //移除所有好友缓存
                    var resultdic = (Dictionary <String, Object>)result.DeserializeObject(token);
                    resultdic = (Dictionary <String, Object>)resultdic["result"];
                    HttpRuntime.Cache.Insert(resultdic["tuin"].ToString(), qqnumber, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(120), CacheItemPriority.Normal, null);//添加UIN转QQ缓存
                    return(true);
                }
            }
            return(false);
        }
Пример #3
0
        private static string BuildMetaRowFormat(ConsoleTableBuilder builder)
        {
            var result = new StringBuilder().AppendFormat(builder.Options.MetaRowFormat, builder.Options.MetaRowParams).ToString();

            if (result.Contains(AppConstants.MetaRow.ROW_COUNT))
            {
                result = result.Replace(AppConstants.MetaRow.ROW_COUNT, builder.Rows.Count.ToString());
            }

            if (result.Contains(AppConstants.MetaRow.COLUMN_COUNT))
            {
                result = result.Replace(AppConstants.MetaRow.COLUMN_COUNT, builder.GetCadidateColumnLengths().Count.ToString());
            }

            return(result);
        }
Пример #4
0
        public static string AsProperNoun(this string s)
        {
            var  builder = new StringBuilder();
            bool newWord = true;

            foreach (char c in s)
            {
                if (newWord && c.IsLetter())
                {
                    builder.Append(c.ToUpper());
                    newWord = false;
                }
                else if (!c.IsLetter() && c != '-')
                {
                    builder.Append(c);
                    newWord = true;
                }
                else
                {
                    builder.Append(c.ToLower());
                }
            }

            while (builder.Contains("  "))
            {
                builder.Replace("  ", " ");
            }

            return(builder.ToString());
        }
        public void AppendError(string errorMessage)
        {
            if (Content != null)
            {
                if (Content.HasError)
                {
                    var currentError = new StringBuilder(Content.ErrorMessage);
                    if (!string.IsNullOrEmpty(errorMessage) && !currentError.Contains(errorMessage))
                    {
                        currentError.Append(errorMessage);
                        Content.ErrorMessage = currentError.ToString();
                    }
                }
                else
                {
                    Content.ErrorMessage = errorMessage;
                }

                Content.HasError = true;
                OnPropertyChanged("Content.ErrorMessage");
                OnPropertyChanged("Content.HasError");
                OnPropertyChanged(nameof(Content));
                HasError = true;
            }
        }
        public void Contains_StringBuilderNull()
        {
            StringBuilder builder     = null;
            bool          doesContain = builder.Contains("abc");

            Assert.IsFalse(doesContain);
        }
Пример #7
0
        static void Main(string[] args)
        {
            StringBuilder str = new StringBuilder();

            str.Append("Hello_World !!!");
            Console.WriteLine("Index is at: " + str.IndexOf("World", 1));
            Console.WriteLine("Index is at: " + str.IndexOf("H"));
            Console.WriteLine("Index is at: " + str.IndexOf("e"));
            Console.WriteLine("Index is at: " + str.IndexOf("l"));
            Console.WriteLine("Index is at: " + str.IndexOf("l", 3));
            Console.WriteLine("Index is at: " + str.IndexOf("o"));
            Console.WriteLine("Index is at: " + str.IndexOf("W"));
            Console.WriteLine("Index is at: " + str.IndexOf("o"));
            Console.WriteLine("Index is at: " + str.IndexOf("r"));
            Console.WriteLine("Index is at: " + str.IndexOf("l"));
            Console.WriteLine("Index is at: " + str.IndexOf("d"));

            Console.WriteLine("Substring 5 to end: " + str.Substring(5));

            Console.WriteLine("Substring 1, length 1: " + str.Substring(1, 1));

            StringBuilder[] strs = str.Split(new String[] { " ", "_" });

            Console.WriteLine("Does string contain Hello? " + str.Contains("Hello"));

            Console.WriteLine("Does string end with !!!? " + str.EndsWith("!!!"));

            Console.WriteLine("Last index of !: " + str.LastIndexOf("!"));

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        } //end main
        public void Contains_Returns_Expected_Results(string text, char searchChar, bool expected)
        {
            var builder = new StringBuilder(text);

            var actual = builder.Contains(searchChar);

            Assert.AreEqual(expected, actual);
        }
        public void Contains_SubStringEmpty()
        {
            StringBuilder builder     = new StringBuilder();
            string        subString   = null;
            bool          doesContain = builder.Contains(subString);

            Assert.IsFalse(doesContain);
        }
Пример #10
0
        public void Add(params string[] contents)
        {
            if (contents.Contains("}"))
            {
                this.tabs -= 1;
            }
            string tabs = new String('\t', this.tabs);

            this.contents.Append(tabs);
            foreach (var data in contents)
            {
                this.contents.Append(data);
            }
            this.contents.Append("\n");
            if (contents.Contains("{"))
            {
                this.tabs += 1;
            }
        }
        public void Contains_SubStringOverlapsEnd()
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("bcdef");
            string subString   = "efg";
            bool   doesContain = builder.Contains(subString);

            Assert.IsFalse(doesContain);
        }
        public void Contains_SubStringDiffersInCaseOnly()
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("abcdefg");
            string subString   = "CDE";
            bool   doesContain = builder.Contains(subString);

            Assert.IsFalse(doesContain);
        }
        public void Contains_SubStringInMiddle()
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("bcdef");
            string subString   = "cde";
            bool   doesContain = builder.Contains(subString);

            Assert.IsTrue(doesContain);
        }
        public void Contains_StringBuilderNOTContainsChar_ReturnsFalse()
        {
            // Arrange
            StringBuilder lSb = new StringBuilder("5×7+2^(3)");

            // Act
            bool lResult = lSb.Contains('y');

            // Assert
            Assert.IsFalse(lResult);
        }
Пример #15
0
        public void ExtensionMethods_Contains_WhenSubstringIsNotContained_ExpectFalse()
        {
            //------------Setup for test--------------------------
            StringBuilder value = new StringBuilder("a b c");

            //------------Execute Test---------------------------
            var result = value.Contains(" bq");

            //------------Assert Results-------------------------
            Assert.IsFalse(result);
        }
        public void Contains_StringsAreNonAscii()
        {
            StringBuilder builder = new StringBuilder();

            //Some random japanese characters, not a perfect test I know but it shows
            //that the function works with non ascii characters.
            builder.Append("\u3041\u3042\u3043");
            string subString   = "\u3042";
            bool   doesContain = builder.Contains(subString);

            Assert.IsTrue(doesContain);
        }
Пример #17
0
        public static bool Contains(this StringBuilder s, string[] ss)
        {
            bool f = false;

            foreach (var x in ss)
            {
                if (s.Contains(x))
                {
                    f = true;
                }
            }
            return(f);
        }
        public static StringBuilder FCBuilder(StringBuilder FCString, StringBuilder funbuilder = null)
        {
            if (FCString == null)
            {
                return(null);
            }

            var noWildOrs  = new string[] { "~_or_", "~_~_", "~,_" };
            var wildOrs    = new string[] { ",_", "_~_", "_or_" };
            var noWildAnds = new string[] { "~_&&_", "~_and_" };
            var wildAnds   = new string[] { "_&&_", "_and_" };
            var abbyAlts   = new string[] { "abbybot", "abby_kaioken" };

            FCString.Replace(" ", "_").Replace(abbyAlts, "abigail_williams");
            if (FCString.Length > 0)
            {
                if (!FCString.EndsWith('~'))
                {
                    FCString.Append("*");
                }
                else
                {
                    FCString.RemoveEnd(1);
                }
            }
            if (FCString.Contains(wildOrs))
            {
                FCString.AppendStartEnd("{", "}");
                FCString.Replace(noWildOrs, " ~ ").Replace(wildOrs, "* ~ ");
            }
            FCString.Replace(noWildAnds, " ").Replace(wildAnds, "* ");
            while (FCString.Contains("**"))
            {
                FCString.Replace("**", "*");
            }
            return(FCString);
        }
Пример #19
0
        private void SetEnvironment()
        {
            StringBuilder current = new StringBuilder(Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine));

            if (!current.Contains(FolderPath))
            {
                // Folder path always ends with \
                if (current[current.Length - 1] != ';')
                {
                    current.Append(';');
                }
                current.Append(FolderPath);
                Environment.SetEnvironmentVariable("Path", current.ToString(), EnvironmentVariableTarget.Machine);
            }
        }
Пример #20
0
        public async Task Integration_LoggerMiddleware_HappyFlow()
        {
            //arrange
            var server = CreateServer();

            _webServer = CreateServer().CreateServer(_baseUrl, true, _rootFolder, _defaultFile, true, string.Empty, string.Empty);

            //act / assert
            using (var client = new HttpClient())
                using (var response = await client.GetAsync(_baseUrl))
                {
                    Assert.IsNotNull(response);
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                    Assert.IsTrue(_console.Contains(_baseUrl));
                }
        }
Пример #21
0
        private static string GetTestResultFilePath(int processId, string testNamespace)
        {
            var tests = new StringBuilder(testNamespace).ToString();

            if (tests.Contains(","))
            {
                tests = tests.Remove(tests.IndexOf(",", StringComparison.Ordinal));
                tests = tests + "_GroupedTests";
            }
            tests = tests.Replace("\"", "");

            var testResultFileName = Path.Combine(Environment.CurrentDirectory,
                                                  processId.ToString(CultureInfo.InvariantCulture),
                                                  string.Format("{0}-{1}.xml", Guid.NewGuid().ToString().Remove(6), tests));

            return(testResultFileName);
        }
Пример #22
0
        public string SlugWithLinqFinalizeWithLoop()
        {
            var str = new StringBuilder().Append(input.Select(c =>
            {
                if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.LetterNumber)
                {
                    return('-');
                }
                return(c);
            }).ToArray()).ToString();

            while (str.Contains("--"))
            {
                str = str.Replace("--", "-");
            }

            return(str);
        }
Пример #23
0
        public void Combining_Multiple_Files()
        {
            var cr = new ContentResolver { ContentDir = FileSets() };

            var paths = new List<string>
            {
                "~/Multiple_File_Set/Single-File-0.js",
                "~/Multiple_File_Set/Single-File-1.js",
                "~/Multiple_File_Set/Single-File-2.js",
                "~/Multiple_File_Set/Single-File-3.js"
            };

            var buff = new StringBuilder().CombineContents(paths, cr).ToString();

            var names = paths.Select(p => Path.GetFileName(p));

            Expect(names.All(name => buff.Contains(name)));
        }
        /// <summary>
        /// подготавливает строку к хешированию
        /// </summary>
        /// <param name="data">входной набор символов</param>
        /// <returns>StringBuilder or null</returns>
        private StringBuilder CleanString(string data)
        {
            if (string.IsNullOrEmpty(data)) return null;

            HtmlParser parser = new HtmlParser();
            var result = new StringBuilder(data.ToLower());
            parser.ClearContent(result);
            for (int i = 0; i < this.keywords.Length; i++)
            {
                if (this.keywords[i] != "")
                {
                    while (result.Contains(this.keywords[i]) >= 0)
                        result.Replace(this.keywords[i], string.Empty);
                }
            }
            parser.ClearContent(result);//еще раз зачищаем строку
            return result;
        }
Пример #25
0
    private string CleanHTML(string htmlText)
    {
        htmlText = new StringBuilder(htmlText)
                   .Replace("<pre", "<code")
                   .Replace("</pre", "</code")
                   .Replace("<em", "<b")
                   .Replace("</em", "</b")
                   .Replace("’", "'")
                   .Replace("[caption", "<caption")
                   //.Replace("[/caption]", "")
                   .Replace("[/caption]", "</caption>")
                   .Replace("]<img", "><img")
                   .ToString();

        if (htmlText.Contains("�"))
        {
            //ColoredConsole.WriteLineWithColor("- Broken symbol found, this file isn't encoded using UTF-8 and doesn't contain a BOM. Some characters may be incorrect.", ConsoleColor.Red);
            htmlText = htmlText.Replace("�", "'");
        }

        htmlText = ConvertCaptionsToMarkdown(htmlText);

        return(htmlText);
    }
		public void Contains_SubStringEmpty()
		{
			StringBuilder builder = new StringBuilder();
			string subString = null;
			bool doesContain = builder.Contains(subString);
			Assert.IsFalse(doesContain);
		}
        internal static List <List <string> > TokenizeTextFile(string filename)
        {
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException("Cannot parse file that does not exist", filename);
            }

            // Do replacement of characters here
            StringBuilder massagedFileText = new StringBuilder();

            massagedFileText.Append(File.ReadAllText(filename));
            massagedFileText
            .Replace('!', '.').Replace('?', '.')
            .Replace("'", string.Empty).Replace("`", string.Empty).Replace("\"", " ")
            .Replace("\t", " ").Replace(",", " ").Replace(";", " ").Replace(":", " ").Replace("-", " ")
            ;

            massagedFileText
            .Replace("\\", " ").Replace("/", " ")
            .Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ")
            .Replace("{", " ").Replace("}", " ").Replace("<", " ").Replace(">", " ")
            .Replace("+", " ").Replace("=", " ").Replace("$", " ").Replace("&", " ")
            .Replace("@", " ").Replace("#", " ").Replace("%", " ")
            .Replace("^", " ").Replace("*", " ").Replace("~", " ")
            ;

            massagedFileText
            .Replace("\r", "").Replace("\n", " ");

            if (massagedFileText.Contains("1st"))
            {
                massagedFileText
                .Replace("1st", "first").Replace("2nd", "second").Replace("3rd", "third").Replace("4th", "fourth").Replace("5th", "fifth")
                .Replace("6th", "sixth").Replace("7th", "seventh").Replace("8th", "eighth").Replace("9th", "ninth").Replace("10th", "tenth")
                .Replace("11th", "eleventh").Replace("12th", "twelfth").Replace("13th", "thirteenth").Replace("14th", "fourteenth").Replace("15th", "fifteenth")
                ;
            }

            if (massagedFileText.ToString().Any(c => Char.IsDigit(c)))
            {
                massagedFileText
                .Replace("0", "zero ")
                .Replace("1", "one ")
                .Replace("2", "two ")
                .Replace("3", "three ")
                .Replace("4", "four ")
                .Replace("5", "five ")
                .Replace("6", "six ")
                .Replace("7", "seven ")
                .Replace("8", "eight ")
                .Replace("9", "nine ")
                ;
            }

            bool contractions = true;

            if (contractions)
            {
                massagedFileText
                .Replace("arent", "are not")
                .Replace("cant", "cannot")
                .Replace("couldnt", "could not")
                .Replace("didnt", "did not")
                .Replace("doesnt", "does not")
                .Replace("dont", "do not")
                .Replace("hadnt", "had not")
                .Replace("hasnt", "has not")
                .Replace("havent", "have not")
                .Replace("im", "i am")
                .Replace("ive", "i have")
                .Replace("isnt", "is not")
                .Replace("lets", "let us")
                .Replace("mightnt", "might not")
                .Replace("mustnt", "must not")
                .Replace("shant", "shall not")
                .Replace("shouldnt", "should not")
                .Replace("theyre", "they are")
                .Replace("theyve", "they have")
                .Replace("were", "we are")
                .Replace("weve", "we have")
                .Replace("werent", "were not")
                .Replace("whatre", "what are")
                .Replace("whatve", "what have")
                .Replace("w***e", "who are")
                .Replace("whove", "who have")
                .Replace("wont", "will not")
                .Replace("wouldnt", "would not")
                .Replace("youre", "you are")
                .Replace("youve", "you have")
                ;
            }

            massagedFileText = ReplaceWhile(massagedFileText.ToString(), "  ", " ");

            string massagedText      = massagedFileText.ToString();
            string sanitizedFileText = new string(massagedText.Where(c => AllowedChars.Contains(c)).ToArray());

            if (massagedText != sanitizedFileText)
            {
                int         index       = 0;
                int         offset      = 0;
                List <int>  diffIndices = new List <int>();
                List <char> diffChars   = new List <char>();
                foreach (char c in sanitizedFileText)
                {
                    if (c != massagedText[index + offset])
                    {
                        diffIndices.Add(index + offset);
                        diffChars.Add(massagedText[index + offset]);
                        offset++;
                    }
                    index++;
                }

                string diff = string.Join("\n", diffIndices.Select(i => i.ToString()));                 //new string(diffChars.ToArray());
                throw new Exception(diff);
            }

            string outputFilename = "NORMALIZED__" + Path.GetFileName(filename);

            File.WriteAllText(outputFilename, sanitizedFileText);

            //List<string> fileLines = sanitizedFileText.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
            //List<List<string>> fileParagraph = fileLines.Select(p => p.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList()).ToList();

            List <string> fileSentences = sanitizedFileText.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();

            int totalWordCount           = 0;
            List <List <string> > result = new List <List <string> >();

            foreach (string sentence in fileSentences)
            {
                List <string> words = sentence.Split(' ').ToList();
                totalWordCount += words.Count;
                result.Add(words);
            }

//#if DEBUG
//			string debugParsedFileFilename = string.Format("Debug.{0}.Parsed.{1}.txt", Path.GetFileNameWithoutExtension(filename), totalWordCount);
//			FileInfo parseFile = new FileInfo(debugParsedFileFilename).RenameIfExists();
//			int counter = 1;
//			File.AppendAllText(
//				parseFile.FullName,
//				string.Join(
//					Environment.NewLine,
//					sentences.Select(l =>
//						string.Format("Sentence{0} = \"{1}\".", counter++, string.Join(" ", l))
//			)	)	);
//#endif
            return(result);
        }
        public IEnumerable<string> GetAttributeValue(string data, string template, string attributeName)
        {            
            template = ClearContent(template);

            var templateParts = template.ToLower().Split('*');
            var content = new StringBuilder(data.ToLower());
            ClearContent(content);
            template = ClearContent(template);
            int startPos = content.Contains(templateParts[0]);
            if (startPos == -1) yield return string.Empty;
            
            int endPos = content.Contains(templateParts[1], startPos + templateParts[0].Length - 1);

            if (startPos != -1 && endPos != -1)
            {
                content.Remove(0, startPos);
                startPos = content.Contains(templateParts[0]);
                endPos = content.Contains(templateParts[1], startPos + templateParts[0].Length - 1);
                if (startPos != -1 && endPos != -1)
                {
                    content.Remove(endPos + templateParts[1].Length, content.Length - (endPos + templateParts[1].Length));
                }
            }            

            while (startPos != -1 && endPos != -1)
            {
                startPos = content.Contains(attributeName, startPos);
                if (startPos == -1) yield return string.Empty;//return result;

                endPos = content.Contains(">", startPos);
                if (endPos == -1) yield return string.Empty;  //return result;

                char[] destination = new char[endPos - (startPos + attributeName.Length)];
                content.CopyTo(startPos + attributeName.Length, destination, 0, endPos - (startPos + attributeName.Length));
                int breakPos = -1;
                for (int i = 0; i < destination.Length; i++)
                    if (destination[i] == ' ')
                    {
                        breakPos = i;
                        break;
                    }
                if (breakPos > -1)
                {
                    Array.Resize<char>(ref destination, breakPos);
                }


                string link = new string(destination);
                //if (!link.StartsWith("host"))
                //    link = host + '/' + link;
                //link = link.Replace("/./", "/");

                //result.Add(link);
                startPos = content.Contains(attributeName, endPos);
                endPos = content.Contains(">", startPos + attributeName.Length - 1);
                yield return RemoveTags(link);
            }
            yield return string.Empty;//return result;
        }
Пример #29
0
        public void WebManager_Serve_PortUnavailable()
        {
            //arrange
            var service = CreateManager();

            _networkServiceMock.Setup(m => m.PortAvailable(_port)).Returns(false);

            //act
            service.Serve(_port, string.Empty, string.Empty, false, false, string.Empty, string.Empty);

            //assert
            Assert.IsTrue(_console.Contains(string.Format(Strings.port_in_use, _port)));
        }
Пример #30
0
        public string CopyFileToLocal(string version, UpdateFile file)
        {
            // Build remote path.
            string remotePath = new StringBuilder()
                                .Append(VersionsManager.Instance.LocalInformation.UpdateServerUrl)
                                .Append(Path.DirectorySeparatorChar)
                                .Append(version)
                                .Append(Path.DirectorySeparatorChar)
                                .Append(file.DestinationFolder)
                                .Append(Path.DirectorySeparatorChar)
                                .Append(file.Name)
                                .ToString();
            // Build local path.
            string localPath = new StringBuilder()
                               .Append(SettingsManager.Instance.BasePath)
                               .Append(Path.DirectorySeparatorChar)
                               .Append(Strings.FOLDER_UPDATE_INFORMATION)
                               .Append(Path.DirectorySeparatorChar)
                               .Append(Strings.FOLDER_TEMP_DOWNLOAD)
                               .Append(Path.DirectorySeparatorChar)
                               .Append(file.Name)
                               .ToString();
            // Get new downloader.
            Downloader downloader = new Downloader();

            ReportMessage(
                new StringBuilder().Append(Strings.MESSAGE_DOWNLOADING_TBC)
                .Append(remotePath)
                .Append(" -> ")
                .Append(localPath)
                .ToString());

            DownloaderState dlState = DownloaderState.OK;

            // switch download based on protocoll and/or location and load file.
            if (remotePath.Contains(Strings.SEARCHSTRING_HTTP) || remotePath.Contains(Strings.SEARCHSTRING_HTTPS))
            {
                dlState = downloader.Download(
                    remotePath,
                    localPath,
                    VersionsManager.Instance.LocalInformation.ServerUser.Name,
                    VersionsManager.Instance.LocalInformation.ServerUser.Pwd,
                    VersionsManager.Instance.LocalInformation.Proxy.Url,
                    VersionsManager.Instance.LocalInformation.Proxy.ProxyUser.Name,
                    VersionsManager.Instance.LocalInformation.Proxy.ProxyUser.Pwd,
                    VersionsManager.Instance.LocalInformation.Proxy.HttpsPort);
            }
            else if (remotePath.StartsWith(Strings.STARTSTRING_LAN) || remotePath.Contains(Strings.SEARCHSTRING_LOCAL))
            {
                dlState = downloader.Download(
                    remotePath,
                    localPath,
                    VersionsManager.Instance.LocalInformation.ServerUser.Name,
                    VersionsManager.Instance.LocalInformation.ServerUser.Pwd);
            }
            while (!downloader.DownloadFinished && dlState == DownloaderState.Running)
            {
                Thread.Sleep(200);
                Application.DoEvents();
                ReportProgress(downloader.PercentFinished);
            }
            if (dlState == DownloaderState.ErrorDestinationNotAccessible || dlState == DownloaderState.ErrorDownloadFailed)
            {
                ReportMessage(Strings.MESSAGE_DOWNLOAD_FAILED);
                return("0");
            }
            ReportMessage(Strings.MESSAGE_DOWNLOAD_FINISHED);
            return(localPath);
        }
Пример #31
0
        /// <summary>
        /// constructor, open template from file
        /// </summary>
        /// <param name="AFullPath"></param>
        public ProcessTemplate(string AFullPath = null)
        {
            if ((AFullPath == null) || (AFullPath.Length == 0))
            {
                return;
            }

            if (!File.Exists(AFullPath))
            {
                throw new Exception("Cannot find template file " + AFullPath + "; please adjust the TemplateDir parameter");
            }

            StreamReader r;

            r             = File.OpenText(AFullPath);
            FTemplateCode = new StringBuilder();

            while (!r.EndOfStream)
            {
                string line = r.ReadLine().TrimEnd(new char[] { '\r', '\t', ' ', '\n' }).Replace("\t", "    ");
                FTemplateCode.Append(line).Append(Environment.NewLine);
            }

            r.Close();

            // add other files, {#INCLUDE <filename>}
            while (FTemplateCode.Contains("{#INCLUDE "))
            {
                Int32  pos             = FTemplateCode.IndexOf("{#INCLUDE ");
                Int32  newLinePos      = FTemplateCode.IndexOf(Environment.NewLine, pos);
                string line            = FTemplateCode.Substring(pos, newLinePos - pos);
                Int32  bracketClosePos = FTemplateCode.IndexOf("}", pos);
                string filename        = FTemplateCode.Substring(pos + "{#INCLUDE ".Length, bracketClosePos - pos - "{#INCLUDE ".Length).Trim();

                // do this recursively, to get snippets and code in the right place, even from the include files
                ProcessTemplate includedTemplate = new ProcessTemplate(Path.GetDirectoryName(AFullPath) + Path.DirectorySeparatorChar + filename);

                FTemplateCode = FTemplateCode.Replace(line, includedTemplate.FTemplateCode.ToString());

                foreach (string key in includedTemplate.FSnippets.Keys)
                {
                    FSnippets.Add(key, includedTemplate.FSnippets[key]);
                }
            }

            // split off snippets (identified by "{##")
            if (FTemplateCode.Contains("{##"))
            {
                StringCollection snippets = StringHelper.StrSplit(FTemplateCode.ToString(), "{##");

                // first part is the actual template code
                FTemplateCode = new StringBuilder(snippets[0]);

                for (int counter = 1; counter < snippets.Count; counter++)
                {
                    string snippetName = snippets[counter].Substring(0, snippets[counter].IndexOf("}"));

                    // exclude first newline
                    string snippetText = snippets[counter].Substring(snippets[counter].IndexOf(Environment.NewLine) + Environment.NewLine.Length);

                    // remove all whitespaces from the end, but keep one line ending for ENDIF etc
                    snippetText = snippetText.TrimEnd(new char[] { '\n', '\r', ' ', '\t' }) + Environment.NewLine;
                    FSnippets.Add(snippetName, snippetText);
                }
            }

            // just make sure that there is a newline at the end, for ENDIF etc
            FTemplateCode.Append(Environment.NewLine);
        }
        public string GetSingleContent(string data, string template)
        {
            var templateParts = template.ToLower().Split('*');
            if (templateParts != null && templateParts.Length == 2)
            {
                templateParts[0] = ClearContent(templateParts[0]);
                templateParts[1] = ClearContent(templateParts[1]);
            }
            var content = new StringBuilder(data.ToLower());
            ClearContent(content);
            int startPos = content.Contains(templateParts[0]);
            if (startPos == -1) return string.Empty;
            int endPos = content.Contains(templateParts[1], startPos + templateParts[0].Length );
            if (startPos != -1 && endPos != -1)
            {
                char[] destination = new char[endPos - startPos + templateParts[0].Length];
                content.CopyTo(startPos + templateParts[0].Length, destination, 0, endPos - (startPos + templateParts[0].Length));
                string result = new string(destination);

                content = null;

                return result;//RemoveTags(result).Trim();
            }
            content = null;
            return string.Empty;//return result;
        }
Пример #33
0
        internal static void GenerateUsings(StringBuilder stringBuilder, IElement saveObject)
        {
            if (stringBuilder.Contains("// Generated Usings"))
            {
                ICodeBlock usings = new CodeDocument();

                UsingsCodeGenerator.GenerateUsingStatements(usings, saveObject);

                int startOfUsingSection = GetIndexAfter("// Generated Usings", stringBuilder);
                stringBuilder.Insert(startOfUsingSection, usings.ToString());
            }
        }
        public void ExtensionMethods_Contains_WhenSubstringIsNotContained_ExpectFalse()
        {
            //------------Setup for test--------------------------
            StringBuilder value = new StringBuilder("a b c");

            //------------Execute Test---------------------------
            var result = value.Contains(" bq");

            //------------Assert Results-------------------------
            Assert.IsFalse(result);
        }
		public void Contains_SubStringOverlapsEnd()
		{
			StringBuilder builder = new StringBuilder();
			builder.Append("bcdef");
			string subString = "efg";
			bool doesContain = builder.Contains(subString);
			Assert.IsFalse(doesContain);
		}
Пример #36
0
        private NavItem ParseDirectory(string dir)
        {
            IEnumerable <string> dirs = Directory.EnumerateDirectories(dir);

            string dirName = dir.Contains("Bleeding") ? dir.Trim('\\').Split('\\').Last()
                                 : Nav.tt.ToTitleCase(dir.Trim('\\').Split('\\').Last());

            if (dirName.Contains("-"))
            {
                dirName = dirName.Split('-')[1].Trim();
            }

            NavItem current = new NavItem(dirName);

            string[] xml = Directory.GetFiles(dir, "*.update");

            XmlSerializer xs = new XmlSerializer(typeof(UpdateManifest));

            foreach (string x in xml)
            {
                UpdateManifest manifest;
                using (var fs = new FileStream(x, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    manifest = xs.Deserialize(fs) as UpdateManifest;
                }

                string version     = Version.Parse(manifest.Version).ToString(4);
                string versionSafe = version.Replace(".", "_");

                StringBuilder md = new StringBuilder();

                md.AppendLine("---");
                md.AppendLine("uid: gaea_" + versionSafe);
                md.AppendLine("title: Gaea " + version);
                md.AppendLine("---\n\n");
                md.AppendLine($"**Released on {manifest.ReleaseDate:dd MMMM yyyy}**\n");
                md.AppendLine($"<a href=\"{manifest.URL}\">Download {manifest.Size / 1024.0 / 1024.0:F}MB</a> <br>");
                md.AppendLine("\n");
                md.AppendLine("<div class=\"release-note\">\n");
                md.AppendLine(manifest.FullDescription);
                md.AppendLine("</div>");

                File.WriteAllText($"{Path.GetDirectoryName(x)}\\{version}.md", md.ToString());
            }

            string[] mds = Directory.GetFiles(dir, "*.md");

            if (dir.Contains("Changelogs"))
            {
                mds = mds.OrderByDescending(x => x).ToArray();
            }

            foreach (string md in mds.Where(md => !md.ToLower().EndsWith(".params.md") && !md.Contains("--")))
            {
                var temp = Nav.GetNavItem(md);
                temp.Link = Nav.ReplaceNumbers(temp.Link.Replace(Nav.RootPath + "source", string.Empty).Replace("\\", "/").Replace(".md", ".html"));

                if (temp.Show)
                {
                    current.Items.Add(temp);
                }

                MDs.Add(md);
            }

            foreach (string d in dirs)
            {
                current.Items.Add(ParseDirectory(d));
            }

            return(current);
        }
		public void Contains_SubStringDiffersInCaseOnly()
		{
			StringBuilder builder = new StringBuilder();
			builder.Append("abcdefg");
			string subString = "CDE";
			bool doesContain = builder.Contains(subString);
			Assert.IsFalse(doesContain);
		}
		public void Contains_StringsAreNonAscii()
		{
			StringBuilder builder = new StringBuilder();

			//Some random japanese characters, not a perfect test I know but it shows
			//that the function works with non ascii characters.
			builder.Append("\u3041\u3042\u3043");
			string subString = "\u3042";
			bool doesContain = builder.Contains(subString);
			Assert.IsTrue(doesContain);
		}
Пример #39
0
 /// <summary>
 ///     Determines whether the specified source contains whitespace.
 /// </summary>
 /// <param name="src">
 ///     The source.
 /// </param>
 /// <returns>
 ///     The <see cref="bool" />.
 /// </returns>
 internal static bool ContainsWhitespace(this StringBuilder src)
 {
     return(src.Contains(' ', '\r', '\n', '\t'));
 }
		public void Contains_SubStringInMiddle()
		{
			StringBuilder builder = new StringBuilder();
			builder.Append("bcdef");
			string subString = "cde";
			bool doesContain = builder.Contains(subString);
			Assert.IsTrue(doesContain);
		}
Пример #41
0
        public static void GenerateCode(IElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            string template;

            if (element is ScreenSave)
            {
                template = mScreenTemplateGeneratedCode;
            }
            else
            {
                template = mEntityTemplateGeneratedCode;
            }

            // Since anything can modify an enumeration value we want to make sure that
            // it's proper before generating code for it:

            // If enumeration values don't work property let's just print some output and carry on
            try
            {
                element.FixEnumerationValues();
            }
            catch (Exception e)
            {
                PluginManager.ReceiveError("Error fixing enumerations for " + element + ": " + e.ToString());
            }

            // Do this before doing anything else since 
            // these reusable entire file RFS's are used 
            // in other code.
            RefreshReusableEntireFileRfses(element);

            EventCodeGenerator.GenerateEventGeneratedFile(element);

            if (element.Events.Count != 0)
            {
                var sharedCodeFullFileName = 
                    EventResponseSave.GetSharedCodeFullFileName(element, FileManager.GetDirectory(ProjectManager.GlueProjectFileName));

                EventCodeGenerator.CreateEmptyCodeIfNecessary(element,
                    sharedCodeFullFileName, false);
            }



            EventCodeGenerator.AddStubsForCustomEvents(element);

            CreateGeneratedFileIfNecessary(element);

            StringBuilder stringBuilder = new StringBuilder(template);

            foreach (PluginManager pluginManager in PluginManager.GetInstances())
            {
                CodeGeneratorPluginMethods.CallCodeGenerationStart(pluginManager, element);
            }

            if (ContentLoadWriter.SuppressGlobalContentDictionaryRefresh == false)
            {
                ReferencedFileSaveCodeGenerator.RefreshGlobalContentDictionary();
            }

            if (ReferencedFileSaveCodeGenerator.GlobalContentFilesDictionary == null)
            {
                throw new Exception("Global content files dictionary should not be null");
            }

            string objectName = FileManager.RemovePath(element.Name);

            string projectNamespace = ProjectManager.ProjectNamespace;

            if (element is EntitySave)
            {
                string directory = FileManager.MakeRelative(FileManager.GetDirectory(element.Name));

                if (directory.ToLower() != "Entities/".ToLower())
                {
                    string relativeDirectory = FileManager.MakeRelative(directory);
                    relativeDirectory = relativeDirectory.Substring(0, relativeDirectory.Length - 1);
                    relativeDirectory = relativeDirectory.Replace('/', '.');

                    projectNamespace += "." + relativeDirectory;
                }
            }
            else if (element is ScreenSave)
            {
                projectNamespace += ".Screens";
            }

            string contentManagerName = element.UseGlobalContent ? "\"Global\"" : null;
            ScreenSave asScreenSave = element as ScreenSave;
            if (asScreenSave != null &&
                !string.IsNullOrEmpty(asScreenSave.ContentManagerMethod))
            {
                contentManagerName = asScreenSave.ContentManagerMethod;
            }

            var whatToInheritFrom = GetInheritance(element);
            CodeWriter.SetClassNameAndNamespace(
                projectNamespace,
                objectName,
                stringBuilder,
                !string.IsNullOrEmpty(contentManagerName),
                contentManagerName,
                whatToInheritFrom
                );

            #region Make Activity, Initialize, PostInitalize, and Destroy "override" if necessary

            if ( element.InheritsFromElement())
            {

                if (stringBuilder.Contains("virtual void Initialize"))
                {
                    stringBuilder.Replace("virtual void Initialize", "override void Initialize");
                }

                if (stringBuilder.Contains("virtual void Activity"))
                {
                    stringBuilder.Replace("virtual void Activity", "override void Activity");
                }

                if (stringBuilder.Contains("virtual void Destroy"))
                {
                    stringBuilder.Replace("virtual void Destroy", "override void Destroy");
                }
            }

            #endregion

            try
            {
                CodeWriter.GenerateUsings(stringBuilder, element);
            }
            catch (Exception e)
            {
                string stackTrace = e.StackTrace;

                throw new Exception("Error trying to generate using statements for " + element + "\n\n" + stackTrace, e);
            }

            #region Generate Fields

            ICodeBlock fieldsSection = CodeWriter.GenerateFields(element);
            int startOfFieldsSection = CodeWriter.GetIndexAfter("// Generated Fields", stringBuilder);
            stringBuilder.Insert(startOfFieldsSection, fieldsSection.ToString());

            #endregion


            #region Generate Initialize

            ICodeBlock initializeSection = CodeWriter.GenerateInitialize(element);
            int startOfInitializeSection = CodeWriter.GetIndexAfter("// Generated Initialize", stringBuilder);
            stringBuilder.Insert(startOfInitializeSection, initializeSection.ToString());

            #endregion


            #region Generate AddToManagers

            int startOfAddToManagers = CodeWriter.GetIndexAfter("// Generated AddToManagers", stringBuilder);
            ICodeBlock addToManagersSection = CodeWriter.GenerateAddToManagers(element);
            stringBuilder.Insert(startOfAddToManagers, addToManagersSection.ToString());


            #endregion


            #region GenerateActivity



            ICodeBlock activityBlock = new CodeDocument(3);
            ICodeBlock currentBlock = activityBlock;

            currentBlock = CodeWriter.GenerateActivity(currentBlock, element);
            currentBlock = CodeWriter.GenerateAfterActivity(currentBlock, element);

            int startOfActivity = CodeWriter.GetIndexAfter("// Generated Activity", stringBuilder);
            stringBuilder.Insert(startOfActivity, activityBlock.ToString());


            #endregion

            #region Generate Destroy

            ICodeBlock destroySection = CodeWriter.GenerateDestroy(element);
            int startOfDestroySection = CodeWriter.GetIndexAfter("// Generated Destroy", stringBuilder);
            stringBuilder.Insert(startOfDestroySection, destroySection.ToString());

            #endregion


            #region Generate Methods

            ICodeBlock methodsSection = new CodeDocument(2);

            CodeWriter.GenerateMethods(methodsSection, element);

            int startOfMethodsSection = CodeWriter.GetIndexAfter("// Generated Methods", stringBuilder);
            stringBuilder.Insert(startOfMethodsSection, methodsSection.ToString());

            #endregion


            #region Extra Classes
            CodeBlockBase codeBlock = new CodeBlockBase(null);

            foreach (var codeGenerator in CodeGenerators)
            {
                codeGenerator.GenerateAdditionalClasses(codeBlock, element);
            }


            string extraClasses = codeBlock.ToString();

            if (!string.IsNullOrEmpty(extraClasses))
            {
                const string extraClassesComment = "// Extra classes";
                int indexToReplace = stringBuilder.LastIndexOf(extraClassesComment);

                stringBuilder.Remove(indexToReplace, extraClassesComment.Length);

                stringBuilder.Insert(indexToReplace, extraClasses);

            }
            #endregion

            string generatedCodeFileName = element.Name + ".Generated.cs";



            CodeWriter.SaveFileContents(stringBuilder.ToString(), FileManager.RelativeDirectory + generatedCodeFileName, true);


            #region Extra stuff if it's a ScreenSave

            if (element is ScreenSave)
            {
                bool inherits = !string.IsNullOrEmpty(element.BaseElement) && element.BaseElement != "<NONE>";
                if (inherits)
                {
                    #region Set the inheritance to the proper class

                    string fileContents;
                    string nameWithoutPath = FileManager.RemovePath(element.Name);

                    fileContents = FileManager.FromFileText(FileManager.RelativeDirectory + element.Name + ".Generated.cs");

                    #endregion

                    #region Replace the ContentManagerName

                    contentManagerName =
                        (element as ScreenSave).ContentManagerForCodeGeneration;

                    if (fileContents.Contains("base(" + contentManagerName + ")"))
                    {
                        // use the lower-case contentManagerName since that's the argument that's given to
                        // the base class' constructor.
                        fileContents = fileContents.Replace("base(" + contentManagerName + ")",
                            "base()");
                    }

                    #endregion

                    EliminateCall("\tInitialize();", ref fileContents);
                    EliminateCall(" Initialize();", ref fileContents);

                    CodeWriter.SaveFileContents(fileContents, FileManager.RelativeDirectory + element.Name + ".Generated.cs", true);
                }
            }

            #endregion

            #region Extra stuff if it's an EntitySave

            if (element is EntitySave)
            {
                EntitySave entitySave = element as EntitySave;

                string fileContents = stringBuilder.ToString();
                string fileName = FileManager.RelativeDirectory + element.Name + ".Generated.cs";
                bool shouldSave = false;

                #region Ok, the code is generated, but we may still need to give it a base class


                bool inherits;

                

                EntitySave rootEntitySave;
                List<string> inheritanceList = InheritanceCodeWriter.Self.GetInheritanceList(element, entitySave, out inherits, out rootEntitySave);
                InheritanceCodeWriter.Self.RemoveCallsForInheritance(entitySave, inherits, rootEntitySave, ref fileContents, ref shouldSave);

                #endregion

                #region If this thing is created by other entities, then we should make it IPoolable

                if (entitySave.CreatedByOtherEntities)
                {
                    FactoryCodeGenerator.UpdateFactoryClass(entitySave);
                }

                #endregion

                #region If this uses global content, then make it use global content regardless of what is passed in

                if (entitySave.UseGlobalContent)
                {
                    fileContents = fileContents.Replace("ContentManagerName = contentManagerName;", "ContentManagerName = FlatRedBall.FlatRedBallServices.GlobalContentManager;");
                    shouldSave = true;
                }

                #endregion


                #region If a change was made to the fileContents, let's save it

                if (shouldSave)
                {
                    bool tryAgain = true;

                    CodeWriter.SaveFileContents(fileContents, fileName, tryAgain);
                }

                #endregion
            }
            #endregion


        }
Пример #42
0
 private void SetEnvironment()
 {
   StringBuilder current = new StringBuilder(Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine));
   if (!current.Contains(FolderPath))
   {
     // Folder path always ends with \
     if (current[current.Length - 1] != ';')
       current.Append(';');
     current.Append(FolderPath);
     Environment.SetEnvironmentVariable("Path", current.ToString(), EnvironmentVariableTarget.Machine);
   }
 }
Пример #43
0
        public static string ClearComments(this string html)
        {
            html = html.CleanHeader();

            var starts = new List<int>();
            for (var i = 0; i < html.Length; i++)
            {
                if (i >= html.Length - 4)
                {
                    break;
                }

                i = html.IndexOf(@"<!--", i, StringComparison.Ordinal);
                if (i == -1)
                {
                    break;
                }
                starts.Add(i);
            }

            var ends = starts.Select(start => html.IndexOf(@"-->", start, StringComparison.Ordinal) + 3).ToList();

            var content = new StringBuilder(html).ToString(); 
            //Enable cleaning mso styling
            content = starts.Select((t, i) => html.Substring(t, ends[i] - t)).Aggregate(content, (current, comment) => current.Replace(comment, ""));

            content = content.Replace(@"<![if !vml]>", "");
            content = content.Replace(@"<![endif]>", "");




            content = content.Substring(content.IndexOf("<body"));
            content = content.Substring(content.IndexOf(">") + 1);
            content = content.Remove(content.LastIndexOf("</body>"), content.Length - content.LastIndexOf("</body>"));


            //deleting index from description
            if (content.Contains("<div style='mso-element:comment-list'>"))
            {
                content = content.Remove(content.IndexOf("<div style='mso-element:comment-list'>"));
            }

            for (int i = 0; ; i++)
            {
                if (!content.Contains(">["))
                {
                    break;
                }
                //content = content.Remove(content.IndexOf(">[")+1, 5);
                content = content.Remove(content.IndexOf(">[") + 1, (content.IndexOf("]</a>")+1) - (content.IndexOf(">[") + 1));
            }
            return content.Trim();

        }
Пример #44
0
        /// <summary>
        /// constructor, open template from file
        /// </summary>
        /// <param name="AFullPath"></param>
        public ProcessTemplate(string AFullPath = null)
        {
            if ((AFullPath == null) || (AFullPath.Length == 0))
            {
                return;
            }

            if (!File.Exists(AFullPath))
            {
                throw new Exception("Cannot find template file " + AFullPath + "; please adjust the TemplateDir parameter");
            }

            StreamReader r;
            r = File.OpenText(AFullPath);
            FTemplateCode = new StringBuilder();

            while (!r.EndOfStream)
            {
                string line = r.ReadLine().TrimEnd(new char[] { '\r', '\t', ' ', '\n' }).Replace("\t", "    ");
                FTemplateCode.Append(line).Append(Environment.NewLine);
            }

            r.Close();

            // add other files, {#INCLUDE <filename>}
            while (FTemplateCode.Contains("{#INCLUDE "))
            {
                Int32 pos = FTemplateCode.IndexOf("{#INCLUDE ");
                Int32 newLinePos = FTemplateCode.IndexOf(Environment.NewLine, pos);
                string line = FTemplateCode.Substring(pos, newLinePos - pos);
                Int32 bracketClosePos = FTemplateCode.IndexOf("}", pos);
                string filename = FTemplateCode.Substring(pos + "{#INCLUDE ".Length, bracketClosePos - pos - "{#INCLUDE ".Length).Trim();

                // do this recursively, to get snippets and code in the right place, even from the include files
                ProcessTemplate includedTemplate = new ProcessTemplate(Path.GetDirectoryName(AFullPath) + Path.DirectorySeparatorChar + filename);

                FTemplateCode = FTemplateCode.Replace(line, includedTemplate.FTemplateCode.ToString());

                foreach (string key in includedTemplate.FSnippets.Keys)
                {
                    FSnippets.Add(key, includedTemplate.FSnippets[key]);
                }
            }

            // split off snippets (identified by "{##")
            if (FTemplateCode.Contains("{##"))
            {
                StringCollection snippets = StringHelper.StrSplit(FTemplateCode.ToString(), "{##");

                // first part is the actual template code
                FTemplateCode = new StringBuilder(snippets[0]);

                for (int counter = 1; counter < snippets.Count; counter++)
                {
                    string snippetName = snippets[counter].Substring(0, snippets[counter].IndexOf("}"));

                    // exclude first newline
                    string snippetText = snippets[counter].Substring(snippets[counter].IndexOf(Environment.NewLine) + Environment.NewLine.Length);

                    // remove all whitespaces from the end, but keep one line ending for ENDIF etc
                    snippetText = snippetText.TrimEnd(new char[] { '\n', '\r', ' ', '\t' }) + Environment.NewLine;
                    FSnippets.Add(snippetName, snippetText);
                }
            }

            // just make sure that there is a newline at the end, for ENDIF etc
            FTemplateCode.Append(Environment.NewLine);
        }
Пример #45
-1
        public void ContainsTest()
        {
            StringBuilder builder = new StringBuilder("Now is the time for all good men to come to the aid of the party.");

            Assert.IsTrue(builder.Contains("Now is the"));
            Assert.IsTrue(builder.Contains("for all good men"));
            Assert.IsTrue(builder.Contains("aid of the party."));
            Assert.IsFalse(builder.Contains("Hello"));
        }
Пример #46
-1
        static void Main(string[] args)
        {
            StringBuilder str = new StringBuilder();
            str.Append("Hello_World !!!");
            Console.WriteLine("Index is at: " + str.IndexOf("World", 1));
            Console.WriteLine("Index is at: " + str.IndexOf("H"));
            Console.WriteLine("Index is at: " + str.IndexOf("e"));
            Console.WriteLine("Index is at: " + str.IndexOf("l"));
            Console.WriteLine("Index is at: " + str.IndexOf("l", 3));
            Console.WriteLine("Index is at: " + str.IndexOf("o"));
            Console.WriteLine("Index is at: " + str.IndexOf("W"));
            Console.WriteLine("Index is at: " + str.IndexOf("o"));
            Console.WriteLine("Index is at: " + str.IndexOf("r"));
            Console.WriteLine("Index is at: " + str.IndexOf("l"));
            Console.WriteLine("Index is at: " + str.IndexOf("d"));

            Console.WriteLine("Substring 5 to end: " + str.Substring(5));

            Console.WriteLine("Substring 1, length 1: " + str.Substring(1, 1));

            StringBuilder[] strs = str.Split(new String[] { " ", "_" });

            Console.WriteLine("Does string contain Hello? " + str.Contains("Hello"));

            Console.WriteLine("Does string end with !!!? " + str.EndsWith("!!!"));

            Console.WriteLine("Last index of !: " + str.LastIndexOf("!"));

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }