WriteLine() public method

public WriteLine ( ) : void
return void
Example #1
1
 private static void PrintCaseStatements(TextWriter output, int branchCount, int value, int off)
 {
     for (var i = branchCount; i > 0; i >>= 1)
     {
         if ((i & value) != 0)
         {
             switch (i)
             {
                 case 32:
                     if (gEnableAvx) output.WriteLine("\t_memcpy32_avx(dst + {0}, src + {0});", off);
                     else output.WriteLine("\t_memcpy32_sse2(dst + {0}, src + {0});", off);
                     break;
                 case 16:
                     output.WriteLine("\t_memcpy16_sse2(dst + {0}, src + {0});", off);
                     break;
                 case 8:
                     output.WriteLine("\t*reinterpret_cast<uint64_t*>(dst + {0}) = *reinterpret_cast<uint64_t const*>(src + {0});", off);
                     break;
                 case 4:
                     output.WriteLine("\t*reinterpret_cast<uint32_t*>(dst + {0}) = *reinterpret_cast<uint32_t const*>(src + {0});", off);
                     break;
                 case 2:
                     output.WriteLine("\t*reinterpret_cast<uint16_t*>(dst + {0}) = *reinterpret_cast<uint16_t const*>(src + {0});", off);
                     break;
                 case 1:
                     output.WriteLine("\tdst[{0}] = src[{0}];", off);
                     break;
             }
             off += i;
         }
     }
 }
Example #2
1
        void IDumpableAsText.DumpAsText(TextWriter writer)
        {
            var pbag = new List<KeyValuePair<String, String>>();
            Func<KeyValuePair<String, String>, String> fmt = kvp =>
            {
                var maxKey = pbag.Max(kvp1 => kvp1.Key.Length);
                return String.Format("    {0} : {1}", kvp.Key.PadRight(maxKey), kvp.Value);
            };

            Action<String> fillPbag = s =>
            {
                foreach (var line in s.SplitLines().Skip(1).SkipLast(1))
                {
                    var m = Regex.Match(line, "^(?<key>.*?):(?<value>.*)$");
                    var key = m.Result("${key}").Trim();
                    var value = m.Result("${value}").Trim();
                    pbag.Add(new KeyValuePair<String, String>(key, value));
                }
            };

            writer.WriteLine("Device #{0} \"{1}\" (/pci:{2}/dev:{3})", Index, Name, PciBusId, PciDeviceId);
            fillPbag(Simd.ToString());
            fillPbag(Clock.ToString());
            fillPbag(Memory.ToString());
            fillPbag(Caps.ToString());
            pbag.ForEach(kvp => writer.WriteLine(fmt(kvp)));
        }
        public static void ToGraphic(this ByteMatrix matrix, TextWriter output)
        {
            output.WriteLine(matrix.Width.ToString());
            for (int j = 0; j < matrix.Width; j++)
            {
                for (int i = 0; i < matrix.Width; i++)
                {

                    char charToPrint;
                    switch (matrix[i, j])
                    {
                        case 0:
                            charToPrint = s_0Char;
                            break;

                        case 1:
                            charToPrint = s_1Char;
                            break;

                        default:
                            charToPrint = s_EmptyChar;
                            break;

                    }
                    output.Write(charToPrint);
                }
                output.WriteLine();
            }
        }
 public override void toXML(TextWriter tw)
 {
     tw.WriteLine("<" + Constants.BINC45MODELSELECTION_ELEMENT + " " +
     Constants.MIN_NO_OBJ_ATTRIBUTE + "=\"" + this.m_minNoObj + "\"   " +
     " xmlns=\"urn:mites-schema\">\n");
     tw.WriteLine("</" + Constants.BINC45MODELSELECTION_ELEMENT + ">");           
 }
Example #5
0
        /// Implementation of the IObjectRenderer interface. Called on when an
        /// exception is logged.
        public void RenderObject(RendererMap map, object obj, System.IO.TextWriter writer)
        {
            Exception ex = obj as Exception;

            for (; ex != null; ex = ex.InnerException)
            {
                if (ex is COMException && ex.Message.StartsWith("<?xml"))
                {
                    writer.WriteLine();
                    writer.Write("HFMException message XML contents:");
                    writer.Write(YAML.XML.ConvertXML(ex.Message));
                }
                else
                {
                    writer.Write(ex.GetType().Name);
                    writer.Write(": ");
                    writer.Write(ex.Message);
                }
                if (ex.InnerException != null)
                {
                    writer.WriteLine();
                }
                else if (_logHierarchy.Root.Level.CompareTo(log4net.Core.Level.Fine) < 0)
                {
                    writer.WriteLine();
                    writer.WriteLine("Backtrace:");
                    writer.Write(ex.StackTrace);
                }
            }
        }
Example #6
0
        private void csvwrite()                                                 // write the keystroke list in csv file
        {
            string date     = Form1.stimuli_start_time;
            string filePath = stimuli_output_path + save_file_name + "_" + date + "_" + "KeyLog" + ".csv";

            int length = csv.Count;

            if (length > 1)
            {
                using (System.IO.TextWriter writer = File.CreateText(filePath))
                {
                    for (int index = 0; index < length; index++)
                    {
                        writer.WriteLine(string.Join(delimiter, csv[index]));
                    }
                }
            }
            else
            {
                using (System.IO.TextWriter writer = File.CreateText(filePath))
                {
                    csv.Add("No key" + delimiter + "No key" + delimiter + "No key");
                    writer.WriteLine(string.Join(delimiter, csv[0]));   // Title
                    writer.WriteLine(string.Join(delimiter, csv[1]));   // No Key,No Key,No Key
                }
            }
        }
    ///
    ///Produces a CVS file with the data from analog input channels
    ///
    public static void ProduceCSV(DataTable dt, System.IO.TextWriter httpStream, bool WriteHeader)
    {
        if (WriteHeader)
        {
            string[] arr = new String[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                arr[i] = dt.Columns[i].ColumnName;
                arr[i] = GetWriteableValue(arr[i]);
            }

            httpStream.WriteLine(string.Join(",", arr));
        }

        for (int j = 0; j < dt.Rows.Count; j++)
        {
            string[] dataArr = new String[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                object o = dt.Rows[j][i];
                dataArr[i] = GetWriteableValue(o);
            }
            httpStream.WriteLine(string.Join(",", dataArr));
        }
    }
Example #8
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;
            }
        }
 /// <summary>
 /// Construct a new redis connection (which will be actually setup on demand)
 /// with an object to synchronize access on.
 /// </summary>
 public AsyncRedisConnection(string tier, string delimitedConfiguration, Func<bool> shouldPromoteSlaveToMaster, string tieBreakerKey, string name, bool preserveAsyncOrder = false, bool shareSocketManager = false, TextWriter log = null)
 {
     if (log != null) log.WriteLine("{0} > AsyncRedisConnection", DateTime.UtcNow.ToShortDateString());
     var options = ConfigurationOptions.Parse(delimitedConfiguration, true);
     muxer = Create(tier, options, tieBreakerKey, name, preserveAsyncOrder, shareSocketManager, log, out subscriber);
     if (log != null) log.WriteLine("{0} < AsyncRedisConnection", DateTime.UtcNow.ToShortDateString());
 }
Example #10
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();
            }
        }
Example #11
0
        public static string ExtractQuery(string fileName, TextWriter errorlogger)
        {
            try
            {
                string data = File.ReadAllText(fileName);
                XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.None);
                Stream xmlFragment = new MemoryStream(Encoding.UTF8.GetBytes(data));
                XmlTextReader reader = new XmlTextReader(xmlFragment, XmlNodeType.Element, context);
                reader.MoveToContent();
                if (reader.NodeType == XmlNodeType.Text)
                {
                    return data;
                }
                XmlReader reader2 = reader.ReadSubtree();
                StringBuilder output = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(output))
                {
                    writer.WriteNode(reader2, true);
                }

                StringReader reader3 = new StringReader(data);
                for (int i = 0; i < reader.LineNumber; i++)
                {
                    reader3.ReadLine();
                }
                return reader3.ReadToEnd().Trim();
            }
            catch (Exception ex)
            {
                errorlogger.WriteLine(ex.Message);
                errorlogger.WriteLine(ex.StackTrace);
            }

            return string.Format("//Error loading the file - {0} .The the linq file might be a linqpad expression which is not supported in the viewer currently." ,fileName);
        }
Example #12
0
        public bool Check(TextWriter textWriter)
        {
            var allGood = true;

            foreach (var filePath in Directory.GetFiles(_targetDir))
            {
                var fileName = Path.GetFileName(filePath);
                if (fileName == "README.md")
                {
                    continue;
                }

                textWriter.WriteLine($"Checking {fileName}");
                if (SharedUtil.IsPropsFile(filePath))
                {
                    allGood &= CheckProps(new ProjectUtil(filePath), textWriter);
                }
                else if (SharedUtil.IsTargetsFile(filePath))
                {
                    allGood &= CheckTargets(new ProjectUtil(filePath), textWriter);
                }
                else if (SharedUtil.IsXslt(filePath))
                {
                    // Nothing to verify
                }
                else
                {
                    textWriter.WriteLine("Unrecognized file type");
                    allGood = false;
                }
            }

            return allGood;
        }
Example #13
0
		private void WritePotHeader(TextWriter writer)
		{
			/* Note:
			 * Since the Transifex upgrade to 1.0 circa 2010-12 the pot file is now required to have
			 * a po header that passes 'msgfmt -c'.
			 * POEdit does not expect a header in the pot file and doesn't read one if present.  The
			 * user is invited to enter the data afresh for the po file which replaces any data we have
			 * provided.  To preserve the original data from the pot we also include the header info
			 * as a comment.
			 */
			writer.WriteLine(@"msgid """"");
			writer.WriteLine(@"msgstr """"");
			writer.WriteLine(@"""Project-Id-Version: " + ProjectId + @"\n""");
			writer.WriteLine(@"""POT-Creation-Date: " + DateTime.UtcNow.ToString("s") + @"\n""");
			writer.WriteLine(@"""PO-Revision-Date: \n""");
			writer.WriteLine(@"""Last-Translator: \n""");
			writer.WriteLine(@"""Language-Team: \n""");
			writer.WriteLine(@"""Plural-Forms: \n""");
			writer.WriteLine(@"""MIME-Version: 1.0\n""");
			writer.WriteLine(@"""Content-Type: text/plain; charset=UTF-8\n""");
			writer.WriteLine(@"""Content-Transfer-Encoding: 8bit\n""");
			writer.WriteLine();

			/* As noted above the commented version below isn't read by POEdit, however it is preserved in the comments */
			writer.WriteLine("# Project-Id-Version: {0}", ProjectId);
			writer.WriteLine("# Report-Msgid-Bugs-To: {0}", MsdIdBugsTo);
			writer.WriteLine("# POT-Creation-Date: {0}", DateTime.UtcNow.ToString("s"));
			writer.WriteLine("# Content-Type: text/plain; charset=UTF-8");
			writer.WriteLine();

		}
Example #14
0
        /// <summary>
        /// Hex dump byte array to Text writer
        /// </summary>
        /// <param name="writer">Text writer to write hex dump to</param>
        /// <param name="bytes">Data to dump as hex</param>
        /// <param name="maxLength">Optional max bytes to dump</param>
        public static void Dump(TextWriter writer, byte[] bytes, int maxLength = int.MaxValue)
        {
            const int rowSize = 16;
            var hex = new StringBuilder(rowSize * 3);
            var ascii = new StringBuilder(rowSize);
            var offset = 0;

            foreach (var b in bytes.Take(maxLength))
            {
                hex.AppendFormat("{0:X2} ", b);
                ascii.Append(Char.IsControl((char)b) ? '.' : (char)b);

                if (ascii.Length == rowSize)
                {
                    writer.WriteLine("{0:X4} : {1}{2} {0}", offset, hex, ascii);
                    hex.Clear();
                    ascii.Clear();
                    offset += rowSize;
                }
            }

            if (ascii.Length != 0)
            {
                while (hex.Length < (rowSize*3)) hex.Append(' ');
                while (ascii.Length < rowSize) ascii.Append(' ');
                writer.WriteLine("{0:X4} : {1}{2} {0}", offset, hex, ascii);
            }

            if (bytes.Length > maxLength)
                writer.WriteLine("(More data... 0x{0:X}({0}))", bytes.Length);
        }
        /// <summary> Stream to which to write the HTML for this subwriter  </summary>
        /// <param name="Output"> Response stream for the item viewer to write directly to </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        public override void Write_Main_Viewer_Section(TextWriter Output, Custom_Tracer Tracer)
        {
            if (Tracer != null)
            {
                Tracer.Add_Trace("YouTube_Embedded_Video_ItemViewer.Write_Main_Viewer_Section", "");
            }

            //Determine the name of the FLASH file
            string youtube_url = CurrentItem.Bib_Info.Location.Other_URL;
             if ( youtube_url.IndexOf("watch") > 0 )
                 youtube_url = youtube_url.Replace("watch?v=","v/") + "?fs=1&amp;hl=en_US";
            const int width = 600;
            const int height = 480;

            // Add the HTML for the image
            StringBuilder result = new StringBuilder(500);
            Output.WriteLine("          <td><div id=\"sbkEmv_ViewerTitle\">Streaming Video</div></td>");
            Output.WriteLine("        </tr>");
            Output.WriteLine("        <tr>");
            Output.WriteLine("          <td id=\"sbkEmv_MainArea\">");
            Output.WriteLine("            <object style=\"width:" + width + ";height:" + height + "\">");
            Output.WriteLine("              <param name=\"allowscriptaccess\" value=\"always\" />");
            Output.WriteLine("              <param name=\"movie\" value=\"" + youtube_url + "\" />");
            Output.WriteLine("              <param name=\"allowFullScreen\" value=\"true\"></param>");
            Output.WriteLine("              <embed src=\"" + youtube_url + "\" type=\"application/x-shockwave-flash\" AllowScriptAccess=\"always\" allowfullscreen=\"true\" width=\"" + width + "\" height=\"" + height + "\"></embed>");
            Output.WriteLine("            </object>");
            Output.WriteLine("          </td>" );
        }
 /// <summary>
 /// Decreases the indent level and closes the actual IL declaration scope.
 /// </summary>
 /// <code>
 /// }
 /// </code>
 /// <returns>The TransformationILWriter instance for use in concatenated output.</returns>
 public TransformationILWriter CloseIL( )
 {
     Indent(-1);
     WriteIndented("}");
     writer.WriteLine();
     return(this);
 }
Example #17
0
 public override void PrintLogo(TextWriter consoleOutput)
 {
     Assembly thisAssembly = typeof(Csi).Assembly;
     consoleOutput.WriteLine(CsiResources.LogoLine1, FileVersionInfo.GetVersionInfo(thisAssembly.Location).FileVersion);
     consoleOutput.WriteLine(CsiResources.LogoLine2);
     consoleOutput.WriteLine();
 }
Example #18
0
 private void AND(OpcodeInfo op, TextWriter w)
 {
     GetValue8(op, w, "value8");
     w.WriteLine(Spaces + "A &= value8;");
     w.WriteLine(Spaces + SetNZ("A"));
     w.WriteLine(Spaces + "PendingCycles -= {0}; TotalExecutedCycles += {0};", op.Cycles);
 }
        /// <summary> Stream to which to write the HTML for this subwriter  </summary>
        /// <param name="Output"> Response stream for the item viewer to write directly to </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering </param>
        public override void Write_Main_Viewer_Section(TextWriter Output, Custom_Tracer Tracer)
        {
            if (Tracer != null)
            {
                Tracer.Add_Trace("EAD_Description_ItemViewer.Write_Main_Viewer_Section", "");
            }

            // Get the metadata module for EADs
            EAD_Info eadInfo = (EAD_Info)CurrentItem.Get_Metadata_Module(GlobalVar.EAD_METADATA_MODULE_KEY);

            // Build the value
            Output.WriteLine("          <td>");
            Output.WriteLine("            <div id=\"sbkEad_MainArea\">");

            if ( !String.IsNullOrWhiteSpace(CurrentMode.Text_Search))
            {
                // Get any search terms
                List<string> terms = new List<string>();
                if (CurrentMode.Text_Search.Trim().Length > 0)
                {
                    string[] splitter = CurrentMode.Text_Search.Replace("\"", "").Split(" ".ToCharArray());
                    terms.AddRange(from thisSplit in splitter where thisSplit.Trim().Length > 0 select thisSplit.Trim());
                }

                Output.Write(Text_Search_Term_Highlighter.Hightlight_Term_In_HTML(eadInfo.Full_Description, terms));
            }
            else
            {
                Output.Write(eadInfo.Full_Description);
            }

            Output.WriteLine("            </div>");
            Output.WriteLine("          </td>");
        }
Example #20
0
        private static void WriteRuleNodes <T>(string source, STbRule <T> rule, System.IO.TextWriter tw, ISTb <T> stb, bool endcase)
        {
            UndefRule <T> raise = rule as UndefRule <T>;

            if (raise != null)
            {
                tw.WriteLine("{0} [fillcolor = {2}, label =\"{1}\"];", source, ShortenLabel(DisplayLabel(raise.Exc)), excColor);
                return;
            }
            BaseRule <T> block = rule as BaseRule <T>;

            if (block != null)
            {
                string lab = Describe(stb, block, endcase);
                if (endcase)
                {
                    tw.WriteLine("{0} [fillcolor={1}, peripheries = 2, label =\"{2}\"];", source, accColor, DisplayLabel(lab));
                }
                else
                {
                    tw.WriteLine("{0} [label =\"{1}\"];", source, DisplayLabel(lab));
                }
                return;
            }
            else
            {
                IteRule <T> ite = (IteRule <T>)rule;
                string      lab = stb.PrettyPrint(ite.Condition);
                tw.WriteLine("{0} [label =\"{1}\", style=rounded];", source, ShortenLabel(DisplayLabel(lab)));
                WriteRuleNodes(source + "T", ite.TrueCase, tw, stb, endcase);
                WriteRuleNodes(source + "F", ite.FalseCase, tw, stb, endcase);
            }
        }
 private static void WriteDomain(TextWriter writer, MBeanDomain domain)
 {
     writer.WriteLine("<span class=\"folder\">{0}</span>", domain.Name);
     writer.WriteLine("<ul>");
     WriteDomainItems(writer, domain);
     writer.WriteLine("</ul>");
 }
        public bool Check(TextWriter textWriter)
        {
            foreach (var element in _document.XPathSelectElements("//CopyTask"))
            {
                foreach (var message in element.Elements(XName.Get("Message")))
                {
                    ProcessMessage(message);
                }
            }

            var allGood = true;
            foreach (var pair in _copyMap.OrderBy(x => x.Key))
            {
                var list = pair.Value;
                if (list.Count > 1)
                {
                    textWriter.WriteLine($"Multiple writes to {pair.Key}");
                    foreach (var item in list)
                    {
                        textWriter.WriteLine($"\t{item}");

                    }
                    textWriter.WriteLine("");

                    allGood = false;
                }
            }

            return allGood;
        }
Example #23
0
        public static void DumpInfo(TextWriter tw)
        {
            for (var i = 0; i < 8; ++i) {
                tw.WriteLine("Priority: {0}", (TimerPriority)i);
                tw.WriteLine();

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

                for (var j = 0; j < mTimers[i].Count; ++j) {
                    var t = mTimers[i][j];

                    var key = t.ToString();

                    List<Timer> list;
                    hash.TryGetValue(key, out list);

                    if (list == null) {
                        hash[key] = list = new List<Timer>();
                    }

                    list.Add(t);
                }

                foreach (var kv in hash) {
                    var key = kv.Key;
                    var list = kv.Value;

                    tw.WriteLine("Type: {0}; Count: {1}; Percent: {2}%", key, list.Count, (int)(100 * (list.Count / (double)mTimers[i].Count)));
                }

                tw.WriteLine();
                tw.WriteLine();
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            output = Console.Out;
            output = new StreamWriter(@"Assignment2.smt");
            start("P Int Int Int", "QF_UFLIA");

            int[] chip = new int[2] {29,22};
            int[] powerComponent = new int[2] {4,2};
            int[,] components = new int[8, 2] {{9,7},{12,6},{10,7},{18,5},{20,4},{10,6},{8,6},{10,8}};
            int powerDist = 17;

            //All components must occur
            for (int i = 2; i < components.Length + 2; i++) {
                output.WriteLine("(or");
                for (int x = 0; x < chip [0]; x++) {
                    for (int y = 0; y < chip [1]; y++) {
                        output.WriteLine("(= (P {0} {1}) {2})", x, y, i);
                    }
                }
                output.WriteLine(")");
            }

            end();

            output.Close();
            //Console.ReadKey();
        }
Example #25
0
 public override void PrintUsage(TextWriter writer)
 {
     writer.WriteLine("  /{0} ", Key);
     writer.WriteLine();
     writer.WriteLine("      {0}", Description);
     writer.WriteLine();
 }
Example #26
0
		/// <summary>
		///  Starts the toploop running using specified input, output and error streams
		/// 
		/// </summary>
		/// <param name="reader"></param>
		/// <param name="writer"></param>
		/// <param name="error"></param>
		public void Run(TextReader reader, TextWriter writer, TextWriter error) 
		{
			Symbol LAST = Symbol.FromName("?");
			Symbol LAST_ERROR = Symbol.FromName("*error*");
			while (true) 
			{
				try 
				{
					writer.Write(prompt);

					Object o = Runtime.EvalString("(eval (read (get_in Console)))",environment);

					environment.AssignLocal(LAST,o);
                    string s = Printer.WriteToString(o);
					writer.WriteLine(s);
				} 
				catch (LSharpException e) 
				{
					error.WriteLine(e.Message);
					environment.AssignLocal(LAST_ERROR, e);
				}
				catch (Exception e) 
				{
					error.WriteLine(e);
					environment.AssignLocal(LAST_ERROR, e);
				}
			}
		}
        public static void Host(TextWriter log, CancellationToken cancellationToken)
        {
            var configuration = new BusConfiguration();
            configuration.UseTransport<AzureStorageQueueTransport>();
            configuration.UsePersistence<InMemoryPersistence>();
            configuration.Conventions()
                .DefiningCommandsAs(t => t.Namespace != null && t.Namespace.StartsWith("VideoStore") && t.Namespace.EndsWith("Commands"))
                .DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("VideoStore") && t.Namespace.EndsWith("Events"))
                .DefiningMessagesAs(t => t.Namespace != null && t.Namespace.StartsWith("VideoStore") && t.Namespace.EndsWith("RequestResponse"))
                .DefiningEncryptedPropertiesAs(p => p.Name.StartsWith("Encrypted"));
            configuration.RijndaelEncryptionService();
            configuration.EnableInstallers();
            
            var startableBus = Bus.Create(configuration);
            startableBus.Start();
            log.WriteLine("The VideoStore.Sales endpoint is now started and ready to accept messages");

            while (!cancellationToken.IsCancellationRequested)
            {
                Thread.Sleep(3000);
            }

            startableBus.Dispose();
            log.WriteLine("Host: stopped at " + DateTime.UtcNow);
        }
Example #28
0
        public static void Write(IniFile iniFile, TextWriter textWriter)
        {
            foreach (IniSection section in iniFile.Sections)
            {
                if (section != iniFile.Sections.First())
                {
                    textWriter.WriteLine();
                }

                if (section.Comments.Count > 0)
                {
                    foreach (string comment in section.Comments)
                    {
                        textWriter.WriteLine(";"  + comment);
                    }
                }

                textWriter.WriteLine("[" + section.Name + "]");

                foreach (IniKeyValue keyValue in section.KeyValues)
                {
                    if (keyValue.Comments.Count > 0)
                    {
                        foreach (string comment in keyValue.Comments)
                        {
                            textWriter.WriteLine(";" + comment);
                        }
                    }

                    textWriter.WriteLine(keyValue.Key + "=" + keyValue.Value);
                }
            }
        }
        public int RunCommand(TextReader input, TextWriter output, string tenant, string[] args, Dictionary<string, string> switches)
        {
            try {
                tenant = tenant ?? "Default";

                var env = FindOrCreateTenant(tenant);

                var parameters = new CommandParameters {
                    Arguments = args,
                    Switches = switches,
                    Input = input,
                    Output = output
                };

                env.Resolve<ICommandManager>().Execute(parameters);

                return 0;
            }
            catch (Exception e) {
                for (int i = 0; e != null; e = e.InnerException, i++) {
                    if (i > 0) {
                        output.WriteLine("-------------------------------------------------------------------");
                    }
                    output.WriteLine("Error: {0}", e.Message);
                    output.WriteLine("{0}", e.StackTrace);
                }
                return 5;
            }
        }
        public void HandleInput(TextReader input, TextWriter output)
        {
            bool isRunning = true;
            IDictionary<string, Command> commands = new Dictionary<string, Command>(Command.Library);
            Command help = new Command(
                name: "help",
                annotation: "Lists all commands.",
                action: (srvr, args) =>
                {
                    string intro = "*** The following are all available commands: ***";
                    output.WriteLine(intro);
                    foreach (var command in commands.Values)
                    {
                        output.WriteLine("*    - " + command.Name + "\n   " + command.Annotation);
                    }
                    output.WriteLine(new string('*', intro.Length));
                });
            commands.Add("help", help);

            char[] delimiter = new char[] { ' ' };
            while (isRunning)
            {
                string data = input.ReadLine();
                string[] split = data.Split(delimiter);
                string command = split[0].ToLowerInvariant();
                if (commands.ContainsKey(command))
                {
                    commands[command].Action(this.server, split.Skip(1).ToArray());
                }
                else
                {
                    output.WriteLine("No such command.");
                }
            }
        }
        /// <summary>
        /// This function demonstrates how cancellation tokens can be used to gracefully shutdown a webjob. 
        /// </summary>
        /// <param name="message">A queue message used to trigger the function</param>
        /// <param name="log">A text writer associated with the output log from dashboard.</param>
        /// <param name="cancellationToken">The cancellation token that is signaled when the job must stop</param>
        public static void ShutdownMonitor(
            [QueueTrigger("%ShutdownQueueName%")] string message,
            TextWriter log,
            CancellationToken cancellationToken)
        {
            // Simulate what happens in Azure WebSites
            // as described here http://blog.amitapple.com/post/2014/05/webjobs-graceful-shutdown/#.U3aIXRFOVaQ
            new Thread(new ThreadStart(() =>
            {
                log.WriteLine("From thread: In about 10 seconds, the job will be signaled to stop");
                Thread.Sleep(10000);

                // Modify the shutdown file
                File.WriteAllText(shutDownFile, string.Empty);
            })).Start();

            log.WriteLine("From function: Received a message: " + message);

            while (!cancellationToken.IsCancellationRequested)
            {
                log.WriteLine("From function: Cancelled: No");
                Thread.Sleep(2000);
            }

            // Perform the graceful shutdown logic here
            log.WriteLine("From function: Cancelled: Yes");
        }
        public void Run(ComputeContext context, TextWriter log)
        {
            try
            {
                ComputeProgram program = new ComputeProgram(context, kernelSources);
                program.Build(null, null, null, IntPtr.Zero);
                log.WriteLine("Program successfully built.");
                ICollection<ComputeKernel> kernels = program.CreateAllKernels();
                log.WriteLine("Kernels successfully created.");

                // cleanup kernels
                foreach (ComputeKernel kernel in kernels)
                {
                    kernel.Dispose();
                }
                kernels.Clear();

                // cleanup program
                program.Dispose();
            }
            catch (Exception e)
            {
                log.WriteLine(e.ToString());
            }
        }
        internal static void WriteCreateInfoFromQueryStringMethod(
            TextWriter writer, List<VariableSpecification> requiredParameters, List<VariableSpecification> optionalParameters, string methodNamePrefix,
            string infoConstructorArgPrefix)
        {
            writer.WriteLine( methodNamePrefix + ( methodNamePrefix.Contains( "protected" ) ? "c" : "C" ) + "reateInfoFromQueryString() {" );

            writer.WriteLine( "try {" );
            var allParameters = requiredParameters.Concat( optionalParameters );

            // Create a local variable for all query parameters to hold their raw query value.
            foreach( var parameter in allParameters ) {
                // If a query parameter is not specified, Request.QueryString[it] returns null. If it is specified as blank (&it=), Request.QueryString[it] returns the empty string.
                writer.WriteLine(
                    "var " + getLocalQueryValueVariableName( parameter ) + " = HttpContext.Current.Request.QueryString[ \"" + parameter.PropertyName + "\" ];" );
            }

            // Enforce specification of all required parameters.
            foreach( var parameter in requiredParameters ) {
                // Blow up if a required parameter was not specified.
                writer.WriteLine(
                    "if( " + getLocalQueryValueVariableName( parameter ) + " == null ) throw new ApplicationException( \"Required parameter not included in query string: " +
                    parameter.Name + "\" );" );
            }

            // Build up the call to the info constructor.
            var infoCtorArguments = new List<string> { infoConstructorArgPrefix };
            infoCtorArguments.AddRange( requiredParameters.Select( rp => getChangeTypeExpression( rp ) ) );

            // If there are optional parameters, build an optional paramater package, populate it, and include it in the call to the info constructor.
            if( optionalParameters.Count > 0 ) {
                infoCtorArguments.Add( "optionalParameterPackage: optionalParameterPackage" );
                writer.WriteLine( "var optionalParameterPackage = new OptionalParameterPackage();" );
                foreach( var parameter in optionalParameters ) {
                    // If the optional parameter was not specified, do not set its value (let it remain its default value).
                    writer.WriteLine(
                        "if( " + getLocalQueryValueVariableName( parameter ) + " != null ) optionalParameterPackage." + parameter.PropertyName + " = " +
                        getChangeTypeExpression( parameter ) + ";" );
                }
            }

            // Construct the info object.
            writer.WriteLine( "info = new Info( " + StringTools.ConcatenateWithDelimiter( ", ", infoCtorArguments.ToArray() ) + " );" );
            writer.WriteLine( "}" ); // Try block

            writer.WriteLine( "catch( Exception e ) {" );
            writer.WriteLine( "if( e is UserDisabledByPageException )" );
            writer.WriteLine( "throw;" );
            writer.WriteLine(
                "throw new ResourceNotAvailableException( \"Query parameter values or non URL elements of the request prevented the creation of the page or entity setup info object.\", e );" );
            writer.WriteLine( "}" ); // Catch block

            // Initialize the parameters modification object.
            if( allParameters.Any() ) {
                writer.WriteLine( "parametersModification = new ParametersModification();" );
                foreach( var parameter in allParameters )
                    writer.WriteLine( "parametersModification." + parameter.PropertyName + " = info." + parameter.PropertyName + ";" );
            }

            writer.WriteLine( "}" );
        }
Example #34
0
		static void Summary(TextWriter c)
		{
			Header(c, "Summary", "$(\"a.type\").click (function (e) { $(this).append ('<div></div>'); $(this).children ().load ('/type/'); console.log ($(this).contents ()); e.preventDefault ();});");
			//Header (c, "Summary", "alert ('loaded');");
			var weakList = MonoTouch.ObjCRuntime.Runtime.GetSurfacedObjects();
			c.WriteLine("<div id='foo'></div>");
			c.WriteLine("<p>Total surfaced objects: {0}", weakList.Count);
			var groups = from weak in weakList
				let nso =  weak.Target
				where nso != null
				let typeName = nso.GetType().FullName
				orderby typeName
				group nso by typeName into g
				let gCount = g.ToList().Count
				orderby gCount descending
				select new { Type = g.Key, Instances = g };
			var list = groups.ToList();
			c.WriteLine("<p>Have {0} different types surfaced", list.Count);
			c.WriteLine("<ul>");
			foreach (var type in list)
			{
				c.WriteLine("<li>{1} <a href='' class='type'>{0}</a>", type.Type, type.Instances.ToList().Count);
			}
			c.WriteLine("</ul>");
			c.WriteLine("</body></html>");
		}
Example #35
0
 /// <summary>
 /// Appends the header.
 /// </summary>
 /// <param name="w">The w.</param>
 public void AppendHeader(TextWriter w)
 {
     w.WriteLine("Content-Type: " + ContentType);
     w.WriteLine("Content-Transfer-Encoding: base64");
     w.WriteLine("Content-Location: " + Uri.ToString());
     w.WriteLine();
 }
Example #36
0
        public static void WriteResource(TextWriter writer, ResourceDefinition resource, string url, string condition, Dictionary<string, string> attributes) {
            if (!string.IsNullOrEmpty(condition)) {
                if (condition == NotIE) {
                    writer.WriteLine("<!--[if " + condition + "]>-->");
                }
                else {
                    writer.WriteLine("<!--[if " + condition + "]>");
                }
            }

            var tagBuilder = GetTagBuilder(resource, url);
            
            if (attributes != null) {
                // todo: try null value
                tagBuilder.MergeAttributes(attributes, true);
            }

            writer.WriteLine(tagBuilder.ToString(resource.TagRenderMode));
            
            if (!string.IsNullOrEmpty(condition)) {
                if (condition == NotIE) {
                    writer.WriteLine("<!--<![endif]-->");
                }
                else {
                    writer.WriteLine("<![endif]-->");
                }
            }
        }
Example #37
0
        private static string sbQueueName = ConfigurationManager.AppSettings["serviceBusQueueName"];//"sksdemo";

        // This function will get triggered/executed when a new message is written 
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([ServiceBusTrigger("wistrondemo")] BrokeredMessage message,
                TextWriter logger)
        {
            logger.WriteLine(message);
            logger.WriteLine($"{message} received at {DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")}");
            if (message.Properties.Keys.Contains("message-source") && (string)message.Properties["message-source"] == "evh")
            {
                var o = message.GetBody<System.IO.Stream>();
                using (var r = new StreamReader(o))
                {
                    var msg = r.ReadToEnd();
                    Console.WriteLine("Body: " + msg);
                    Console.WriteLine("MessageID: " + message.MessageId);
                    SendNotificationAsync(msg);
                    // Remove message from queue.
                    message.Complete();
                }

            }
            else
            {
                // Process message from stream analytics.
                var msg = message.GetBody<string>();

                Console.WriteLine("Body: " + msg);
                Console.WriteLine("MessageID: " + message.MessageId);
                SendNotificationAsync(msg);
                // Remove message from queue.
                message.Complete();
            }

        }
 private void logSceneSwitch(GameScenes scene)
 {
     if (Tw != null)
     {
         Tw.WriteLine(DateTime.Now.ToString("HH:mm:ss tt") + " [KSP] ==== Scene Switch to " + scene.ToString() + " ! ====");
     }
 }
Example #39
0
 public override void WriteTo(System.IO.TextWriter w)
 {
     w.WriteLine("/* This program was generated by Tevador.RandomJS */");
     w.WriteLine("/* Seed: {0} */", BinaryUtils.ByteArrayToString(Seed));
     w.WriteLine("/* Print order: {0} */", string.Join(", ", PrintOrder));
     w.WriteLine("'use strict';");
     base.WriteTo(w);
 }
 public override void WriteCommand(System.IO.TextWriter writer)
 {
     writer.WriteLine("Translate {");
     foreach (string[] key in _stringmapping.Keys)
     {
         writer.WriteLine("{0} => {1}", ProjectSerializer.SecureList(key), ProjectSerializer.SecureList(_stringmapping[key]));
     }
     writer.WriteLine("}");
 }
Example #41
0
        public void SaveStateText(System.IO.TextWriter writer)
        {
            var s = SaveState();

            ser.Serialize(writer, s);
            // write extra copy of stuff we don't use
            writer.WriteLine();
            writer.WriteLine("Frame {0}", Frame);
        }
 public void Serialize(System.IO.TextWriter writer)
 {
     writer.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
     writer.WriteLine("<recordings>");
     for (int i = 0; i < this.mList.Count; i++)
     {
         this.mList[i].Serialize(writer);
     }
     writer.WriteLine("</recordings>");
 }
Example #43
0
 public void Read(string file)
 {
     try {
         System.IO.StreamReader reader = new System.IO.StreamReader(file);
         _i.Read(reader);
     } catch (System.Exception e) {
         _writer.WriteLine(e.Message);
         _writer.WriteLine(e.StackTrace);
     }
 }
        private static void WriteArtifactsToFile(TLArtifactsCollection artifacts, System.IO.TextWriter writeFile)
        {
            //header
            writeFile.WriteLine("Id,Text");

            foreach (TLArtifact artifact in artifacts.Values)
            {
                writeFile.WriteLine("\"{0}\",\"{1}\"", artifact.Id, artifact.Text);
            }
        }
Example #45
0
 private void writeHtml(System.IO.TextWriter textWriter, IList <UserSummary> summaries)
 {
     textWriter.WriteLine("<table><tr><th>Rank</th><th>Reputation</th><th>Name</th></tr>");
     foreach (UserSummary user in summaries)
     {
         textWriter.WriteLine("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", user.Rank, user.Reputation, user.Name);
     }
     textWriter.Write("</table>");
     textWriter.Flush();
 }
Example #46
0
        private void OutLine(string arg)
        {
#if false
            // for tree on the left and assembly code on the right
            _output.WriteLine(String.Format("{0}{1}", "                                       ", arg));
#else
            // for code on left and tree on the right
            var pad = Dump.LastIntro == null ? "" : Dump.LastIntro.Substring(arg.Length);
            _output.WriteLine(String.Format("{0}{1}", arg, pad));
#endif
        }
Example #47
0
        /// <summary>
        /// Private method to write TLSimilarityMatrix to CSV
        /// </summary>
        /// <param name="similarityMatrix">Matrix</param>
        /// <param name="writeFile">Open TextWriter stream</param>
        private static void WriteMatrixCSV(TLSimilarityMatrix similarityMatrix, System.IO.TextWriter writeFile)
        {
            //header
            writeFile.WriteLine("Source Artifact Id,Target Artifact Id,Probability");
            TLLinksList traceLinks = similarityMatrix.AllLinks;

            traceLinks.Sort();
            foreach (TLSingleLink link in traceLinks)
            {
                writeFile.WriteLine("{0},{1},{2}", link.SourceArtifactId, link.TargetArtifactId, link.Score);
            }
        }
Example #48
0
        /// <summary>
        /// Private method to export a TLSimilarityMatrix to CSV with an additional column for correct links
        /// 0 - incorrect link
        /// 1 - correct link
        /// </summary>
        /// <param name="similarityMatrix">Candidate Matrix</param>
        /// <param name="answerMatrix">Answer Matrix</param>
        /// <param name="writeFile">Open TextWriter stream</param>
        private static void WriteMatrixCSVWithCorrectness(TLSimilarityMatrix similarityMatrix, TLSimilarityMatrix answerMatrix, System.IO.TextWriter writeFile)
        {
            //header
            writeFile.WriteLine("Source Artifact Id,Target Artifact Id,Probability,Is correct");
            TLLinksList traceLinks = similarityMatrix.AllLinks;

            traceLinks.Sort();
            foreach (TLSingleLink link in traceLinks)
            {
                writeFile.WriteLine("{0},{1},{2},{3}", link.SourceArtifactId, link.TargetArtifactId, link.Score, (answerMatrix.IsLinkAboveThreshold(link.SourceArtifactId, link.TargetArtifactId)) ? "1" : "0");
            }
        }
Example #49
0
 public void Start()
 {
     if (File.Exists(AssemblyFolder + "/PluginData/" + AssemblyName + ".log"))
     {
         File.Delete(AssemblyFolder + "/PluginData/" + AssemblyName + ".log");
     }
     Tw = new StreamWriter(AssemblyFolder + "/PluginData/" + AssemblyName + ".log");
     Tw.WriteLine(AssemblyName + Assembly.GetExecutingAssembly().GetName().Version);
     Tw.WriteLine("Loaded up on " + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss tt") + ".");
     Tw.WriteLine();
     GameEvents.onGameSceneLoadRequested.Add(logSceneSwitch);
 }
 private static void ShowComputedHash <T>(string algDisplayName, byte[] data, System.IO.TextWriter w) where T : HashAlgorithm, new()
 {
     using (var alg = new T())
     {
         var hash = alg.ComputeHash(data);
         w.WriteLine("{0}:", algDisplayName);
         foreach (ChaosHelper.KeyEncoding item in Enum.GetValues(typeof(ChaosHelper.KeyEncoding)))
         {
             w.WriteLine("{0,-20}{1}", item, ChaosHelper.FormatByteArray(hash, item));
         }
         w.WriteLine();
     }
 }
Example #51
0
        public static void doDiagnostic()
        {
            System.IO.TextWriter stream = getDiagnosticFile();
            if (stream != null)
            {
                stream.WriteLine("Diagnostic le " + DateTime.Now.ToLongDateString() + " à " + DateTime.Now.ToLongTimeString());
                stream.WriteLine();

                stream.WriteLine("== XP Nessecaire par niveau ==");
                stream.WriteLine(".");
                for (int i = 0; i < 30; i++)
                {
                    stream.WriteLine("Niveau {0}: {1}xp", i.ToString(), XPHelper.GetXpForLevel(i).ToString());
                    if (i == 20)
                    {
                        stream.WriteLine("-- Niveaux de prestiges --");
                    }
                }

                stream.WriteLine(".");
                int xplvlmax = 0;
                for (int i = 0; i < 20; i++)
                {
                    xplvlmax += XPHelper.GetXpForLevel(i);
                }
                stream.WriteLine("XP Total Nessecaire pour level 20 : " + xplvlmax);
            }
            Console.WriteLine("Diagnostic terminé, voir " + fileName);
            stream.Close();
        }
Example #52
0
/*************************************************************************************************************************/
        public void write_record_file()
        {
            Log.PushStackInfo("FMRS_THL.write_record_file", "FMRS_THL_Log: entering write_record_file()");
            Log.dbg("FMRS_THL_Log: write to record file");

            writing = true;

            Throttle_Log_Buffer.Sort(delegate(entry x, entry y)
            {
                if (x.time > y.time)
                {
                    return(1);
                }
                else
                {
                    return(-1);
                }
            });

            IO.TextWriter writer = null;
            try
            {
                writer = IO.File.AppendText(FMRS.FILES.RECORD_TXT);
                writer.WriteLine("##########################################");
                foreach (entry temp in Throttle_Log_Buffer)
                {
                    writer.WriteLine(temp.ToString());
                }

                if (!started)
                {
                    writer.WriteLine("####EOF####");
                }
            }
            finally
            {
                writer?.Close();
            }

            Throttle_Log_Buffer.Clear();
            writing = false;

            foreach (entry temp in temp_buffer)
            {
                Throttle_Log_Buffer.Add(temp);
            }
            temp_buffer.Clear();

            FMRS.Log.PopStackInfo("FMRS_THL_Log: leave write_record_file()");
        }
Example #53
0
 private static void AddVersionKey(IO.TextWriter writer, string name, object value)
 {
     if (value != null)
     {
         writer.WriteLine($"VIAddVersionKey \"{name}\" \"{value}\"");
     }
 }
Example #54
0
 private void IRCOutputProcedure(System.IO.TextWriter output)
 {
     System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
     stopWatch.Start();
     while (!stopThreads)
     {
         lock (commandQueue)
         {
             if (commandQueue.Count > 0) //do we have any commands to send?
             {
                 // https://github.com/justintv/Twitch-API/blob/master/IRC.md#command--message-limit
                 //have enough time passed since we last sent a message/command?
                 if (stopWatch.ElapsedMilliseconds > 1750)
                 {
                     //send msg.
                     output.WriteLine(commandQueue.Peek());
                     output.Flush();
                     //remove msg from queue.
                     commandQueue.Dequeue();
                     //restart stopwatch.
                     stopWatch.Reset();
                     stopWatch.Start();
                 }
             }
         }
     }
 }
Example #55
0
        public MdxObject Parse(string mdx)
        {
            try
            {
                var ms = new MemoryStream(Encoding.Unicode.GetBytes(mdx));
                ms.Position = 0;

                var lexer = new mdxLexer
                                (new Antlr.Runtime.ANTLRInputStream
                                    (ms
                                    , Encoding.Unicode
                                    )
                                );
                lexer.Error = this.Error;
                var parser = new mdxParser
                             (
                    new Antlr.Runtime.CommonTokenStream(lexer)
                             );
                parser.Error = this.Error;
                var result = parser.mdx_statement();
                return(result);
            }
            catch (Exception e)
            {
                Error.WriteLine(e.ToString());
                throw new Exception("При разборе запроса были ошибки. Смотрите протокол.", e);
            }
        }
Example #56
0
        private void RemoveXmlFilesWhereXmbExists(System.IO.TextWriter verboseOutput)
        {
            for (int x = FileChunksFirstIndex; x < mFiles.Count; x++)
            {
                var file = mFiles[x];
                if (!ResourceUtils.IsXmlBasedFile(file.FileName))
                {
                    continue;
                }

                string xmb_name = file.FileName;
                xmb_name += Xmb.XmbFile.kFileExt;
                EraFileEntryChunk xmb_file;
                if (!mFileNameToChunk.TryGetValue(xmb_name, out xmb_file))
                {
                    continue;
                }

                if (verboseOutput != null)
                {
                    verboseOutput.WriteLine("\tRemoving XML file #{0} '{1}' from listing since its XMB already exists {2}",
                                            FileIndexToListingIndex(x),
                                            file.FileName,
                                            xmb_file.FileName);
                }

                mFiles.RemoveAt(x);
                x--;
            }
        }
Example #57
0
 private void write(string title, IList <Diagnostic> errors)
 {
     if (errors.Count > 0)
     {
         writer.WriteAsync(errors.Count.ToString());
     }
     else
     {
         writer.WriteAsync("No");
     }
     writer.WriteAsync(" error");
     if (errors.Count > 1)
     {
         writer.WriteAsync('s');
     }
     writer.WriteAsync(" in \"");
     writer.WriteAsync(title);
     if (errors.Count > 0)
     {
         writer.WriteLineAsync("\":");
         foreach (var e in errors)
         {
             writer.WriteLine(e.ToString());
         }
     }
     else
     {
         writer.WriteLineAsync("\".");
     }
 }
        private static void ReadSimilarityMatrixToFile(TLSimilarityMatrix similarityMatrix, System.IO.TextWriter writeFile)
        {
            //header
            writeFile.WriteLine("Source Artifact Id,Target Artifact Id,Probability");

            foreach (string sourceArtifact in similarityMatrix.SourceArtifactsIds)
            {
                var traceLinks = similarityMatrix.GetLinksAboveThresholdForSourceArtifact(sourceArtifact);
                traceLinks.Sort();

                foreach (TLSingleLink link in traceLinks)
                {
                    writeFile.WriteLine("{0},{1},{2}", link.SourceArtifactId, link.TargetArtifactId, link.Score);
                }
            }
        }
Example #59
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();
            }
        }
Example #60
0
        public void GerandoArquivoLogPeloServico(string strDescrição)
        {
            try
            {
                DateTime data = DateTime.Now;

                string CaminhoArquivoLog = "";
                CaminhoArquivoLog = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory.ToString()) + "\\..\\..\\..\\..\\Modulos\\Log\\Log-" + data.ToString("dd-MM-yyyy") + ".txt";

                if (!System.IO.File.Exists(CaminhoArquivoLog))
                {
                    FileStream   file = new FileStream(CaminhoArquivoLog, FileMode.Create);
                    BinaryWriter bw   = new BinaryWriter(file);
                    bw.Close();
                }

                string nomeArquivo           = CaminhoArquivoLog;
                System.IO.TextWriter arquivo = System.IO.File.AppendText(nomeArquivo);

                // Agora é só sair escrevendo
                arquivo.WriteLine(data.ToString("HH:mm:ss") + " - " + strDescrição);

                arquivo.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }