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;
        }
Example #3
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);
   }
 }
Example #4
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 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_SubStringInMiddle()
	{
		StringBuilder builder = new StringBuilder();
		builder.Append("bcdef");
		string subString = "cde";
		bool doesContain = builder.Contains(subString);
		Assert.IsTrue(doesContain);
	}
	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_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);
		}
	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_SubStringEmpty()
	{
		StringBuilder builder = new StringBuilder();
		string subString = null;
		bool doesContain = builder.Contains(subString);
		Assert.IsFalse(doesContain);
	}
Example #11
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());
            }
        }
Example #12
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


        }
        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;
        }
        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;
        }
Example #15
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();

        }
        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();
        }