Write() public méthode

public Write ( bool value ) : void
value bool
Résultat void
Exemple #1
0
	/**
	 * Prettyprint the object to the outputstream.
	 */
	public static void print(object o, TextWriter w, bool typeheader) {
		if (o == null) {
			if(typeheader) w.WriteLine("null object");
			w.WriteLine("null");
			w.Flush();
			return;
		}

		if (o is IDictionary) {
			if(typeheader) w.WriteLine("hashtable");
			IDictionary map=(IDictionary)o;
			w.Write("{");
			foreach(object key in map.Keys) {
				w.Write(key.ToString()+"="+map[key].ToString()+", ");
			}
			w.WriteLine("}");
		} else if (o is string) {
			if(typeheader) w.WriteLine("String");
			w.WriteLine(o.ToString());
		} else if (o is DateTime) {
			if(typeheader) w.WriteLine("DateTime");
			w.WriteLine((DateTime)o);
		} else if (o is IEnumerable) {
			if(typeheader) w.WriteLine(o.GetType().Name);
			writeEnumerable(o, w);
			w.WriteLine("");
		} else {
			if(typeheader) w.WriteLine(o.GetType().Name);
			w.WriteLine(o.ToString());
		}
		
		w.Flush();
	}
        /// <summary></summary>
        public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer)
        {
            if (obj == null)
            {
                return;
            }

            var objAsString = obj as string;
            if (obj is string)
            {
                writer.Write(objAsString);
                return;
            }

            if (obj is LazyString)
            {
                writer.Write(obj.ToString());
                return;
            }

            var ns = obj.GetType().Namespace;
            if (!string.IsNullOrEmpty(ns) && (ns.StartsWith("log4net") || ns.StartsWith("Common.Logging")))
            {
                //if we get a log4net object, log4net will expect us to call ToString to get the format
                writer.Write(obj.ToString());
                return;
            }

            obj.DumpTo(writer);
        }
        public void ValidateFile(Stream stream, TextWriter outstream, Action<int> progress, Action<string> status)
        {
            try {
                MZTabErrorList errorList = new MZTabErrorList(Level.Info);

                try {
                    validate(stream, outstream, errorList, progress, status);
                    //refine();
                } catch (MZTabException e) {
                    outstream.Write(MZTabProperties.MZTabExceptionMessage);
                    errorList.Add(e.Error);
                } catch (MZTabErrorOverflowException) {
                    outstream.Write(MZTabProperties.MZTabErrorOverflowExceptionMessage);
                }

                errorList.print(outstream);
                if (errorList.IsNullOrEmpty()) {
                    outstream.Write("No errors in this section!" + MZTabConstants.NEW_LINE);
                }

                outstream.Close();
                //stream.Close();
            } catch (Exception e) {
                MessageBox.Show(e.Message, e.StackTrace);
            }
        }
		/// <summary>
		/// Describes this object.
		/// </summary>
		/// <param name="writer">The text writer the description is added to.</param>
		void ISelfDescribing.DescribeTo(TextWriter writer)
		{
			writer.Write("set ");
			writer.Write(name);
			writer.Write("=");
			writer.Write(value);
		}
		/// <summary>
		/// Write the current thread identity to the output
		/// </summary>
		/// <param name="writer">the writer to write to</param>
		/// <param name="state">null, state is not set</param>
		/// <remarks>
		/// <para>
		/// Writes the current thread identity to the output <paramref name="writer"/>.
		/// </para>
		/// </remarks>
		override protected void Convert(TextWriter writer, object state) 
		{
#if (NETCF || SSCLI)
			// On compact framework there's no notion of current thread principals
			writer.Write( SystemInfo.NotAvailableText );
#else
			try
			{
				if (System.Threading.Thread.CurrentPrincipal != null && 
					System.Threading.Thread.CurrentPrincipal.Identity != null &&
					System.Threading.Thread.CurrentPrincipal.Identity.Name != null)
				{
					writer.Write( System.Threading.Thread.CurrentPrincipal.Identity.Name );
				}
			}
			catch(System.Security.SecurityException)
			{
				// This security exception will occur if the caller does not have 
				// some undefined set of SecurityPermission flags.
				LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored.");

				writer.Write( SystemInfo.NotAvailableText );
			}
#endif
		}
Exemple #6
0
        /// <summary>
        /// Write the DataTable to a TextWriter stream.
        /// </summary>
        /// <param name="stream">A TextWriter stream to write the values to.</param>
        /// <param name="table">The source DataTable with the values.</param>
        /// <param name="header">True if including a header row with the column names.</param>
        /// <param name="quoteall">True if quoting all values.</param>
        public static void WriteToStream(TextWriter stream, DataTable table, bool header, bool quoteall)
        {
            if (header)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    WriteItem(stream, table.Columns[i].Caption, quoteall);
                    if (i < table.Columns.Count - 1)
                        stream.Write(',');
                    else
                        stream.Write(Environment.NewLine);
                }
            }

            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    WriteItem(stream, row[i], quoteall);
                    if (i < table.Columns.Count - 1)
                        stream.Write(',');
                    else
                        stream.Write(Environment.NewLine);
                }
            }
        }
Exemple #7
0
		/// <summary>
		/// Describes this matcher.
		/// </summary>
		/// <param name="writer">The text writer the description is added to.</param>
		public virtual void DescribeTo(TextWriter writer)
		{
			if(Description == null)
				writer.Write("[" + GetType().Name + "]");
			else if(!Description.Equals(string.Empty))
				writer.Write(Description);
		}
        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            var text = GetFullyQualifiedName(loggingEvent);

            if (m_precision == 0 || text == null || text.Length < 2)
            {
                writer.Write(text);
                return;
            }

            var elements = text
                .Trim()
                .Trim(new[] { '.' })
                .Split(new[] { '.' });

            if (m_precision > 0)
            {
                writer.Write(
                    string.Join("/",
                                elements
                                    .Reverse()
                                    .Take(m_precision)
                                    .Reverse()
                        )
                    );
                return;
            }

            writer.Write(
                string.Join("/",
                            elements
                                .Take(elements.Count() + m_precision)
                    )
                );
        }
Exemple #9
0
        static void GenerateDummies(TextWriter @out)
        {
            @out.Write(@"
            namespace Dummies {

            #region Interfaces

            ");
            string dummyFace = " interface IDummy{0} : IDummy {{ void DoMore(); }}\r\n";
            string dummyBody = @"
            public class SimpleDummy{0} : IDummy{1} {{
            public SimpleDummy{0}() {{}}
            public void Do() {{}}
            public void DoMore() {{}}
            }}
            ";
            for (var i = 0; i < NUM_I; i++) {
                @out.Write(dummyFace, i);
            }

            @out.Write(@"
            #endregion
            #region Implementation\r\n");
            int K = NUM_I * K_TO_I;
            for (var k = 0; k < K ; k++) {
                int i = k / K_TO_I;
                @out.Write(dummyBody, k, i);
            }

            @out.Write(@"
            #endregion
            }");
        }
        public void Write(string parsedSourceCode,
            IList<Scope> scopes,
            IStyleSheet styleSheet,
            TextWriter textWriter)
        {
            var styleInsertions = new List<TextInsertion>();

            foreach (Scope scope in scopes)
                GetStyleInsertionsForCapturedStyle(scope, styleInsertions);

            styleInsertions.SortStable((x, y) => x.Index.CompareTo(y.Index));

            int offset = 0;

            foreach (TextInsertion styleInsertion in styleInsertions)
            {
                textWriter.Write(HttpUtility.HtmlEncode(parsedSourceCode.Substring(offset, styleInsertion.Index - offset)));
                if (string.IsNullOrEmpty(styleInsertion.Text))
                    BuildSpanForCapturedStyle(styleInsertion.Scope, styleSheet, textWriter);
                else
                    textWriter.Write(styleInsertion.Text);
                offset = styleInsertion.Index;
            }

            textWriter.Write(HttpUtility.HtmlEncode(parsedSourceCode.Substring(offset)));
        }
Exemple #11
0
        /// <summary>
        /// Entry point to the encoder.
        /// </summary>
        public void Encode(char[] value, int startIndex, int characterCount, TextWriter output)
        {
            // Input checking
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }
            ValidateInputs(startIndex, characterCount, actualInputLength: value.Length);

            if (characterCount != 0)
            {
                fixed (char* pChars = value)
                {
                    int indexOfFirstCharWhichRequiresEncoding = GetIndexOfFirstCharWhichRequiresEncoding(&pChars[startIndex], characterCount);
                    if (indexOfFirstCharWhichRequiresEncoding < 0)
                    {
                        // All chars are valid - just copy the buffer as-is.
                        output.Write(value, startIndex, characterCount);
                    }
                    else
                    {
                        // Flush all chars which are known to be valid, then encode the remainder individually
                        if (indexOfFirstCharWhichRequiresEncoding > 0)
                        {
                            output.Write(value, startIndex, indexOfFirstCharWhichRequiresEncoding);
                        }
                        EncodeCore(&pChars[startIndex + indexOfFirstCharWhichRequiresEncoding], (uint)(characterCount - indexOfFirstCharWhichRequiresEncoding), output);
                    }
                }
            }
        }
Exemple #12
0
 public void Write(TextWriter writer)
 {
     writer.Write("{0} ", Address.ToLinear());
     bool inString = false;
     for (int i = 0; i < Line.Length; ++i)
     {
         int b = Line[i];
         if (inString)
         {
             writer.Write(Encoding.UTF8.GetString(Line, i, 1));
             inString = (b != 0x22);
         }
         else
         {
             if (TokenMin <= b && b < TokenMax)
             {
                 writer.Write(TokenStrs[b - TokenMin]);
             }
             else
             {
                 writer.Write(Encoding.UTF8.GetString(Line, i, 1));
             }
             inString = (b == 0x22);
         }
     }
     writer.WriteLine();
 }
Exemple #13
0
        void WriteActionSignature(IBAction action, System.IO.TextWriter writer)
        {
            writer.Write("- (IBAction){0}", action.ObjCName);
            bool isFirst = true;

            foreach (var param in action.Parameters)
            {
                string paramType = param.ObjCType;
                if (isFirst && paramType == "NSObject")
                {
                    paramType = "id";
                }
                else
                {
                    paramType = paramType + " *";
                }

                if (isFirst)
                {
                    isFirst = false;
                    writer.Write(":({0}){1}", paramType, param.Name);
                }
                else
                {
                    writer.Write(" {0}:({1}){2}", param.Label, paramType, param.Name);
                }
            }
        }
Exemple #14
0
		/// <summary>
		/// Describes this matcher.
		/// </summary>
		/// <param name="writer">The text writer to which the description is added.</param>
		public override void DescribeTo(TextWriter writer)
		{
			if (_o == null)
				writer.Write("Object in ObjectMatcher is null.");
			else
				writer.Write(_o.ToString());
		}
Exemple #15
0
        public override void Execute(TextWriter outputWriter)
        {
            if(!FileSystem.DirectoryExists(Options.ScriptDirectory))
            {
                outputWriter.WriteLine(string.Format("The script directory {0} doesn't exist.  Have you created any migrations yet?",
                    Options.ScriptDirectory));

                outputWriter.WriteLine("You can change this directory by providing the --scriptsdir option");
                return;
            }

            int? migration = Database.CurrentMigration();

            outputWriter.WriteLine("Migrations");
            outputWriter.WriteLine("----------------------------");
            var files = FileSystem.GetFilesInDirectory(Options.ScriptDirectory, "*.boo");

            foreach (var file in files)
            {
                outputWriter.Write("\t");
                if (IsCurrentMigration(file, migration))
                    outputWriter.Write("=> ");
                else
                    outputWriter.Write("   ");

                outputWriter.WriteLine(file);
            }

            outputWriter.WriteLine();
            outputWriter.WriteLine("Total migrations: " + files.Length);
        }
        /// <summary>
        /// Writes the answer collection as a HotDocs XML answer file to the TextWriter.
        /// </summary>
        /// <param name="output">The TextWriter to which to write the XML answer file.</param>
        /// <param name="writeDontSave">Indicates whether or not answers that are marked as "do not save" should be written to the answer file.</param>
        public void WriteXml(System.IO.TextWriter output, bool writeDontSave)
        {
            output.Write("<?xml version=\"1.0\" encoding=\"");
            output.Write(output.Encoding.WebName);            //Write out the IANA-registered name of the encoding.
            output.WriteLine("\" standalone=\"yes\"?>");
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent             = true;
            settings.IndentChars        = "\t";
            settings.OmitXmlDeclaration = true;             // because we emitted it manually above
            bool forInterview = true;

            using (XmlWriter writer = new AnswerXmlWriter(output, settings, forInterview))
            {
                writer.WriteStartDocument(true);
                writer.WriteStartElement("AnswerSet");
                writer.WriteAttributeString("title", _title);
                writer.WriteAttributeString("version", XmlConvert.ToString(_version));
                //writer.WriteAttributeString("useMangledNames", XmlConvert.ToString(false));
                foreach (Answer ans in _answers.Values)
                {
                    ans.WriteXml(writer, writeDontSave);
                }
                writer.WriteEndElement();
            }
        }
Exemple #17
0
        /// <summary>
        /// Writes the answer collection as a HotDocs XML answer file to the TextWriter.
        /// </summary>
        /// <param name="output">The TextWriter to which to write the XML answer file.</param>
        /// <param name="writeDontSave">Indicates whether or not answers that are marked as "do not save" should be written to the answer file.</param>
        public void WriteXml(System.IO.TextWriter output, bool writeDontSave)
        {
            output.Write("<?xml version=\"1.0\" encoding=\"");
            output.Write(output.Encoding.WebName);            //Write out the IANA-registered name of the encoding.
            output.WriteLine("\" standalone=\"yes\"?>");
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent             = true;
            settings.IndentChars        = "\t";
            settings.OmitXmlDeclaration = true;   // because we emitted it manually above
            bool forInterview = true;             // ensures the userModifiable and userExtendible attributes are output

            using (XmlWriter writer = new AnswerXmlWriter(output, settings, forInterview))
            {
                writer.WriteStartDocument(true);
                if (!String.IsNullOrEmpty(_dtd))
                {
                    writer.WriteRaw(_dtd);
                }
                writer.WriteStartElement("AnswerSet");
                writer.WriteAttributeString("title", _title);
                writer.WriteAttributeString("version", XmlConvert.ToString(_version));
                //writer.WriteAttributeString("useMangledNames", XmlConvert.ToString(false));
                IEnumerator <Answer> answerEnumerator = GetEnumerator();
                while (answerEnumerator.MoveNext())
                {
                    answerEnumerator.Current.WriteXml(writer, writeDontSave);
                }
                writer.WriteEndElement();
            }
        }
        public override void Render(TextWriter writer)
        {
            if (state == ControlPanelState.DragDrop)
            {
                if (ZoneName.IndexOfAny(new[] { '.', ',', ' ', '\'', '"', '\t', '\r', '\n' }) >= 0) throw new N2Exception("Zone '" + ZoneName + "' contains illegal characters.");

                writer.Write("<div class='" + ZoneName + " dropZone'");
                writer.WriteAttribute(PartUtilities.PathAttribute, CurrentItem.Path)
                    .WriteAttribute(PartUtilities.ZoneAttribute, ZoneName)
                    .WriteAttribute(PartUtilities.AllowedAttribute, PartUtilities.GetAllowedNames(ZoneName, PartsAdapter.GetAllowedDefinitions(CurrentItem, ZoneName, Html.ViewContext.HttpContext.User)))
                    .WriteAttribute("title", ZoneTitle ?? DroppableZone.GetToolTip(Html.ResolveService<IDefinitionManager>().GetDefinition(CurrentItem), ZoneName))
                    .Write(">");

                if (string.IsNullOrEmpty(Html.ViewContext.HttpContext.Request["preview"]))
                {
                    base.Render(writer);
                }
                else
                {
                    string preview = Html.ViewContext.HttpContext.Request["preview"];
                    RenderReplacingPreviewed(writer, preview);
                }

                writer.Write("</div>");
            }
            else
                base.Render(writer);
        }
 public override void GetPacketDataString(TextWriter text, bool flagsDescription)
 {
     text.Write("regionIndex:0x{0:X2} region:{1,-3} serverIp:\"{2}\" portFrom:{3} portTo:{4}",
          regionIndex, region, serverIp, portFrom, portTo);
     if (flagsDescription)
         text.Write(" zoneInfo:\"{0}\"", zoneInfo);
 }
		private void DumpNode(HuffmanNode node,string tag, int i, TextWriter writer)
		{
			for (int j = 0; j < i; j++)
			{
				writer.Write("    ");
			}
			writer.Write('-');

			if (node.IsBranch)
				writer.Write(" {0} '{2}' x {1:4} = ", tag, node.Freq, (char)node.Symbol);
			else
				writer.Write(" {1} Freq {0} = ", node.Freq, tag);

			if (node.IsBranch == false)
			{
				foreach (var bit in node.Bits)
				{
					writer.Write(bit ? "1" : "0");
				}
			}

			writer.WriteLine();

			if (node.IsBranch == false)
				return;
			DumpNode(node.Left, "left", i+1, writer);
			DumpNode(node.Right, "right", i + 1, writer);
		}
        void WriteActionSignature(IBAction action, System.IO.TextWriter writer)
        {
            writer.Write("- (IBAction){0}", action.ObjCName);
            bool isFirst = true;

            foreach (var param in action.Parameters)
            {
                string paramType = param.ObjCType;
                if (paramType == null)
                {
                    throw new ObjectiveCGenerationException(string.Format(
                                                                "Could not generate Obj-C code for action '{0}' in class '{1}' as the type '{2}'" +
                                                                "of its parameter '{3}' could not be resolved to Obj-C",
                                                                action.CliName, this.CliName, param.CliType, param.Name), this);
                }
                if (isFirst && paramType == "NSObject")
                {
                    paramType = "id";
                }
                else
                {
                    paramType = paramType + " *";
                }

                if (isFirst)
                {
                    isFirst = false;
                    writer.Write(":({0}){1}", paramType, param.Name);
                }
                else
                {
                    writer.Write(" {0}:({1}){2}", param.Label, paramType, param.Name);
                }
            }
        }
Exemple #22
0
        public void DebugDump(TextWriter writer, Story story)
        {
            if (Name.Length > 0)
            {
                if (Negate) writer.Write("!");
                writer.Write("{0}(", Name);
                if (Parameters != null)
                {
                    for (var i = 0; i < Parameters.Count; i++)
                    {
                        Parameters[i].DebugDump(writer, story);
                        if (i < Parameters.Count - 1) writer.Write(", ");
                    }
                }

                writer.Write(") ");
            }

            if (GoalIdOrDebugHook != 0)
            {
                if (GoalIdOrDebugHook < 0)
                {
                    writer.Write("<Debug hook #{0}>", -GoalIdOrDebugHook);
                }
                else
                {
                    var goal = story.Goals[(uint)GoalIdOrDebugHook];
                    writer.Write("<Complete goal #{0} {1}>", GoalIdOrDebugHook, goal.Name);
                }
            }
        }
Exemple #23
0
		public static void Serialize(bool value, TextWriter sw)
		{
			if (value)
				sw.Write("true");
			else
				sw.Write("false");
		}
        private void RenderExceptionData(RendererMap rendererMap, Exception ex, TextWriter writer, int depthLevel)
        {
            var dataCount = ex.Data.Count;
            if (dataCount == 0)
            {
                return;
            }

            writer.WriteLine();

            writer.WriteLine($"Exception data on level {depthLevel} ({dataCount} items):");

            var currentElement = 0;
            foreach (DictionaryEntry entry in ex.Data)
            {
                currentElement++;

                writer.Write("[");
                ExceptionObjectLogger.RenderValue(rendererMap, writer, entry.Key);
                writer.Write("]: ");

                ExceptionObjectLogger.RenderValue(rendererMap, writer, entry.Value);

                if (currentElement < dataCount)
                {
                    writer.WriteLine();
                }
            }
        }
		protected virtual void WriteConstraint(RouteConstraintDefinition constraint, TextWriter output)
		{
			output.Write(@"""");
			output.Write(constraint.ParameterName);
			output.Write(@""":");
			output.Write(constraint.GetExpression());
		}
		/// <summary>
		/// Describes this object.
		/// </summary>
		/// <param name="writer">The text writer the description is added to.</param>
		void ISelfDescribing.DescribeTo(TextWriter writer)
		{
			writer.Write("set arg ");
			writer.Write(index);
			writer.Write("=");
			writer.Write(value);
		}
Exemple #27
0
        public void ToSqlInsert(TextWriter writer)
        {
            foreach (var id in _comments.Keys)
                writer.Write("-- {0} => {1}{2}", id, _comments[id], Environment.NewLine);

            writer.WriteLine();
            writer.Write("insert into conditions values");

            var last = _conditions.Last();

            var conditions = from c1 in _conditions
                             from c2 in c1.Conditions
                             select c2;

            foreach (var condition in conditions)
            {
                writer.Write(
                    "{0}  {1}{2}",
                    Environment.NewLine,
                    condition.ToString(),
                    condition == last ? ";" : ",");
            }

            writer.WriteLine();
            writer.Flush();
        }
Exemple #28
0
        public void writeCSV(System.IO.TextWriter tw)
        {
            // Writes a CSV (comma-separated values) file which can be read by Excel.

            bool first = true;

            foreach (string h in _headers)
            {
                if (!first)
                {
                    tw.Write(",");
                }
                first = false;
                tw.Write(h);
            }
            tw.WriteLine();

            foreach (string[] result in _results)
            {
                first = true;
                foreach (string value in result)
                {
                    if (!first)
                    {
                        tw.Write(",");
                    }
                    first = false;
                    tw.Write(value);
                }
                tw.WriteLine();
            }
        }
Exemple #29
0
 public static void WriteToStream(TextWriter stream, DataTable table, bool header, bool quoteall)
 {
     if (header)
     {
         for (int i = 0; i < table.Columns.Count; i++)
         {
             WriteItem(stream, table.Columns[i].Caption, quoteall);
             if (i < table.Columns.Count - 1)
                 stream.Write(',');
             else
                 stream.Write("\r\n");
         }
     }
     foreach (DataRow row in table.Rows)
     {
         for (int i = 0; i < table.Columns.Count; i++)
         {
             WriteItem(stream, row[i], quoteall);
             if (i < table.Columns.Count - 1)
                 stream.Write(',');
             else
                 stream.Write("\r\n");
         }
     }
     stream.Flush();
     stream.Close();
 }
Exemple #30
0
		static void PrintMethodAllocationsPerClass (TextWriter writer, LoadedClass.AllocationsPerMethod allocationsPerMethod, bool JitTime, bool printStackTraces, double stackTraceTreshold) {
			if (! JitTime) {
				writer.WriteLine ("        {0} bytes ({1} instances) from {2}.{3}", allocationsPerMethod.AllocatedBytes, allocationsPerMethod.AllocatedInstances, allocationsPerMethod.Method.Class.Name, allocationsPerMethod.Method.Name);
			} else {
				writer.WriteLine ("                {0} bytes ({1} instances) at JIT time in {2}.{3}", allocationsPerMethod.AllocatedBytes, allocationsPerMethod.AllocatedInstances, allocationsPerMethod.Method.Class.Name, allocationsPerMethod.Method.Name);
			}
			
			if (printStackTraces) {
				LoadedClass.AllocationsPerStackTrace [] stackTraces = allocationsPerMethod.StackTraces;
				Array.Sort (stackTraces, LoadedClass.AllocationsPerStackTrace.CompareByAllocatedBytes);
				Array.Reverse (stackTraces);
				double cumulativeAllocatedBytesPerStackTrace = 0;
				
				foreach (LoadedClass.AllocationsPerStackTrace trace in stackTraces) {
					if (cumulativeAllocatedBytesPerStackTrace / allocationsPerMethod.AllocatedBytes < stackTraceTreshold) {
						writer.WriteLine ("                {0} bytes ({1} instances) inside", trace.AllocatedBytes, trace.AllocatedInstances);
						for (StackTrace frame = trace.Trace; frame != null; frame = frame.Caller) {
							writer.Write ("                        ");
							if (frame.MethodIsBeingJitted) {
								writer.Write ("[JIT time]:");
							}
							writer.WriteLine ("{0}.{1}", frame.TopMethod.Class.Name, frame.TopMethod.Name);
						}
					} else {
						break;
					}
					cumulativeAllocatedBytesPerStackTrace += (double)trace.AllocatedBytes;
				}
			}
		}
Exemple #31
0
        internal static void WriteUlongAsHexToBuffer(ulong value, TextWriter textWriter)
        {
            // This tracks the length of the output and serves as the index for the next character to be written into the pBuffer.
            // The length could reach up to 16 characters, so at least that much space should remain in the pBuffer.
            int length = 0;

            // Write the hex value from left to right into the buffer without zero padding.
            for (int i = 0; i < 16; i++)
            {
                // Convert the first 4 bits of the value to a valid hex character.
                char hexChar = Int32ToHex((int)(value >> 60));
                value <<= 4;

                // Don't increment length if it would just add zero padding
                if (length != 0 || hexChar != '0')
                {
                    textWriter.Write(hexChar);
                    length++;
                }
            }

            if (length == 0)
            {
                textWriter.Write('0');
            }
        }
Exemple #32
0
 public void Source(ISetting setting, TextWriter output)
 {
     output.Write (setting.BlockBegin);
     output.Write ("dump ");
     output.Write (this.expression);
     output.Write (setting.BlockEnd);
 }
Exemple #33
0
 public static void ShowBlinkingDots(CancellationToken ct, TextWriter consoleOut, byte count = 9, 
     int msTimeout = 10)
 {
     if (consoleOut == null)
     {
         throw new ArgumentNullException("consoleOut", ConsoleTextMessages.NullArgument);
     }
     byte i;
     var sb = new StringBuilder(count);
     string empty;
     for (i = 0; i < count; ++i)
     {
         sb.Append(" ");
     }
     empty = sb.ToString();
     while (!ct.IsCancellationRequested)
     {
         for (i = 0; i < count; ++i)
         {
             consoleOut.Write(".");
             Thread.Sleep(msTimeout);
         }
         consoleOut.Write("\r" + empty + "\r");
     }
     consoleOut.WriteLine("\n");
 }
        ///<summary>Print a hex dump of the supplied bytes to the supplied TextWriter.</summary>
        public static void Dump(byte[] bytes, TextWriter writer)
        {
            int rowlen = 16;

            for (int count = 0; count < bytes.Length; count += rowlen) {
                int thisRow = Math.Min(bytes.Length - count, rowlen);

                writer.Write(String.Format("{0:X8}: ", count));
                for (int i = 0; i < thisRow; i++) {
                    writer.Write(String.Format("{0:X2}", bytes[count + i]));
                }
                for (int i = 0; i < (rowlen - thisRow); i++) {
                    writer.Write("  ");
                }
                writer.Write("  ");
                for (int i = 0; i < thisRow; i++) {
                    if (bytes[count + i] >= 32 &&
                        bytes[count + i] < 128)
                        {
                            writer.Write((char) bytes[count + i]);
                        } else {
                            writer.Write('.');
                        }
                }
                writer.WriteLine();
            }
            if (bytes.Length % 16 != 0) {
                writer.WriteLine(String.Format("{0:X8}: ", bytes.Length));
            }
        }
Exemple #35
0
		public override void Format(TextWriter writer, LoggingEvent loggingEvent) {
			// check arguments
			if (loggingEvent == null) return;
			if (loggingEvent.MessageObject == null && loggingEvent.RenderedMessage == null) return;

			// get logger id
			string loggerId = loggingEvent.GetLoggingEventProperty("__objectId");

			// prepare stuff
			string message = loggingEvent.MessageObject == null ? loggingEvent.RenderedMessage : loggingEvent.MessageObject.ToString();
			string info = loggingEvent.GetLoggingEventProperty("__extendedInfo");
			if (info != null) {
				message = message + " " + info;
			}
			string[] lines = message.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
			string header = string.Format("{0} [{1}] ({3}|{4}|{5}) {2} : ", loggingEvent.TimeStamp.ToString("dd-MM-yyyy hh:mm:ss,fff"), loggingEvent.Level.DisplayName.PadLeft(5, ' '), this.LoggerName(loggingEvent.LoggerName), Thread.CurrentThread.GetHashCode().ToString(CultureInfo.InvariantCulture).PadLeft(2, ' '), loggerId.PadLeft(2), Thread.CurrentPrincipal != null ? Thread.CurrentPrincipal.Identity.Name : "unknown");
			const string FILLER = "\t";

			for (int i = 0; i < lines.Length; i++) {
				if (i == 0) {
					writer.Write(header);
				} else {
					writer.Write(FILLER);
				}
				writer.WriteLine(lines[i]);
			}
		}
Exemple #36
0
        public static void ReadProject(string project, Dictionary <string, string> files, System.IO.TextWriter logger)
        {
            var direc = System.IO.Path.GetDirectoryName(project);

            foreach (var line in DeepEnds.Core.Utilities.ReadFile(project).Split('\n'))
            {
                var trimmed = line.Trim();

                if (trimmed.Length < 8)
                {
                    continue;
                }

                if (trimmed.Substring(0, 8) != "<Compile")
                {
                    continue;
                }

                trimmed = trimmed.Substring(trimmed.IndexOf('"') + 1);
                trimmed = trimmed.Substring(0, trimmed.IndexOf('"'));
                var file = System.IO.Path.Combine(direc, trimmed);
                if (!System.IO.File.Exists(file))
                {
                    logger.Write("! Cannot find ");
                    logger.WriteLine(file);
                    continue;
                }

                logger.Write("  Appended ");
                logger.WriteLine(file);
                files[file] = project;
            }
        }
Exemple #37
0
 private static void EmitRegistersCore(IEnumerable <Storage> regs, TextWriter sb)
 {
     foreach (var reg in regs.Where(r => r != null).OrderBy(r => r.Name))
     {
         sb.Write(" ");
         sb.Write(reg.Name);
     }
 }
Exemple #38
0
 public static void EmitRegisterValues <TValue>(string caption, Dictionary <Storage, TValue> symbols, TextWriter sb)
 {
     sb.Write(caption);
     foreach (var de in symbols.OrderBy(de => de.Key.ToString()))
     {
         sb.Write(" {0}:{1}", de.Key, de.Value);
     }
 }
Exemple #39
0
        private static void PrintShaderProperty(string property, Material material, System.IO.TextWriter textWriter)
        {
            textWriter.Write("Has ");
            textWriter.Write(property);
            textWriter.Write(" = ");

            bool hasProperty = material.HasProperty(property);

            textWriter.WriteLine(hasProperty);
        }
Exemple #40
0
 public void EmitFlagGroup(IProcessorArchitecture arch, string caption, Dictionary <RegisterStorage, uint> flagRegs, TextWriter sb)
 {
     sb.Write(caption);
     foreach (var freg in flagRegs
              .Select(f => arch.GetFlagGroup(f.Key, f.Value) !)
              .OrderBy(f => f.Name))
     {
         sb.Write(" {0}", freg.Name);
     }
 }
Exemple #41
0
 public override void WriteId(System.IO.TextWriter trapFile)
 {
     trapFile.Write(assembly.ToString());
     if (!(assemblyPath is null))
     {
         trapFile.Write("#file:///");
         trapFile.Write(assemblyPath.Replace("\\", "/"));
     }
     trapFile.Write(";assembly");
 }
Exemple #42
0
        /// <summary>
        /// Constructs a unique string for this label.
        /// </summary>
        /// <param name="trapFile">The trap builder used to store the result.</param>
        public void AppendTo(System.IO.TextWriter trapFile)
        {
            if (!Valid)
            {
                throw new NullReferenceException("Attempt to use an invalid label");
            }

            trapFile.Write('#');
            trapFile.Write(Value);
        }
Exemple #43
0
 private void writeJson(System.IO.TextWriter textWriter, IList <UserSummary> summaries)
 {
     textWriter.Write("[");
     foreach (UserSummary user in summaries)
     {
         textWriter.Write("{3}Rank:{0}, Reputation:{1}, Name:'{2}'{4},", user.Rank, user.Reputation, user.Name.Replace("\\", "\\\\").Replace("'", "\\'"), "{", "}");
     }
     textWriter.Write("]");
     textWriter.Flush();
 }
Exemple #44
0
        /// <summary>
        /// Shows an error message.
        /// </summary>
        public static void ShowError(IWin32Window parent, string title, Exception ex)
        {
            try
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }

                if (ex.StackTrace != null)
                {
                    Gurux.Common.GXCommon.TraceWrite(ex.StackTrace.ToString());
                }
                string path = ApplicationDataPath;
                if (System.Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    path = Path.Combine(path, ".Gurux");
                }
                else
                {
                    path = Path.Combine(path, "Gurux");
                }
                path = Path.Combine(path, "LastError.txt");
                try
                {
                    using (System.IO.TextWriter tw = System.IO.File.CreateText(path))
                    {
                        tw.Write(ex.ToString());
                        if (ex.StackTrace != null)
                        {
                            tw.Write("----------------------------------------------------------\r\n");
                            tw.Write(ex.StackTrace.ToString());
                        }
                        tw.Close();
                    }
                    GXFileSystemSecurity.UpdateFileSecurity(path);
                }
                catch (Exception)
                {
                    //Skip error.
                }
                if (parent != null && !((Control)parent).IsDisposed && !((Control)parent).InvokeRequired)
                {
                    MessageBox.Show(parent, ex.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(ex.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                //Do nothing. Fatal exception blew up message box.
            }
        }
Exemple #45
0
 static void WriteIcon(System.IO.TextWriter kml, double heading)
 {
     kml.WriteLine("<IconStyle>");
     kml.WriteLine(" <color>ff0000ff</color>");
     kml.WriteLine(" <scale>0.7</scale>");
     kml.Write(" <heading>");
     kml.Write(heading.ToString());
     kml.WriteLine("</heading>");
     kml.WriteLine(" <Icon><href>http://maps.google.com/mapfiles/kml/shapes/arrow.png</href></Icon>");
     kml.WriteLine("</IconStyle>");
 }
Exemple #46
0
 public override void WriteId(System.IO.TextWriter trapFile)
 {
     if (Path is null)
     {
         trapFile.Write("GENERATED;sourcefile");
     }
     else
     {
         trapFile.Write(DatabasePath);
         trapFile.Write(";sourcefile");
     }
 }
Exemple #47
0
        /// <summary>
        /// Writes attachment to a stream
        /// </summary>
        /// <param name="stream">The stream to write the attachmment on</param>
        public void Write(System.IO.TextWriter stream)
        {
            string st = "";

            // writes headers
#if false
            foreach (System.Collections.DictionaryEntry s in m_headers)
            {
                string v = (string)s.Value;

                st = s.Key + ":" + v;
                if (!v.EndsWith("\r\n"))
                {
                    st += endl;
                }

                stream.Write(st);
            }
#else
            foreach (MimeField m in m_headers)
            {
                st = m.Name + ":" + m.Value;
                if (!st.EndsWith("\r\n"))
                {
                    st += endl;
                }

                stream.Write(st);
            }
#endif

            // \r\n to end header
            stream.Write(endl);

            // write body
            System.IO.StringReader r = new System.IO.StringReader(m_body.ToString());
            string tmp;
            while ((tmp = r.ReadLine()) != null)
            {
                stream.Write(tmp + "\r\n");
            }
            r.Close();
            stream.Write(endl);

            // write attachments
            if (m_attachments.Count > 0)
            {
                stream.Write(m_boundary);
                stream.Write(endl);

                foreach (MimeAttachment m in m_attachments)
                {
                    m.Write(stream);
                }
                stream.Write(m_boundary);
                stream.Write(endl);
            }
        }
Exemple #48
0
        private void WriteIEnumerable(System.IO.TextWriter writer, object value)
        {
            WritingArray = true;
            writer.Write("[");
            PushIndent();
            IEnumerable?enumerable = value as System.Collections.IEnumerable;
            int         writeCount = 0;

#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
#pragma warning disable CS8602 // Dereference of a possibly null reference.
            foreach (object item in enumerable)
#pragma warning restore CS8602 // Dereference of a possibly null reference.
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
            {
                bool skip = false;
                if (!(item is null) && IgnoreTypes.Contains(item.GetType()))
                {
                    skip = true;
                }

                if (!skip && ((item?.GetType().IsValueType != false) ||
                              (value is System.Collections.IEnumerable)))
                {
                    if (writeCount > 0)
                    {
                        if (!WritingArray)
                        {
                            writer.Write($",{GetLineFeed()}{GetIndent()}");
                        }
                        else
                        {
                            writer.Write(",");
                        }
                    }
#pragma warning disable CS8604 // Possible null reference argument.
                    Write(writer, item);
#pragma warning restore CS8604 // Possible null reference argument.
                    ++writeCount;
                }
            }
            PopIndent();
            if (!WritingArray)
            {
                writer.Write($"{GetLineFeed()}{GetIndent()}]{GetLineFeed()}");
            }
            else
            {
                writer.Write($"]");
            }

            WritingArray = false;
        }
        protected override void Convert(System.IO.TextWriter writer, object state)
        {
            // Making Greenshot portable
            string pafPath = Path.Combine(Application.StartupPath, @"App\Greenshot");

            if (Directory.Exists(pafPath))
            {
                writer.Write(Path.Combine(Application.StartupPath, @"Data"));
                return;
            }
            Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), base.Option, true);
            writer.Write(Environment.GetFolderPath(specialFolder));
        }
Exemple #50
0
        public static void EmitRegisters(IProcessorArchitecture arch, string caption, Dictionary <RegisterStorage, uint> grfFlags, IEnumerable <Storage> regs, TextWriter sb)
        {
            sb.Write(caption);
            var sGrf = string.Join(" ", grfFlags
                                   .Where(f => f.Value != 0)
                                   .Select(f => arch.GetFlagGroup(f.Key, f.Value) !)
                                   .OrderBy(f => f.Name));

            if (sGrf.Length > 0)
            {
                sb.Write(" {0}", sGrf);
            }
            EmitRegistersCore(regs, sb);
        }
Exemple #51
0
        public override void Write(ContentItem item, string propertyName, System.IO.TextWriter writer)
        {
            string content = item[propertyName] as string;

            if (string.IsNullOrEmpty(content))
            {
                return;
            }

            writer.Write("<meta name=\"");
            writer.Write(propertyName.ToLower());
            writer.Write("\" content=\"");
            writer.Write(content);
            writer.Write("\" />");
        }
Exemple #52
0
        public override void Write(ContentItem item, string propertyName, System.IO.TextWriter writer)
        {
            string content = item[propertyName] as string;

            if (string.IsNullOrEmpty(content))
            {
                return;
            }

            writer.Write("<meta name=\"");
            writer.Write(propertyName.ToLower());
            writer.Write("\" content=\"");
            N2.Context.Current.Resolve <ISafeContentRenderer>().HtmlEncode(content, writer);
            writer.Write("\" />");
        }
Exemple #53
0
        public async System.Threading.Tasks.Task InputLoop()
        {
            string input = null;

            while (!nameof(Commands.Quit).Equals(input, StringComparison.OrdinalIgnoreCase))
            {
                txtOut.WriteLine("Syntax: Origin-Destination outDate [inDate]");
                txtOut.Write(">>");
                input = txtIn.ReadLine();
                await Run(input);
            }
        }
        public void Save(System.IO.TextWriter stream)
        {
            RemoveDuplicateElements();
            var ms = new MemoryStream();

            doc.Save(ms);
            ms.Flush();
            ms.Position = 0;
            var s = new StreamReader(ms).ReadToEnd();

            if (ApplicationName != null)
            {
                s = s.Replace("${applicationId}", ApplicationName);
            }
            if (Placeholders != null)
            {
                foreach (var entry in Placeholders.Select(e => e.Split(new char [] { '=' }, 2, StringSplitOptions.None)))
                {
                    if (entry.Length == 2)
                    {
                        s = s.Replace("${" + entry [0] + "}", entry [1]);
                    }
                    else
                    {
                        log.LogWarning("Invalid application placeholders (AndroidApplicationPlaceholders) value. Use 'key1=value1;key2=value2, ...' format. The specified value was: " + Placeholders);
                    }
                }
            }
            stream.Write(s);
        }
 public void Write(Verbosity v, string template, params object[] args)
 {
     if (v <= verbosity_ && textWriter_ != null)
     {
         textWriter_.Write(template, args);
     }
 }
Exemple #56
0
        /// <summary>
        /// Método que gera arquivo de suitability para a fato
        /// </summary>
        /// <param name="pTexto">Texto com o conteúdo di arquivo que irá ser gravado na pasta específica</param>
        public void GerarArquivoSuitability(StringBuilder pTexto)
        {
            try
            {
                string lNomeArquivo = ConfigurationManager.AppSettings["PathSUITABILITYFATO"].ToString() + "SUITABILITY" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                //string lRenamedArquivo = ConfigurationManager.AppSettings["PathSUITABILITYFATO"].ToString() + "suitability_clientes_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";

                //if (!System.IO.File.Exists(lNomeArquivo))
                //{
                System.IO.File.Create(lNomeArquivo).Close();
                //}
                //else
                //{
                //    System.IO.File.Move(lNomeArquivo, lRenamedArquivo);
                //    System.IO.File.Create(lNomeArquivo).Close();
                //}

                System.IO.TextWriter lArquivo = System.IO.File.AppendText(lNomeArquivo);
                lArquivo.Write(pTexto);

                lArquivo.Close();

                //this.EnviarEmailForaPerfil(lNomeArquivo);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #57
0
        /// <summary>
        /// Called when a shortcut is extracted from the installer and needs to be installed to the device OS
        /// </summary>
        /// <param name="shortcutInfo"></param>
        public virtual void OnInstallShortcut(ref ShortcutInstallInfo shortcutInfo)
        {
            string shortcutFile = SI.Path.Combine(shortcutInfo.ShortcutLocation, shortcutInfo.ShortcutName);

            if (!SI.File.Exists(shortcutInfo.TargetLocation))
            {
                if (ShortcutFailure != null)
                {
                    bool cancel = false;

                    ShortcutFailure(shortcutInfo, new SI.FileNotFoundException("Target file does not exist"), ref cancel);
                    if (!cancel)
                    {
                        m_failedShortcuts++;
                    }
                }
                else
                {
                    m_failedShortcuts++;
                }

                return;
            }

            using (SI.TextWriter writer = SI.File.CreateText(shortcutFile))
            {
                int length = shortcutInfo.TargetLocation.Length;
                length += (length.ToString().Length + 1);

                writer.Write(string.Format("{0}#{1}", length, shortcutInfo.TargetLocation));
            }
        }
Exemple #58
0
        /// <summary>
        /// Método que gera o arquivo fora perfil
        /// </summary>
        /// <param name="pTexto">Texto que irá ser gravado no arquivo fora perfil</param>
        public void GerarArquivo(StringBuilder pTexto)
        {
            try
            {
                string lNomeArquivo    = ConfigurationManager.AppSettings["PathFORAPERFIL"].ToString() + "FORA_PERFIL.prn";
                string lRenamedArquivo = ConfigurationManager.AppSettings["PathFORAPERFIL"].ToString() + "FORA_PERFIL_" + DateTime.Now.ToString("yyyyMMdd") + ".prn";

                if (!System.IO.File.Exists(lNomeArquivo))
                {
                    System.IO.File.Create(lNomeArquivo).Close();
                }
                else
                {
                    System.IO.File.Move(lNomeArquivo, lRenamedArquivo);
                    System.IO.File.Create(lNomeArquivo).Close();
                }

                System.IO.TextWriter lArquivo = System.IO.File.AppendText(lNomeArquivo);
                lArquivo.Write(pTexto);

                lArquivo.Close();

                this.EnviarEmailForaPerfil(lNomeArquivo);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #59
0
 private static void SaveToFile(string fileName)
 {
     SOPOWriter.Write(sb.ToString());
     SOPOWriter.Flush();
     sb.Clear();
     //w.Close();
 }
Exemple #60
0
        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
            string rawcontents    = File.ReadAllText(_viewPhysicalPath);
            string parsedcontents = Parse(rawcontents, viewContext.ViewData);

            writer.Write(parsedcontents);
        }