public void Process( XmlReader xmlReader, StringBuilder output, ElementProcessContext elementProcessContext) { if (elementProcessContext.Current.IsPreservingSpace) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if (elementProcessContext.Current.IsSignificantWhiteSpace && !output.IsNewLine()) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if ((elementProcessContext.Current.ContentType == ContentTypeEnum.None) && this.options.RemoveEndingTagOfEmptyElement) { // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if ((output[bracketIndex - 1] != '\t') && (output[bracketIndex - 1] != ' ') && this.options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } } else if ((elementProcessContext.Current.ContentType == ContentTypeEnum.SingleLineTextOnly) && !elementProcessContext.Current.IsMultlineStartTag) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring((bracketIndex + 1), (output.Length - bracketIndex - 1)).Trim(); output.Length = (bracketIndex + 1); output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = this.indentService.GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } elementProcessContext.Pop(); }
public void Process(XmlReader xmlReader, StringBuilder output, ElementProcessContext elementProcessContext) { if (elementProcessContext.Current.IsPreservingSpace) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if (elementProcessContext.Current.IsSignificantWhiteSpace && !output.IsNewLine()) { output.Append("</").Append(xmlReader.Name).Append(">"); } // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> else if (elementProcessContext.Current.ContentType == ContentTypeEnum.NONE && _options.RemoveEndingTagOfEmptyElement) { #region shrink element with no content output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if (output[bracketIndex - 1] != '\t' && output[bracketIndex - 1] != ' ' && _options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } #endregion shrink element with no content } else if (elementProcessContext.Current.ContentType == ContentTypeEnum.SINGLE_LINE_TEXT_ONLY && elementProcessContext.Current.IsMultlineStartTag == false) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring(bracketIndex + 1, output.Length - bracketIndex - 1).Trim(); output.Length = bracketIndex + 1; output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = _indentService.GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } elementProcessContext.Pop(); }
public static string GetContent(ApiRequest request, string configuration, TransformalizeResponse response) { var content = string.Empty; var results = string.Empty; var builder = new StringBuilder(); var processes = string.Empty; switch (request.RequestType) { case ApiRequestType.MetaData: builder.Append(configuration); builder.InsertFormat(builder.LastIndexOf('<'), RESPONSE_TEMPLATE, request.RequestType, request.Status, request.Message, request.Stopwatch.ElapsedMilliseconds, string.Empty, LogsToXml(response.Log), content); return builder.ToString(); case ApiRequestType.Configuration: builder.Append(configuration); builder.InsertFormat(builder.LastIndexOf('<'), MINIMAL_RESPONSE_TEMPLATE, request.RequestType, request.Status, request.Message, request.Stopwatch.ElapsedMilliseconds); return builder.ToString(); case ApiRequestType.Enqueue: builder.AppendFormat(XML_TEMPLATE, request.RequestType, request.Status, request.Message, request.Stopwatch.ElapsedMilliseconds, string.Empty, processes, results, LogsToXml(response.Log), content); return builder.ToString(); case ApiRequestType.Execute: switch (request.Flavor) { case "attributes": processes = SecureConfiguration(configuration); results = new XmlResultsToAttributesHandler().Handle(response.Processes); break; case "table": content = new XmlResultsToHtmlTable().Handle(response.Processes); break; default: processes = SecureConfiguration(configuration); results = new XmlResultsToDictionaryHandler().Handle(response.Processes); break; } builder.AppendFormat(XML_TEMPLATE, request.RequestType, request.Status, request.Message, request.Stopwatch.ElapsedMilliseconds, string.Empty, processes, results, LogsToXml(response.Log), content); return builder.ToString(); default: if (request.Status == 200) { request.Status = 400; request.Message = "Bad Request"; } builder.AppendFormat(XML_TEMPLATE, request.RequestType, request.Status, request.Message, request.Stopwatch.ElapsedMilliseconds, string.Empty, processes, results, LogsToXml(response.Log), content); return builder.ToString(); } }
public void ExtensionMethods_LastIndexOf_WhenNormalStringWithCaseIgnore_ExpectLastIndex() { //------------Setup for test-------------------------- StringBuilder value = new StringBuilder("aaa bbb aaa ccc ddd aaa eee BBB"); //------------Execute Test--------------------------- var result = value.LastIndexOf("bbb", true); //------------Assert Results------------------------- Assert.AreEqual(28, result); }
private void ProcessEndElement(XmlReader xmlReader, StringBuilder output) { if (this.ElementProcessStatusStack.Peek().IsPreservingSpace) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if (this.ElementProcessStatusStack.Peek().IsSignificantWhiteSpace && !output.IsNewLine()) { output.Append("</").Append(xmlReader.Name).Append(">"); } // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> else if ((ContentTypeEnum.None == this.ElementProcessStatusStack.Peek().ContentType) && Options.RemoveEndingTagOfEmptyElement) { #region shrink element with no content output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if ((output[bracketIndex - 1] != '\t') && (output[bracketIndex - 1] != ' ') && Options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } #endregion shrink element with no content } else if ((ContentTypeEnum.SingleLineTextOnly == this.ElementProcessStatusStack.Peek().ContentType) && !this.ElementProcessStatusStack.Peek().IsMultlineStartTag) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring(bracketIndex + 1, output.Length - bracketIndex - 1).Trim(); output.Length = bracketIndex + 1; output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = this.GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } }
private void ProcessEndElement(XmlReader xmlReader, StringBuilder output) { // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> if (ContentTypeEnum.NONE == _elementProcessStatusStack.Peek().ContentType && Options.RemoveEndingTagOfEmptyElement) { #region shrink element with no content output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if (output[bracketIndex - 1] != '\t' && output[bracketIndex - 1] != ' ' && Options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } #endregion shrink element with no content } else if (ContentTypeEnum.SINGLE_LINE_TEXT_ONLY == _elementProcessStatusStack.Peek().ContentType && false == _elementProcessStatusStack.Peek().IsMultlineStartTag) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring(bracketIndex + 1, output.Length - bracketIndex - 1).Trim(); output.Length = bracketIndex + 1; output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } }
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 }
/// <summary> /// To connect to the server. /// </summary> public void Connect() { _logReceiver.AddInfoLog("[{0}] Connecting...", Name); if (_socket != null) throw new InvalidOperationException(LocalizedStrings.Str2152); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _socket.Connect(Address); lock (_syncDisconnect) IsExportStarted = true; ThreadingHelper .Thread(() => { var buf = new StringBuilder(); var buffer = new byte[1024]; var isError = false; try { while (true) { if (_socket == null) throw new InvalidOperationException(LocalizedStrings.Str2153); if (_socket.Poll(500000, SelectMode.SelectRead)) { // http://stackoverflow.com/questions/2661764/how-to-check-if-a-socket-is-connected-disconnected-in-c if (_socket.Available == 0) throw new InvalidOperationException(LocalizedStrings.Str1611); var bytesRecv = _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); buf.Append(Encoding.ASCII.GetString(buffer, 0, bytesRecv)); var index = buf.LastIndexOf('\n'); if (index == -1) continue; var res = buf.ToString(0, index + 1); var reply = res.Split("\n").Select(v => v.TrimEnd('\r', '\n')); if (index < buf.Length - 1) buf.Remove(0, index + 1); else buf.Clear(); try { foreach (var line in reply) { _logReceiver.AddDebugLog("[{0}] Response: {1}", Name, line); ProcessReply.SafeInvoke(line); } } catch (Exception ex) { _logReceiver.AddErrorLog(ex); } } lock (_syncDisconnect) { if (IsExportStarted) continue; _logReceiver.AddInfoLog(LocalizedStrings.Str2154Params, Name); Monitor.Pulse(_syncDisconnect); break; } } } catch (ObjectDisposedException ex) { isError = true; ConnectionError.SafeInvoke(new InvalidOperationException(LocalizedStrings.Str2155, ex)); } catch (Exception ex) { isError = true; ConnectionError.SafeInvoke(ex); } if (isError) { lock (_syncDisconnect) IsExportStarted = false; } try { _socket.Shutdown(SocketShutdown.Both); } catch (Exception ex) { _logReceiver.AddErrorLog(ex); } _socket.Close(); _socket = null; _logReceiver.AddInfoLog(LocalizedStrings.Str2156Params, Name); }) .Name("IQFeed '{0}' thread".Put(Name)) .Culture(CultureInfo.InvariantCulture) .Start(); Request("S,SET PROTOCOL,5.1"); _logReceiver.AddInfoLog("[{0}] Connected", Name); } catch { _socket.Close(); _socket = null; throw; } }
public void TestInsertAt() { var sb = new StringBuilder("<strong>emphasis</strong>"); var index = sb.LastIndexOf('<'); sb.Insert(index, "!!!"); Assert.AreEqual("<strong>emphasis!!!</strong>", sb.ToString()); }
public void TestInsertFormat() { var sb = new StringBuilder("<strong>emphasis</strong>"); sb.InsertFormat(sb.LastIndexOf('<')," and other {0}.", "things"); Assert.AreEqual("<strong>emphasis and other things.</strong>", sb.ToString()); }
public void TestLastIndexOfNotThere() { var sb = new StringBuilder("<strong>emphasis</strong>"); Assert.AreEqual(-1, sb.LastIndexOf('!')); }
public void TestLastIndexOf() { var sb = new StringBuilder("<strong>emphasis</strong>"); Assert.AreEqual(16, sb.LastIndexOf('<')); }
public void IndexTest() { StringBuilder str = new StringBuilder("Hello"); Assert.AreEqual(1, str.IndexOf("el")); Assert.AreEqual(3, str.LastIndexOf("l")); }
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(); }
public void ExtensionMethods_LastIndexOf_WhenNormalStringInMiddle_ExpectLastIndex() { //------------Setup for test-------------------------- StringBuilder value = new StringBuilder("aaa bbb aaa ccc ddd aaa eee bbb"); //------------Execute Test--------------------------- var result = value.LastIndexOf("ccc", false); //------------Assert Results------------------------- Assert.AreEqual(12, result); }
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(); }