Exemple #1
1
        public void NormalSectionAndKey() {
            StringWriter writer = new StringWriter();
            writer.WriteLine("[Logging]");
            writer.WriteLine(" great logger =   log4net  ");
            writer.WriteLine("  [Pets] ; pets comment  ");
            IniReader reader = new IniReader(new StringReader(writer.ToString()));

            Assert.AreEqual(IniReadState.Initial, reader.ReadState);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniReadState.Interactive, reader.ReadState);
            Assert.AreEqual(IniType.Section, reader.Type);
            Assert.AreEqual("Logging", reader.Name);
            Assert.AreEqual("", reader.Value);
            Assert.IsNull(reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Key, reader.Type);
            Assert.AreEqual("great logger", reader.Name);
            Assert.AreEqual("log4net", reader.Value);
            Assert.AreEqual(null, reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Section, reader.Type);
            Assert.AreEqual("Pets", reader.Name);
            Assert.AreEqual("", reader.Value);
            Assert.IsNull(reader.Comment);
        }
Exemple #2
0
 public virtual void Dump(StringWriter sw)
 {
     string s0 = @"        [Embed(source=""" + Path + @""", symbol=""" + SymbolName + @""")]";
     string s1 = @"        public var " + SymbolName + ":Class";
     sw.WriteLine(s0);
     sw.WriteLine(s1);
 }
        //Export  data to csv

        public void exportToCsv()
        {
            System.IO.StringWriter sw = new System.IO.StringWriter();

            sw.WriteLine("\"Code Exemplaire\",\"Designation\",\"Prix\",\"Suivi\",\"Localisation\",\"Statut\",\"Entree en Service\",\"Fin de Service\"");

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=exportedExemplaires.csv");
            Response.ContentType = "application/ms-excel";


            var exemplaires = db.Exemplaires;

            foreach (var exemplaire in exemplaires)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\"",

                                           exemplaire.exemplaireCODE,
                                           exemplaire.designation,
                                           exemplaire.prix,
                                           exemplaire.suivi,
                                           exemplaire.location,
                                           exemplaire.typelocation,
                                           exemplaire.statut,
                                           exemplaire.Date_ES,
                                           exemplaire.Date_FS)
                             );
            }
            Response.Write(sw.ToString());
            Response.End();
        }
Exemple #4
0
        protected void Gettxt()
        {
            Model.Feedback      feedback        = new Model.Feedback();
            BLL.FeedbackManager feedbackManager = new BLL.FeedbackManager();
            DataSet             ds = feedbackManager.GetTXTList();

            Response.Clear();
            Response.Buffer  = false;
            Response.Charset = "utf - 8";
            DateTime dt  = System.DateTime.Now;
            string   str = dt.ToString("yyyyMMddhhmmss");

            Response.AppendHeader("Content-Disposition", "attachment;filename=" + str + ".txt");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.ContentType     = "application/ms-txt";
            Response.Write("<meta http-equiv=Content-Type;content=/text/html;charset=utf-8/>");

            System.IO.StringWriter sw = new System.IO.StringWriter();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    sw.WriteLine(ds.Tables[0].Rows[i][j].ToString().Trim() + "\t");
                }
                sw.WriteLine("\r \n");
            }
            HttpContext.Current.Response.Write(sw.ToString());
            sw.Close();
            HttpContext.Current.Response.End();
        }
Exemple #5
0
        public void NormalComment() {
            StringWriter writer = new StringWriter();
            writer.WriteLine("");
            writer.WriteLine(" ; Something");
            writer.WriteLine(" ;   Some comment  ");
            writer.WriteLine(" ;");
            IniReader reader = new IniReader(new StringReader(writer.ToString()));

            Assert.AreEqual(IniReadState.Initial, reader.ReadState);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniReadState.Interactive, reader.ReadState);
            Assert.AreEqual(IniType.Empty, reader.Type);
            Assert.AreEqual("", reader.Name);
            Assert.AreEqual(null, reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Empty, reader.Type);
            Assert.AreEqual("Something", reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Empty, reader.Type);
            Assert.AreEqual("Some comment", reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual("", reader.Comment);

            Assert.IsFalse(reader.Read());
        }
Exemple #6
0
        private void AddPrerequisiteFile(IO.StringWriter writer, string regRootKey, string regSubKey, string regValueName)
        {
            if (PrerequisiteFile == null)
            {
                return;
            }

            if (PrerequisiteRegKeyValue != null)
            {
                writer.WriteLine($"!insertmacro REG_KEY_VALUE_EXISTS {regRootKey} \"{regSubKey}\" \"{regValueName}\"");
                writer.WriteLine("IfErrors 0 primary");
            }

            var arguments = PrerequisiteFileArguments;

            if (PrerequisiteFileOptionName != null)
            {
                writer.WriteLine($"${{GetOptions}} \"$R0\" \"{PrerequisiteFileOptionName}\" $R1");
                arguments = AppendArgument(arguments, "$R1");
            }

            AddFileCommand(writer, PrerequisiteFile);
            AddExecuteCommand(writer, IO.Path.GetFileName(PrerequisiteFile), arguments, null);

            if (PrerequisiteRegKeyValue != null && !DoNotPostVerifyPrerequisite)
            {
                writer.WriteLine($"!insertmacro REG_KEY_VALUE_EXISTS {regRootKey} \"{regSubKey}\" \"{regValueName}\"");
                writer.WriteLine("IfErrors end 0");
            }
        }
Exemple #7
0
        public ActionResult GetFixtureReport(SportCategoryID SC)
        {
            List<FixturesReport> report = reportRep.GetFixtureReport(SC.SportCategory, SC.Date.Date);
            SportCategoryRepository screp = new SportCategoryRepository();
            StringWriter sw = new StringWriter();
            sw.WriteLine("\"StartTime\",\"TeamA\",\"TeamsB\",\"Field\",\"FixtureId\"");

            string name = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=Fixture" + "_" + name + ".csv");
            Response.ContentType = "text/csv";

            sw.WriteLine("\"Fixtures\"");
            sw.WriteLine(SC.SportCategory);
            sw.WriteLine(SC.Date.Date);

            foreach (FixturesReport ex in report)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\""
                                      , ex.StartTime
                                      , ex.TeamIdA
                                      , ex.TeamIdB
                                      , ex.Field
                                      , ex.FixturesId
                                      ));
            }

            Response.Write(sw.ToString());
            Response.End();
            return null;
        }
Exemple #8
0
    protected void exportFile_ServerClick(object sender, EventArgs e)
    {
        string group = group_id.Value;

        if (string.IsNullOrEmpty(group))
        {
            return;
        }
        GROUPMEMDETAIL[] detail = GetGroupDetail(ToUInt(group));
        if (detail != null)
        {
            System.IO.StringWriter swCSV = new System.IO.StringWriter();
            swCSV.WriteLine("姓名,学号,班级,学院");
            for (int i = 0; i < detail.Length; i++)
            {
                GROUPMEMDETAIL            mb     = detail[i];
                System.Text.StringBuilder sbText = new System.Text.StringBuilder();
                sbText = AppendCSVFields(sbText, mb.szTrueName);
                sbText = AppendCSVFields(sbText, mb.szPID);
                sbText = AppendCSVFields(sbText, mb.szClassName);
                sbText = AppendCSVFields(sbText, mb.szDeptName);
                //去掉尾部的逗号
                sbText.Remove(sbText.Length - 1, 1);
                //写datatable的一行
                swCSV.WriteLine(sbText.ToString());
            }
            DownloadFile(Response, swCSV.GetStringBuilder(), "成员名单.csv");
            swCSV.Close();
            Response.End();
        }
    }
Exemple #9
0
        private static void AppendIL(MethodInfo method, StringWriter sw, ITypeFactory typeFactory)
        {
            var reader = ILReaderFactory.Create(method);
            var exceptions = reader.ILProvider.GetExceptionInfos();
            var writer = new RichILStringToTextWriter(sw, exceptions);

            sw.WriteLine(".method " + method.ToIL());
            sw.WriteLine("{");
            sw.WriteLine("  .maxstack " + reader.ILProvider.MaxStackSize);

            var sig = reader.ILProvider.GetLocalSignature();
            var lsp = new LocalsSignatureParser(reader.Resolver, typeFactory);
            var locals = default(Type[]);
            if (lsp.Parse(sig, out locals) && locals.Length > 0)
            {
                sw.WriteLine("  .locals init (");

                for (var i = 0; i < locals.Length; i++)
                {
                    sw.WriteLine($"    [{i}] {locals[i].ToIL()}{(i != locals.Length - 1 ? "," : "")}");
                }

                sw.WriteLine("  )");
            }

            sw.WriteLine();

            writer.Indent();
            reader.Accept(new ReadableILStringVisitor(writer));
            writer.Dedent();

            sw.WriteLine("}");
        }
        /// <summary>
        /// Gera o arquivo de retorno de carga quando a partir de um arquivo que já foi gerado
        /// </summary>
        /// <param name="idArquivo"></param>
        /// <returns></returns>
        public StringWriter GeraArquivoRetornoCarga(int idArquivo)
        {
            try
            {
                using (StringWriter sw = new StringWriter(new System.Globalization.CultureInfo("pt-BR")))
                {
                    //Gero Cabeçalho
                    sw.WriteLine(ACSOPRGCR_RCabecalhoBD.ConsultaPorIdArquivo(idArquivo).ToString());

                    //Gero Lote
                    sw.WriteLine(ACSOPRGCR_RLoteBD.ConsultaPorIdArquivo(idArquivo).ToString());

                    //Gero detalhe
                    foreach (var det in ACSOPRGCR_RDetalheBD.ConsultaPorIdArquivo(idArquivo))
                        sw.WriteLine(det.ToString());

                    //Gero Rodapé
                    sw.WriteLine(ACSOPRGCR_RRodapeBD.ConsultaPorIdArquivo(idArquivo));

                    return sw;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void Merge() {
            StringWriter textWriter = new StringWriter();
            XmlTextWriter xmlWriter = NiniWriter(textWriter);
            WriteSection(xmlWriter, "Pets");
            WriteKey(xmlWriter, "cat", "muffy");
            WriteKey(xmlWriter, "dog", "rover");
            WriteKey(xmlWriter, "bird", "tweety");
            xmlWriter.WriteEndDocument();

            StringReader reader = new StringReader(textWriter.ToString());
            XmlTextReader xmlReader = new XmlTextReader(reader);
            XmlConfigSource xmlSource = new XmlConfigSource(xmlReader);

            StringWriter writer = new StringWriter();
            writer.WriteLine("[People]");
            writer.WriteLine(" woman = Jane");
            writer.WriteLine(" man = John");
            IniConfigSource iniSource =
                new IniConfigSource(new StringReader(writer.ToString()));

            xmlSource.Merge(iniSource);

            IConfig config = xmlSource.Configs["Pets"];
            Assert.AreEqual(3, config.GetKeys().Length);
            Assert.AreEqual("muffy", config.Get("cat"));
            Assert.AreEqual("rover", config.Get("dog"));

            config = xmlSource.Configs["People"];
            Assert.AreEqual(2, config.GetKeys().Length);
            Assert.AreEqual("Jane", config.Get("woman"));
            Assert.AreEqual("John", config.Get("man"));
        }
Exemple #12
0
        private void ExportClientsListToCSV(List<Models.StockIndi> vLiIndi)
        {
            StringWriter sw = new StringWriter();

            sw.WriteLine("\"TxnDate\",\"DealStockCnt\",\"DealStockAmt\",\"OpenPrice\",\"HighPrice\",\"LowPrice\",\"ClosePrice\",\"PriceDiff\",\"DealCount\"");

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=TW_Stock_Indi.csv");
            Response.ContentType = "text/csv";


            foreach (var line in vLiIndi)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\"",
                                            line.TxnDate,
                                            line.DealStockCnt,
                                            line.DealStockAmt,
                                            line.OpenPrice,
                                            line.HighPrice,
                                            line.LowPrice,
                                            line.ClosePrice,
                                            line.PriceDiff,
                                            line.DealCount
                                            ));
            }

            Response.Write(sw.ToString());

            Response.End();
        }
        public void AddNewConfigsAndKeys()
        {
            // Add some new configs and keys here and test.
            StringWriter writer = new StringWriter ();
            writer.WriteLine ("[Pets]");
            writer.WriteLine (" cat = muffy");
            writer.WriteLine (" dog = rover");
            IniConfigSource source = new IniConfigSource
                                    (new StringReader (writer.ToString ()));

            IConfig config = source.Configs["Pets"];
            Assert.AreEqual ("Pets", config.Name);
            Assert.AreEqual (2, config.GetKeys ().Length);

            IConfig newConfig = source.AddConfig ("NewTest");
            newConfig.Set ("Author", "Brent");
            newConfig.Set ("Birthday", "February 8th");

            newConfig = source.AddConfig ("AnotherNew");

            Assert.AreEqual (3, source.Configs.Count);
            config = source.Configs["NewTest"];
            Assert.IsNotNull (config);
            Assert.AreEqual (2, config.GetKeys ().Length);
            Assert.AreEqual ("February 8th", config.Get ("Birthday"));
            Assert.AreEqual ("Brent", config.Get ("Author"));
        }
        public ActionResult GetOrdervsGRVReport(DateTimeFromToQuery ins)
        {
            List<OrdervsGRVReport> report = reportrepo.GetOrdervsGRVReport(ins);

            StringWriter sw = new StringWriter();
            sw.WriteLine("\"Day\",\"Date\",\"Order Total\",\"Friday Total\",\"GRV Total\",\"Friday Total\"");

            string name = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=OrdervsGRV_" + name + ".csv");
            Response.ContentType = "text/csv";

            foreach (OrdervsGRVReport ex in report)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\"",
                                           ex.Day
                                           , ex.Date
                                           , ex.OrderTotal
                                           , ex.FridayOrderTotal
                                           , ex.GRVTotal
                                           , ex.FridayGRVTotal));
            }

            //Response.ClearContent();
            //Response.AddHeader("content-disposition", "attachment;filename=MemberDetailReport_" + GroupName + "_" + name + ".zip");
            //Response.ContentType = "application/zip";

            Response.Write(sw.ToString());

            Response.End();

            return null;
        }
        /// <summary>
        /// Generates a message saying that the constructor is ambiguous.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="bestDirectives">The best constructor directives.</param>
        /// <returns>The exception message.</returns>
        public static string ConstructorsAmbiguous(IContext context, IGrouping<int, ConstructorInjectionDirective> bestDirectives)
        {
            using (var sw = new StringWriter())
            {
                sw.WriteLine("Error activating {0} using {1}", context.Request.Service.Format(), context.Binding.Format(context));
                sw.WriteLine("Several constructors have the same priority. Please specify the constructor using ToConstructor syntax or add an Inject attribute.");
                sw.WriteLine();

                sw.WriteLine("Constructors:");
                foreach (var constructorInjectionDirective in bestDirectives)
                {
                    FormatConstructor(constructorInjectionDirective.Constructor, sw);
                }

                sw.WriteLine();

                sw.WriteLine("Activation path:");
                sw.WriteLine(context.Request.FormatActivationPath());

                sw.WriteLine("Suggestions:");
                sw.WriteLine("  1) Ensure that the implementation type has a public constructor.");
                sw.WriteLine("  2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.");

                return sw.ToString();
            }
        }
Exemple #16
0
        /* upload a file from a shared directory to Riskmaster for the HR Interface based on configurable values */
        private string runHRInterfaceRiskmasterFTP(Session ftpSession)
        {
            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            String sourceDirectory           = Program.appSettings.Settings["RiskMasterLocalDirectory"].Value;
            String archiveDirectory          = Program.appSettings.Settings["RiskMasterArchiveDirectory"].Value;
            String riskMasterRemoteDirectory = Program.appSettings.Settings["RiskMasterRemoteDirectory"].Value;
            String hrInterfaceFilename       = Program.appSettings.Settings["HRInterfaceFilename"].Value;
            String fileToFTP = Path.Combine(sourceDirectory, hrInterfaceFilename);

            strWriter.WriteLine("BEGIN runHRInterfaceRiskmasterFTP " + currentDateTimeString);
            if (File.Exists(fileToFTP))
            {
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode      = WinSCP.TransferMode.Binary;
                transferOptions.OverwriteMode     = WinSCP.OverwriteMode.Overwrite;
                transferOptions.PreserveTimestamp = true;

                // make a copy of the HRInterface file for archival and auditing purposes
                string hrInterfaceArchiveFilename = hrInterfaceFilename + "-" + currentDateString;
                string hrInterfaceArchiveFile     = Path.Combine(archiveDirectory, hrInterfaceArchiveFilename);
                File.Copy(fileToFTP, hrInterfaceArchiveFile, true);
                strWriter.WriteLine("Copied " + hrInterfaceArchiveFilename + " to " + archiveDirectory);
                /* capture console/standard out from the ftp session to a string to be written after all is done */

                Console.SetOut(strWriter);
                ftpSession.PutFileToDirectory(fileToFTP, riskMasterRemoteDirectory, false, transferOptions);

                strWriter.WriteLine("END runHRInterfaceRiskmasterFTP");
            }
            else
            {
                strWriter.WriteLine("END runHRInterfaceRiskmasterFTP " + fileToFTP + " file does not exist.");
            }
            return(strWriter.ToString());
        }
        public static byte[] Create(HttpCode httpCode, string content, bool closeConnection = false)
        {
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}");

                sw.WriteLine($"Date: {DateTime.Now.ToUniversalTime():r}");
                sw.WriteLine("Server: Arctium-Emulation");
                sw.WriteLine("Retry-After: 600");
                sw.WriteLine($"Content-Length: {content.Length}");
                sw.WriteLine("Vary: Accept-Encoding");

                if (closeConnection)
                    sw.WriteLine("Connection: close");

                sw.WriteLine("Content-Type: application/json;charset=UTF-8");
                sw.WriteLine();

                sw.WriteLine(content);
            }

            return Encoding.UTF8.GetBytes(sb.ToString());
        }
Exemple #18
0
 public static void Write(StringWriter writer, string script)
 {
     var text = GetText(script);
     writer.WriteLine(text);
     writer.WriteLine();
     writer.WriteLine();
 }
Exemple #19
0
        private string levelIndention()
        {
            var lines = _writer.ToString().ReadLines().ToArray();
            if (!lines.Any()) return string.Empty;

            var indention = lines.Where(x => x.IsNotEmpty()).Min(s => s.LeadingSpaces());

            if (indention == 0) return _writer.ToString();

            var writer = new StringWriter();
            foreach (var line in lines)
            {
                if (line.IsEmpty())
                {
                    writer.WriteLine();
                }
                else
                {
                    writer.WriteLine(line.Substring(indention));
                }
                
            }

            return writer.ToString();
        }
        public static async Task<UpdateOutputLogCommand> CreateAsync(IStorageBlockBlob outputBlob,
            string existingContents, Func<string, CancellationToken, Task> uploadCommand,
            CancellationToken cancellationToken)
        {
            if (outputBlob == null)
            {
                throw new ArgumentNullException("outputBlob");
            }
            else if (uploadCommand == null)
            {
                throw new ArgumentNullException("uploadCommand");
            }

            StringWriter innerWriter = new StringWriter();

            if (existingContents != null)
            {
                // This can happen if the function was running previously and the 
                // node crashed. Save previous output, could be useful for diagnostics.
                innerWriter.WriteLine("Previous execution information:");
                innerWriter.WriteLine(existingContents);

                var lastTime = await GetBlobModifiedUtcTimeAsync(outputBlob, cancellationToken);
                if (lastTime.HasValue)
                {
                    var delta = DateTime.UtcNow - lastTime.Value;
                    innerWriter.WriteLine("... Last write at {0}, {1} ago", lastTime, delta);
                }

                innerWriter.WriteLine("========================");
            }

            return new UpdateOutputLogCommand(innerWriter, uploadCommand);
        }
Exemple #21
0
        public static string GetIL(this LambdaExpression expression, bool appendInnerLambdas = false)
        {
            Delegate d = expression.Compile();

            MethodInfo method = d.GetMethodInfo();
            ITypeFactory typeFactory = GetTypeFactory(expression);

            var sw = new StringWriter();

            AppendIL(method, sw, typeFactory);

            if (appendInnerLambdas)
            {
                var closure = (Closure)d.Target;

                int i = 0;
                foreach (object constant in closure.Constants)
                {
                    var innerMethod = constant as DynamicMethod;
                    if (innerMethod != null)
                    {
                        sw.WriteLine();
                        sw.WriteLine("// closure.Constants[" + i + "]");
                        AppendIL(innerMethod, sw, typeFactory);
                    }

                    i++;
                }
            }

            return sw.ToString();
        }
Exemple #22
0
		/*----------------------------------------------------------------------------------------*/
		public static string Context(IContext context)
		{
			using (var sw = new StringWriter())
			{
				if (context.IsRoot)
				{
					sw.Write("active request for {0}", Type(context.Service));
				}
				else
				{
					sw.Write("passive injection of service {0} into {1}", Type(context.Service),
						InjectionRequest(context));
				}

				if (context.HasDebugInfo)
				{
					sw.WriteLine();
					sw.Write("     from {0}", context.DebugInfo);
				}

				if (context.Binding != null)
				{
					sw.WriteLine();
					sw.Write("     using {0}", Binding(context.Binding));

					if (context.Binding.HasDebugInfo)
					{
						sw.WriteLine();
						sw.Write("     declared by {0}", context.Binding.DebugInfo);
					}
				}

				return sw.ToString();
			}
		}
Exemple #23
0
        public override void Log(ILogEntry logEntry)
        {
            Ensure.ArgumentNotNull(() => logEntry);
            Ensure.TypeSupported(() => logEntry, typeof(LogEntry));

            var entry = (LogEntry)logEntry;;

            if (IsLoggable(entry.Level))
            {
                var writer = new StringWriter();

                writer.WriteLine("Message: {0}", entry.Message);
                writer.WriteLine("Event Id: {0}", entry.EventId);
                writer.WriteLine("Priority: {0}", entry.Priority);

                if (entry.Exception != null)
                {
                    var formatter = ExceptionFormatterFactory.Get(entry.Exception.GetType());

                    formatter.Write(entry.Exception, writer);
                }

                var eventId = entry.EventId is int ? (int)entry.EventId : _defaultEventId;

                LogInternal(entry.Level, eventId, writer.ToString());
            }
        }
 // First Header  | Second Header | Third Header
 // ------------- | ------------- | ------------
 // Content Cell  | Content Cell  | Content Cell
 // Content Cell  | Content Cell  | Content Cell
 public static string ProcessTables(string content, MarkdownWebPage page) {
     return Regex.Replace(content,
         @"[\r\n]+((.*?)\s+\|\s+)+(.*?)\s*" +
         @"[\r\n]+((-+?)\s+\|\s+)+(-+?)\s*" +
         @"[\r\n]+(((.*?)\s+\|\s+)+(.*?)\s*[\r\n]+)+",
     match => {
         var writer = new StringWriter();
         writer.WriteLine("<table><thead><tr>");
         foreach (Capture header in match.Groups[1].Captures) {
             var headerVal = header.Value.Trim();
             writer.WriteLine("    <td>" + headerVal.Substring(0, headerVal.Length - 1) + "</td>");
         }
         writer.WriteLine("    <td>" + match.Groups[3].Value.Trim() + "</td>");
         writer.WriteLine("</tr></thead><tbody>");
         var rows = match.Groups[7].Captures;
         var cells = match.Groups[9].Captures;
         var colCount = cells.Count/rows.Count;
         var i = 0;
         foreach (Capture row in rows) {
             writer.WriteLine("    <tr>");
             for (var j = 0; j < colCount; j++ ) {
                 writer.WriteLine("        <td>" + cells[colCount * i + j] + "</td>");
             }
             writer.WriteLine("        <td>" + match.Groups[10].Captures[i++] + "</td>");
             writer.WriteLine("    </tr>");
         }
         writer.WriteLine("</tbody></table>");
         writer.WriteLine("");
         return writer.ToString();
     }
     , RegexOptions.Multiline);
 }
		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public override string ToString()
		{
			StringWriter sw = new StringWriter();
			sw.WriteLine("Could not find {0} attribute",this.Message);
			sw.WriteLine(base.ToString());
			return sw.ToString();
		}
Exemple #26
0
        private void AddPrerequisiteFile(IO.StringWriter writer, string regRootKey, string regSubKey, string regValueName)
        {
            if (Prerequisite.FileName == null)
            {
                return;
            }

            if (Prerequisite.RegKeyValue != null)
            {
                writer.WriteLine($"!insertmacro REG_KEY_VALUE_EXISTS {regRootKey} \"{regSubKey}\" \"{regValueName}\"");
                writer.WriteLine("IfErrors 0 primary");
            }

            string arguments = null;

            if (Prerequisite.OptionName != null)
            {
                writer.WriteLine($"${{GetOptions}} \"$R0\" \"{Prerequisite.OptionName}\" $R1");
                arguments = "$R1";
            }

            AddPayloads(writer, Prerequisite.Payloads);
            AddFileCommand(writer, Prerequisite.FileName);
            AddExecuteCommand(writer, Prerequisite, arguments, "$0");

            if (Prerequisite.RegKeyValue != null && Prerequisite.PostVerify)
            {
                writer.WriteLine($"!insertmacro REG_KEY_VALUE_EXISTS {regRootKey} \"{regSubKey}\" \"{regValueName}\"");
                writer.WriteLine("IfErrors end 0");
            }
        }
Exemple #27
0
        public static string CreateBooCode(CompilerErrorCollection errors,
                CompilerWarningCollection warnings,
                Module module,
                IList<ICSharpCode.NRefactory.ISpecial> specials)
        {
            using (StringWriter w = new StringWriter())
            {
                foreach (CompilerError error in errors)
                {
                    w.WriteLine("ERROR: " + error.ToString());
                }
                if (errors.Count > 0)
                    w.WriteLine();
                foreach (CompilerWarning warning in warnings)
                {
                    w.WriteLine("# WARNING: " + warning.ToString());
                }

                if (warnings.Count > 0)
                    w.WriteLine();

                BooPrinterVisitorWithComments printer = new BooPrinterVisitorWithComments(specials, w);
                printer.OnModule(module);
                printer.Finish();
                return w.ToString();
            }
        }
        void Database.DeleteAndReCreateFromFile( string filePath, bool keepDbInStandbyMode )
        {
            using( var sw = new StringWriter() ) {
                sw.WriteLine( "DROP DATABASE IF EXISTS {0};".FormatWith( info.Database ) );
                sw.WriteLine( "CREATE DATABASE {0};".FormatWith( info.Database ) );
                sw.WriteLine( "use {0}".FormatWith( info.Database ) );
                sw.Write( File.ReadAllText( filePath ) );
                sw.WriteLine( "quit" );

                executeMethodWithDbExceptionHandling(
                    delegate {
                        try {
                            EwlStatics.RunProgram(
                                EwlStatics.CombinePaths( binFolderPath, "mysql" ),
                                getHostAndAuthenticationArguments() + " --disable-reconnect --batch --disable-auto-rehash",
                                sw.ToString(),
                                true );
                        }
                        catch( Exception e ) {
                            if( e.Message.Contains( "ERROR" ) && e.Message.Contains( "at line" ) )
                                throw new UserCorrectableException( "Failed to create database from file. Please try the operation again after obtaining a new database file.", e );
                            throw DataAccessMethods.CreateDbConnectionException( info, "re-creating (from file)", e );
                        }
                    } );
            }
        }
Exemple #29
0
    private StringWriter GetPrefabsXML(LevelObject[] prefabs)
    {
        var xml = new System.IO.StringWriter();

        xml.WriteLine(string.Format(@"<level name=""{0}"" nextlevel=""{1}"" challengetime=""{2}"" levelnumber=""{3}""  cameraSize=""{4}"" memekoForce=""{5}"" maxturns=""{6}""  >", levelName, nextlevel, challengeTime, levelNumber, cameraSize, memekoForce, maxturns));

        foreach (LevelObject prefab in prefabs)
        {
            string position = prefab.transform.position.x + "," + prefab.transform.position.y + "," +
                              prefab.transform.position.z;
            string rotation = prefab.transform.localEulerAngles.x + "," + prefab.transform.localEulerAngles.y + "," +
                              prefab.transform.localEulerAngles.z;
            string scale = prefab.transform.localScale.x + "," + prefab.transform.localScale.y + "," +
                           prefab.transform.localScale.z;

            if (prefab.type == LevelObjectType.Text)
            {
                string textmessage = prefab.GetComponent <TextMesh>().text;
                xml.WriteLine(string.Format(@"<prefab name=""{0}"" position=""{1}"" rotation=""{2}"" scale=""{3}"" type=""{4}"" text=""{5}"" />",
                                            prefab.name, position, rotation, scale, prefab.type.ToString(), textmessage));
            }
            else
            {
                xml.WriteLine(string.Format(@"<prefab name=""{0}"" position=""{1}"" rotation=""{2}"" scale=""{3}"" type=""{4}"" />",
                                            prefab.name, position, rotation, scale, prefab.type.ToString()));
            }
        }

        xml.WriteLine(string.Format(@"</level>"));
        return(xml);
    }
Exemple #30
0
        public void LoadTest()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);

            writer.WriteLine("key1=value1");
            writer.WriteLine("key2 = on");
            writer.WriteLine("key3= true");
            writer.Flush();

            MemoryStream stream = new MemoryStream(Encoding.GetEncoding("ISO-8859-1").GetBytes(sb.ToString()));

            DbConfig config = DbConfig.Empty;
            config.Load(stream);

            string value = config.GetValue<string>("key1");
            Assert.IsNotNull(value, "The 'key1' was not set into the config.");
            Assert.IsNotEmpty(value, "The value of 'key1' is empty.");
            Assert.AreEqual("value1", value, "The value for 'key1' is not correct.");

            value = config.GetValue<string>("key2");
            Assert.IsNotNull(value, "The 'key2' was not set into the config.");
            Assert.IsNotEmpty(value, "The value of 'key2' is empty.");
            Assert.AreEqual("on", value, "The value for 'key2' is not correct.");

            value = config.GetValue<string>("key3");
            Assert.IsNotNull(value, "The 'key3' was not set into the config.");
            Assert.IsNotEmpty(value, "The value of 'key3' is empty.");
            Assert.AreEqual("true", value, "The value for 'key1' is not correct.");
        }
Exemple #31
0
        static Program()
        {
            //this needs to be done before the warnings/errors show up
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //http://www.codeproject.com/Articles/310675/AppDomain-AssemblyResolve-Event-Tips
#if WINDOWS
            //try loading libraries we know we'll need
            //something in the winforms, etc. code below will cause .net to popup a missing msvcr100.dll in case that one's missing
            //but oddly it lets us proceed and we'll then catch it here
            var  d3dx9 = Win32.LoadLibrary("d3dx9_43.dll");
            var  vc2015 = Win32.LoadLibrary("vcruntime140.dll");
            var  vc2010 = Win32.LoadLibrary("msvcr100.dll");            //TODO - check version?
            var  vc2010p = Win32.LoadLibrary("msvcp100.dll");
            bool fail = false, warn = false;
            warn |= d3dx9 == IntPtr.Zero;
            fail |= vc2015 == IntPtr.Zero;
            fail |= vc2010 == IntPtr.Zero;
            fail |= vc2010p == IntPtr.Zero;
            if (fail || warn)
            {
                var sw = new System.IO.StringWriter();
                sw.WriteLine("[ OK ] .Net 4.0 (You couldn't even get here without it)");
                sw.WriteLine("[{0}] Direct3d 9", d3dx9 == IntPtr.Zero ? "FAIL" : " OK ");
                sw.WriteLine("[{0}] Visual C++ 2010 SP1 Runtime", (vc2010 == IntPtr.Zero || vc2010p == IntPtr.Zero) ? "FAIL" : " OK ");
                sw.WriteLine("[{0}] Visual C++ 2015 Runtime", (vc2015 == IntPtr.Zero) ? "FAIL" : " OK ");
                var str = sw.ToString();
                var box = new BizHawk.Client.EmuHawk.CustomControls.PrereqsAlert(!fail);
                box.textBox1.Text = str;
                box.ShowDialog();
                if (!fail)
                {
                }
                else
                {
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
            }

            Win32.FreeLibrary(d3dx9);
            Win32.FreeLibrary(vc2015);
            Win32.FreeLibrary(vc2010);
            Win32.FreeLibrary(vc2010p);

            // this will look in subdirectory "dll" to load pinvoked stuff
            string dllDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll");
            SetDllDirectory(dllDir);

            //in case assembly resolution fails, such as if we moved them into the dll subdiretory, this event handler can reroute to them
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            //but before we even try doing that, whack the MOTW from everything in that directory (thats a dll)
            //otherwise, some people will have crashes at boot-up due to .net security disliking MOTW.
            //some people are getting MOTW through a combination of browser used to download bizhawk, and program used to dearchive it
            WhackAllMOTW(dllDir);

            //We need to do it here too... otherwise people get exceptions when externaltools we distribute try to startup
#endif
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            {
                ASSERTREQ   vrParameter = new ASSERTREQ();
                UNIASSERT[] vrResult;
                if (m_Request.Assert.AssertGet(vrParameter, out vrResult) == REQUESTCODE.EXECUTE_SUCCESS)
                {
                    System.IO.StringWriter swCSV = new System.IO.StringWriter();
                    swCSV.WriteLine("资产编号,资产名称,规格型号,单价,采购日期,所属实验室,所属部门");
                    for (int i = 0; i < vrResult.Length; i++)
                    {
                        System.Text.StringBuilder sbText = new System.Text.StringBuilder();
                        sbText = AppendCSVFields(sbText, vrResult[i].szAssertSN.ToString());
                        sbText = AppendCSVFields(sbText, vrResult[i].szDevName.ToString());
                        sbText = AppendCSVFields(sbText, vrResult[i].szModel.ToString());
                        sbText = AppendCSVFields(sbText, vrResult[i].dwUnitPrice.ToString());
                        sbText = AppendCSVFields(sbText, GetDateStr(vrResult[i].dwPurchaseDate));
                        sbText = AppendCSVFields(sbText, vrResult[i].szRoomName.ToString());
                        sbText = AppendCSVFields(sbText, vrResult[i].szDeptName.ToString());
                        //去掉尾部的逗号
                        sbText.Remove(sbText.Length - 1, 1);

                        //写datatable的一行
                        swCSV.WriteLine(sbText.ToString());
                    }
                    DownloadFile(Response, swCSV.GetStringBuilder(), "RuleDaySum.csv");
                    swCSV.Close();
                    Response.End();
                }
            }
        }
    }
Exemple #33
0
        private static void Process(ScgiConnection conn)
        {
            conn.ReadRequestAsync ().ContinueWith (tread =>
            {
                if (tread.IsFaulted)
                    Console.WriteLine (tread.Exception);
                var req = tread.Result;
                var echoResponse = new StringWriter ();
                echoResponse.WriteLine ("Method: {0}\nPath: {1}\nQueryString: {2}\nLocalPort: {3}\nRemoteAddress: {4}\nRemotePort: {5}\nScheme: {6}", req.Method, req.Path, req.QueryString, req.LocalPort, req.RemoteAddress, req.RemotePort, req.Scheme);

                echoResponse.WriteLine ("\nHeaders");
                foreach (var header in req.Headers)
                {
                    echoResponse.Write ("{0}:", header.Key);
                    foreach (var v in header.Value)
                        echoResponse.WriteLine ("\t{0}", v);
                }

                return conn.SendResponse (HttpStatusCode.OK, new Dictionary<string, string> (), Encoding.UTF8.GetBytes (echoResponse.ToString ()));
            }).Unwrap ().ContinueWith (tres =>
                {
                    if (tres.IsFaulted)
                        Console.WriteLine (tres.Exception);
                    conn.Close ();
                    conn.Dispose ();
                });
        }
        //-------------------------------------------------------------------------------------------------//
        /// <summary>
        /// Create a string which represents the experiment specification. Each line contains two fields
        /// which are the name of the field and its value. The format of the string will be different
        /// for comma-seperated-values and applet parameters.
        /// </summary>
        /// <param name="xmlNodeExperimentResult"></param>
        /// <param name="swArgument"></param>
        /// <returns></returns>
        public string CreateSpecificationString(ResultInfo resultInfo, string swArgument)
        {
            StringWriter sw = new StringWriter();
            try
            {
                if (resultInfo.setupId.Equals(LabConsts.STRXML_SetupId_NTPServer))
                {
                    if (resultInfo.title != null)
                    {
                        // Write the server url
                        sw.WriteLine(swArgument, LabConsts.STR_Server_Url, resultInfo.serverUrl);
                    }
                    else
                    {
                        // Previous version - write the server name
                        sw.WriteLine(swArgument, LabConsts.STR_TimeServer, resultInfo.serverName);
                    }
                }

                // Write the format name
                sw.WriteLine(swArgument, LabConsts.STR_TimeFormat, resultInfo.formatName);
            }
            catch (Exception ex)
            {
                Logfile.WriteError(ex.Message);
            }

            return sw.ToString();
        }
        //-------------------------------------------------------------------------------------------------//
        /// <summary>
        /// Create a string which represents the experiment specification. Each line contains two fields
        /// which are the name of the field and its value. The format of the string will be different
        /// for comma-seperated-values and applet parameters.
        /// </summary>
        /// <param name="xmlNodeExperimentResult"></param>
        /// <param name="swArgument"></param>
        /// <returns></returns>
        public string CreateSpecificationString(ResultInfo resultInfo, string swArgument)
        {
            StringWriter sw = new StringWriter();
            try
            {
                if (resultInfo.setupId.Equals(LabConsts.STRXML_SetupId_VoltageVsSpeed) == true ||
                    resultInfo.setupId.Equals(LabConsts.STRXML_SetupId_SpeedVsVoltage) == true)
                {
                    sw.WriteLine(swArgument, LabConsts.STR_MinSpeed, resultInfo.speedMin);
                    sw.WriteLine(swArgument, LabConsts.STR_MaxSpeed, resultInfo.speedMax);
                    sw.WriteLine(swArgument, LabConsts.STR_SpeedStep, resultInfo.speedStep);
                }
                else if (resultInfo.setupId.Equals(LabConsts.STRXML_SetupId_VoltageVsField) == true ||
                    resultInfo.setupId.Equals(LabConsts.STRXML_SetupId_SpeedVsField) == true)
                {
                    sw.WriteLine(swArgument, LabConsts.STR_MinField, resultInfo.fieldMin);
                    sw.WriteLine(swArgument, LabConsts.STR_MaxField, resultInfo.fieldMax);
                    sw.WriteLine(swArgument, LabConsts.STR_FieldStep, resultInfo.fieldStep);
                }
                else if (resultInfo.setupId.Equals(LabConsts.STRXML_SetupId_VoltageVsLoad) == true)
                {
                    sw.WriteLine(swArgument, LabConsts.STR_MinLoad, resultInfo.loadMin);
                    sw.WriteLine(swArgument, LabConsts.STR_MaxLoad, resultInfo.loadMax);
                    sw.WriteLine(swArgument, LabConsts.STR_LoadStep, resultInfo.loadStep);
                }
            }
            catch (Exception ex)
            {
                Logfile.WriteError(ex.Message);
            }

            return sw.ToString();
        }
        public void ConvertDialogScriptToRealScript(Dialog dialog, Game game, CompileMessages errors)
        {
            string thisLine;
            _currentlyInsideCodeArea = false;
            _hadFirstEntryPoint = false;
            _game = game;
            _currentDialog = dialog;
            _existingEntryPoints.Clear();
            _currentLineNumber = 0;

            StringReader sr = new StringReader(dialog.Script);
            StringWriter sw = new StringWriter();
            sw.Write(string.Format("function _run_dialog{0}(int entryPoint) {1} ", dialog.ID, "{"));
            while ((thisLine = sr.ReadLine()) != null)
            {
                _currentLineNumber++;
                try
                {
                    ConvertDialogScriptLine(thisLine, sw, errors);
                }
                catch (CompileMessage ex)
                {
                    errors.Add(ex);
                }
            }
            if (_currentlyInsideCodeArea)
            {
                sw.WriteLine("}");
            }
            sw.WriteLine("return RUN_DIALOG_RETURN; }"); // end the function
            dialog.CachedConvertedScript = sw.ToString();
            sw.Close();
            sr.Close();
        }
        public void Write(DdlRules rules, StringWriter writer)
        {

            if (rules.TableCreation == CreationStyle.DropThenCreate)
            {
                writer.WriteLine("DROP TABLE IF EXISTS {0} CASCADE;", Table.QualifiedName);
                writer.WriteLine("CREATE TABLE {0} (", Table.QualifiedName);
            }
            else
            {
                writer.WriteLine("CREATE TABLE IF NOT EXISTS {0} (", Table.QualifiedName);
            }

            var length = Columns.Select(x => x.Name.Length).Max() + 4;

            Columns.Each(col =>
            {
                writer.Write($"    {col.ToDeclaration(length)}");
                if (col == Columns.Last())
                {
                    writer.WriteLine();
                }
                else
                {
                    writer.WriteLine(",");
                }
            });

            writer.WriteLine(");");

            rules.GrantToRoles.Each(role =>
            {
                writer.WriteLine($"GRANT SELECT ({Columns.Select(x => x.Name).Join(", ")}) ON TABLE {Table.QualifiedName} TO \"{role}\";");
            });
        }
        public void StorageUsed()
        {
            var observer = new StorageObserver("mva2015logs");
            var random = new Random();
            var writer = new StringWriter();
            writer.WriteLine("StoreTime;Storage;Bytes");
            var minute = 0;
            while (true)
            {
                var size = random.Next(10000, 50000);
                writer.WriteLine("{0};{1};{2}", DateTime.Now.ToUniversalTime(), _name, size);

                var delay = random.Next(1000, 2000);
                System.Threading.Thread.Sleep(delay);
                minute += delay;
                if (minute > 60000) {
                    writer.Close();
                    observer.OnNext(new CsvEvent {
                        Data = DateTime.UtcNow
                        ,
                        Csv = writer.ToString()
                    });
                    writer = new StringWriter();
                    writer.WriteLine("StoreTime;Storage;Bytes");
                    minute = 0;
                }
            }
        }
 public string FormatControlFlowGraph(ControlFlowGraph cfg)
 {
     StringWriter writer = new StringWriter();
     foreach (InstructionBlock block in cfg.Blocks)
     {
         writer.WriteLine("block {0}:", block.Index);
         writer.WriteLine("\tbody:");
         foreach (Instruction instruction in block)
         {
             writer.Write("\t\t");
             InstructionData data = cfg.GetData(instruction);
             writer.Write("[{0}:{1}] ", data.StackBefore, data.StackAfter);
             Formatter.WriteInstruction(writer, instruction);
             writer.WriteLine();
         }
         InstructionBlock[] successors = block.Successors;
         if (successors.Length > 0)
         {
             writer.WriteLine("\tsuccessors:");
             foreach (InstructionBlock block2 in successors)
             {
                 writer.WriteLine("\t\tblock {0}", block2.Index);
             }
         }
     }
     return writer.ToString();
 }
Exemple #40
0
    // <Snippet1>
    // This function takes arguments for 2 connection strings and commands to create a transaction
    // involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the
    // transaction is rolled back. To test this code, you can connect to two different databases
    // on the same server by altering the connection string, or to another 3rd party RDBMS by
    // altering the code in the connection2 code block.
    static public int CreateTransactionScope(
        string connectString1, string connectString2,
        string commandText1, string commandText2)
    {
        // Initialize the return value to zero and create a StringWriter to display results.
        int returnValue = 0;

        System.IO.StringWriter writer = new System.IO.StringWriter();

        try
        {
            // Create the TransactionScope to execute the commands, guaranteeing
            // that both commands can commit or roll back as a single unit of work.
            using (TransactionScope scope = new TransactionScope())
            {
                using (SqlConnection connection1 = new SqlConnection(connectString1))
                {
                    // Opening the connection automatically enlists it in the
                    // TransactionScope as a lightweight transaction.
                    connection1.Open();

                    // Create the SqlCommand object and execute the first command.
                    SqlCommand command1 = new SqlCommand(commandText1, connection1);
                    returnValue = command1.ExecuteNonQuery();
                    writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

                    // If you get here, this means that command1 succeeded. By nesting
                    // the using block for connection2 inside that of connection1, you
                    // conserve server and network resources as connection2 is opened
                    // only when there is a chance that the transaction can commit.
                    using (SqlConnection connection2 = new SqlConnection(connectString2))
                    {
                        // The transaction is escalated to a full distributed
                        // transaction when connection2 is opened.
                        connection2.Open();

                        // Execute the second command in the second database.
                        returnValue = 0;
                        SqlCommand command2 = new SqlCommand(commandText2, connection2);
                        returnValue = command2.ExecuteNonQuery();
                        writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
                    }
                }

                // The Complete method commits the transaction. If an exception has been thrown,
                // Complete is not  called and the transaction is rolled back.
                scope.Complete();
            }
        }
        catch (TransactionAbortedException ex)
        {
            writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
        }

        // Display messages.
        Console.WriteLine(writer.ToString());

        return(returnValue);
    }
Exemple #41
0
        public static void WriteRelationships(TopicRequest request)
        {
            var @ns       = Path.GetFileName(request.RootDirectory);
            var className = request.TopicName + "TopicRegistry";

            var writer = new StringWriter();

            writer.WriteLine("namespace {0}", @ns);
            writer.WriteLine("{");
            writer.WriteLine("    public class {0} : {1}", className, typeof(TopicRegistry).FullName);
            writer.WriteLine("    {");

            writer.WriteLine("        public {0}()", className);
            writer.WriteLine("        {");

            writeRelationships(writer, request);

            writer.WriteLine("        }");
            writer.WriteLine("    }");
            writer.WriteLine("}");

            var path = request.RootDirectory.AppendPath(className + ".cs");

            Console.WriteLine("Writing the topic registry to " + path);
            new FileSystem().WriteStringToFile(path, writer.ToString());
        }
Exemple #42
0
        private void TestEscaping <T>(T formatter, IRdfReader parser, char[] cs) where T : INodeFormatter, ITripleFormatter
        {
            Graph    g     = new Graph();
            IUriNode subj  = g.CreateUriNode(new Uri("http://example.org/subject"));
            IUriNode pred  = g.CreateUriNode(new Uri("http://example.org/predicate"));
            IUriNode pred2 = g.CreateUriNode(new Uri("http://example.org/predicate2"));

            foreach (String value in this._values)
            {
                //Do Escaping and Checking
                Console.WriteLine("Original Value - " + value);
                String temp = value.EscapeBackslashes(cs);
                Console.WriteLine("Backslash Escaped Value - " + temp);
                INode obj = g.CreateLiteralNode(temp);
                Console.WriteLine("Formatted Value - " + formatter.Format(obj));
                this.CheckEscapes(temp, cs);

                //Can only do round-trip checking if an RDF format
                if (parser != null)
                {
                    //Now generate a Triple, save in a String and then re-parse to check for round trip value equality
                    Triple tOrig = new Triple(subj, pred, obj);
                    System.IO.StringWriter writer = new System.IO.StringWriter();
                    writer.WriteLine(formatter.Format(tOrig));
                    Triple t2Orig = new Triple(subj, pred2, g.CreateLiteralNode(value));
                    writer.WriteLine(formatter.Format(t2Orig));

                    Console.WriteLine("Serialized Output");
                    Console.WriteLine(writer.ToString());

                    StringParser.Parse(g, writer.ToString(), parser);
                    Triple t = g.Triples.FirstOrDefault();
                    if (t == null)
                    {
                        Assert.Fail("Failed to parse a Triple");
                    }

                    Triple t2 = g.Triples.LastOrDefault();
                    if (t2 == null)
                    {
                        Assert.Fail("Failed to parse a Triple");
                    }
                    if (ReferenceEquals(t, t2))
                    {
                        Assert.Fail("Failed to generate two Triples");
                    }

                    Assert.AreEqual(t2.Object, t.Object);
                }

                Console.WriteLine();

                g.Clear();
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            {
                REPORTREQ  vrParameter = new REPORTREQ();
                USERSTAT[] vrResult;
                vrParameter.dwStartDate = DateToUint(Request["dwStartDate"]);
                vrParameter.dwEndDate   = DateToUint(Request["dwEndDate"]);
                string szKey = Request["orderkey"];
                if (szKey == null)
                {
                    vrParameter.szReqExtInfo.szOrderKey  = "dwUseTime";
                    vrParameter.szReqExtInfo.szOrderMode = "desc";
                }
                else
                {
                    vrParameter.szReqExtInfo.szOrderKey  = szKey;
                    vrParameter.szReqExtInfo.szOrderMode = "desc";
                }

                if (m_Request.Report.GetUserStat(vrParameter, out vrResult) == REQUESTCODE.EXECUTE_SUCCESS)
                {
                    System.IO.StringWriter swCSV = new System.IO.StringWriter();
                    swCSV.WriteLine("学工号,姓名,班级,学院,使用次数,使用总时间");
                    for (int i = 0; i < vrResult.Length; i++)
                    {
                        System.Text.StringBuilder sbText = new System.Text.StringBuilder();
                        string szClassName = "";
                        sbText = AppendCSVFields(sbText, vrResult[i].szPID.ToString());
                        sbText = AppendCSVFields(sbText, vrResult[i].szTrueName.ToString());
                        UNIACCOUNT accinfo;
                        if (GetAccByAccno(vrResult[i].dwAccNo.ToString(), out accinfo))
                        {
                            szClassName = accinfo.szClassName.ToString();
                        }

                        sbText = AppendCSVFields(sbText, szClassName.ToString());
                        sbText = AppendCSVFields(sbText, vrResult[i].szDeptName.ToString());
                        sbText = AppendCSVFields(sbText, vrResult[i].dwUseTimes.ToString());
                        uint uUseTime = (uint)vrResult[i].dwUseTime;
                        sbText = AppendCSVFields(sbText, uUseTime / 60 + "小时" + uUseTime % 60 + "分钟");
                        //去掉尾部的逗号
                        sbText.Remove(sbText.Length - 1, 1);

                        //写datatable的一行
                        swCSV.WriteLine(sbText.ToString());
                    }
                    DownloadFile(Response, swCSV.GetStringBuilder(), "RuleDaySum.csv");
                    swCSV.Close();
                    Response.End();
                }
            }
        }
    }
Exemple #44
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            REQUESTCODE  uResponse   = REQUESTCODE.EXECUTE_FAIL;
            ATTENDRECREQ vrParameter = new ATTENDRECREQ();

            GetHTTPObj(out vrParameter);
            if (vrParameter.dwStartDate == 0)
            {
                vrParameter.dwStartDate = null;
            }
            if (vrParameter.dwEndDate == 0)
            {
                vrParameter.dwEndDate = null;
            }
            //  if(vrParameter.dwStartDate=)
            uint uAttend = Parse(Request["attendid"]);
            if (uAttend != 0)
            {
                vrParameter.dwAttendID = uAttend;
            }

            ATTENDREC[] vrResult;
            uResponse = m_Request.Attendance.GetAttendRec(vrParameter, out vrResult);
            if (uResponse == REQUESTCODE.EXECUTE_SUCCESS && vrResult != null && vrResult.Length > 0)
            {
                System.IO.StringWriter swCSV = new System.IO.StringWriter();
                swCSV.WriteLine("学工号,姓名,考勤规则,出勤日期,考勤房间,进入时间,退出时间,最近一次进入时间,停留时间(分钟),刷卡次数,状态");
                for (int i = 0; i < vrResult.Length; i++)
                {
                    System.Text.StringBuilder sbText = new System.Text.StringBuilder();
                    sbText = AppendCSVFields(sbText, vrResult[i].szPID);
                    sbText = AppendCSVFields(sbText, vrResult[i].szTrueName);
                    sbText = AppendCSVFields(sbText, vrResult[i].szAttendName.ToString());
                    sbText = AppendCSVFields(sbText, GetDateStr(vrResult[i].dwAttendDate));
                    sbText = AppendCSVFields(sbText, (vrResult[i].szRoomName));
                    sbText = AppendCSVFields(sbText, Get1970Date(vrResult[i].dwInTime));
                    sbText = AppendCSVFields(sbText, Get1970Date(vrResult[i].dwOutTime));
                    sbText = AppendCSVFields(sbText, Get1970Date(vrResult[i].dwLatestInTime));
                    sbText = AppendCSVFields(sbText, (vrResult[i].dwStayMin).ToString());
                    sbText = AppendCSVFields(sbText, (vrResult[i].dwCardTimes).ToString());
                    sbText = AppendCSVFields(sbText, GetJustName(vrResult[i].dwAttendStat, "attendstatus"));
                    sbText.Remove(sbText.Length - 1, 1);

                    //写datatable的一行
                    swCSV.WriteLine(sbText.ToString());
                }
                DownloadFile(Response, swCSV.GetStringBuilder(), "attendrec.csv");
                swCSV.Close();
                Response.End();
            }
        }
    }
        private void AddIncludes(IO.StringWriter writer)
        {
            writer.WriteLine("!include LogicLib.nsh");
            writer.WriteLine("!include x64.nsh");
            writer.WriteLine("!include FileFunc.nsh");

            if (OSValidation.Any)
            {
                writer.WriteLine("!include WinVer.nsh");
            }
        }
Exemple #46
0
 private void AddSplashScreen(IO.StringWriter writer)
 {
     if (SplashScreen != null)
     {
         AddFileCommand(writer, SplashScreen.FileName);
         writer.WriteLine($@"splash::show {SplashScreen.Delay.TotalMilliseconds} ""{PluginsDir}\{IO.Path.GetFileNameWithoutExtension(SplashScreen.FileName)}""");
         // $0 has '1' if the user closed the splash screen early,
         // '0' if everything closed normally, and '-1' if some error occurred.
         writer.WriteLine("Pop $0");
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            TEACHINGRESVREQ vrParameter = new TEACHINGRESVREQ();
            TEACHINGRESV[]  vrResult;
            vrParameter.dwBeginDate = Parse(DateTime.Now.ToString("yyyyMMdd"));
            vrParameter.dwEndDate   = Parse(DateTime.Now.ToString("yyyyMMdd"));
            uint uTeachid = Parse(Request["dwTeacherID"]);
            if (uTeachid != 0)
            {
                vrParameter.dwTeacherID = uTeachid;
            }
            uint dwCourseID = Parse(Request["dwCourseID"]);
            if (uTeachid != 0)
            {
                vrParameter.dwCourseID = dwCourseID;
            }
            System.IO.StringWriter swCSV = new System.IO.StringWriter();
            swCSV.WriteLine("课程名,教师,房间,班级,应到人数,目前人数,上课时间");
            if (m_Request.Reserve.GetTeachingResv(vrParameter, out vrResult) == REQUESTCODE.EXECUTE_SUCCESS)
            {
                for (int i = 0; i < vrResult.Length; i++)
                {
                    System.Text.StringBuilder sbText = new System.Text.StringBuilder();

                    sbText = AppendCSVFields(sbText, vrResult[i].szCourseName);
                    sbText = AppendCSVFields(sbText, vrResult[i].szTeacherName);
                    RESVDEV[] resvDev    = vrResult[i].ResvDev;
                    string    szRoomName = "";
                    for (int k = 0; resvDev != null && k < resvDev.Length; k++)
                    {
                        szRoomName += resvDev[k].szRoomName + ",";
                    }
                    sbText = AppendCSVFields(sbText, szRoomName);
                    sbText = AppendCSVFields(sbText, vrResult[i].szGroupName);
                    sbText = AppendCSVFields(sbText, vrResult[i].dwGroupUsers.ToString());
                    sbText = AppendCSVFields(sbText, vrResult[i].dwCurUsers.ToString());
                    sbText = AppendCSVFields(sbText, GetTeachingTime((uint)vrResult[i].dwTeachingTime));

                    //去掉尾部的逗号
                    sbText.Remove(sbText.Length - 1, 1);

                    //写datatable的一行
                    swCSV.WriteLine(sbText.ToString());
                }


                DownloadFile(Response, swCSV.GetStringBuilder(), "teachplan.csv");
                swCSV.Close();
                Response.End();
            }
        }
    }
        static Class1()
        {
            // Create test writer object to hold expected output
            System.IO.StringWriter expectedOut = new System.IO.StringWriter();

            // Write expected output to string writer object
            expectedOut.WriteLine("In catch 1 File x not found");
            expectedOut.WriteLine("In main's catch File x not found");

            // Create and initialize test log object
            testLog = new TestUtil.TestLog(expectedOut);
        }
Exemple #49
0
    static a()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine("In middle method, throwing");
        expectedOut.WriteLine("Caught");
        expectedOut.WriteLine("Pass");

        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }
Exemple #50
0
        private void BundleMinifier_ErrorMinifyingFile(object sender, MinifyFileEventArgs e)
        {
            var logger    = Hood.Core.Engine.Services.Resolve <ILogService>();
            var logWriter = new System.IO.StringWriter();

            logWriter.WriteLine($"Bundle errors from {e.Result.FileName} - {DateTime.UtcNow.ToDisplay()}");
            foreach (var error in e.Result.Errors)
            {
                logWriter.WriteLine($"Line {error.LineNumber} and column {error.ColumnNumber}: {error.Message}");
            }
            logger.AddLogAsync <PageBuilder>($"Bundle errors from {e.Result.FileName}", logWriter.ToString(), Models.LogType.Error);
            logWriter.Dispose();
        }
Exemple #51
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        var list = (List <string[]>)Session["PersonalList"];

        printinconsoletest(list);

        for (int cv03 = 0; cv03 < list.Count / 6; cv03++)
        {
            System.Diagnostics.Debug.WriteLine("etre3e:" + cv03 + " " + list.Count);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset     = "";
            HttpContext.Current.Response.ContentType = "text/x-vCard";
            string vfilename = "MyContact" + cv03 + ".VCF";
            HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=" + vfilename);
            StringBuilder                strHtmlContent = new StringBuilder();
            System.IO.StringWriter       stringWrite    = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite      = new HtmlTextWriter(stringWrite);
            stringWrite.WriteLine("BEGIN:VCARD");
            stringWrite.WriteLine("VERSION:2.1");


            string vmail     = "";
            string vname     = "";
            string vcno      = "";
            string vcomp     = "";
            string vjobtitle = "";
            string vadd      = "";
            string vcomments = "";



            vcomments = list[0 + 6 * cv03][2];
            vmail     = list[1 + 6 * cv03][2];
            vname     = list[2 + 6 * cv03][2] + " " + list[4 + 6 * cv03][2];
            vcno      = list[3 + 6 * cv03][2];
            vcomp     = "ADDCompanyName";
            vjobtitle = list[5 + 6 * cv03][2];
            vadd      = "ADDAddress1";

            stringWrite.WriteLine("FN:" + vcomments);
            stringWrite.WriteLine("NOTE:" + vname);
            stringWrite.WriteLine("Email:" + vmail);
            stringWrite.WriteLine("ORG:" + vcomp);
            stringWrite.WriteLine("TITLE:" + vjobtitle);
            stringWrite.WriteLine("ADR;WORK;ENCODING=QUOTED-PRINTABLE:" + vadd);


            stringWrite.WriteLine("END:VCARD");
            HttpContext.Current.Response.Write(stringWrite.ToString());
            HttpContext.Current.Response.End();
            System.Diagnostics.Debug.WriteLine("eteliose");
        }

        /////////////////////
    }
Exemple #52
0
    static simple()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine("Begin test...");
        expectedOut.WriteLine("In main try");
        expectedOut.WriteLine("In main catch");
        expectedOut.WriteLine("In inner try");
        expectedOut.WriteLine("End test...");
        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }
        public FractronAboutBox()
        {
            InitializeComponent();
            this.Text = String.Format("About {0}", AssemblyTitle);

            this.labelVersion.Text   = String.Format("Version {0}", FractronConfig.VersionString);
            this.labelCopyright.Text = AssemblyCopyright;

            System.IO.StringWriter desc = new System.IO.StringWriter();
            desc.WriteLine(Narratives.Info_Description);
            desc.WriteLine();
            desc.WriteLine(Narratives.Info_LicenseBrief);
            this.licenseBriefLabel.Text = Narratives.Info_LicenseBrief;
        }
    static Test()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine(" try");
        expectedOut.WriteLine("\t try");
        expectedOut.WriteLine("\t finally");
        expectedOut.WriteLine(" catch");

        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }
Exemple #55
0
    static a()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine("Main: In Try");
        expectedOut.WriteLine("In try");
        expectedOut.WriteLine("In finally");
        expectedOut.WriteLine("Main: Caught the exception");

        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }
    static Class1()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine("in main try");
        expectedOut.WriteLine("  in middle1 try");
        expectedOut.WriteLine("  in middle1 finally");
        expectedOut.WriteLine("in main catch");

        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }
Exemple #57
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            {
                RESVKINDSTATREQ vrParameter = new RESVKINDSTATREQ();
                uint            uKind       = Parse(Request["Kind"]);
                CODINGTABLE[]   vtCode      = null;
                if (uKind == 1)
                {
                    vtCode = getCodeTableByType((uint)CODINGTABLE.DWCODETYPE.CODE_RESVKIND);
                    vrParameter.dwPurpose = (uint)UNIRESERVE.DWPURPOSE.USEFOR_PERSONNAL + (uint)UNIRESERVE.DWPURPOSE.USEFOR_STUDYROOM;
                }
                else if (uKind == 2)
                {
                    vtCode = getCodeTableByType((uint)CODINGTABLE.DWCODETYPE.CODE_ACTIVITYKIND);
                    vrParameter.dwPurpose = (uint)UNIRESERVE.DWPURPOSE.USEFOR_ACTIVITY;
                }
                vrParameter.szReqExtInfo.dwNeedLines = 1000000;
                vrParameter.szReqExtInfo.dwStartLine = 0;
                RESVKINDSTAT[] vrResult;
                vrParameter.dwStartDate = DateToUint(Request["dwStartDate"]);
                vrParameter.dwEndDate   = DateToUint(Request["dwEndDate"]);

                if (m_Request.Report.GetResvKindStat(vrParameter, out vrResult) == REQUESTCODE.EXECUTE_SUCCESS)
                {
                    System.IO.StringWriter swCSV = new System.IO.StringWriter();
                    swCSV.WriteLine("类型,预约次数,预约总时间");
                    for (int i = 0; i < vrResult.Length; i++)
                    {
                        System.Text.StringBuilder sbText = new System.Text.StringBuilder();
                        sbText = AppendCSVFields(sbText, GetCode(vtCode, (uint)vrResult[i].dwKind));
                        sbText = AppendCSVFields(sbText, vrResult[i].dwResvTimes.ToString());

                        sbText = AppendCSVFields(sbText, vrResult[i].dwResvMinutes.ToString());

                        //去掉尾部的逗号
                        sbText.Remove(sbText.Length - 1, 1);

                        //写datatable的一行
                        swCSV.WriteLine(sbText.ToString());
                    }
                    DownloadFile(Response, swCSV.GetStringBuilder(), "RuleDaySum.csv");
                    swCSV.Close();
                    Response.End();
                }
            }
        }
    }
Exemple #58
0
    static a()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine("In outer try");
        expectedOut.WriteLine("In outer finally");
        expectedOut.WriteLine("In inner try");
        expectedOut.WriteLine("In inner finally");
        expectedOut.WriteLine("Pass");

        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }
    static Class1()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine("Caught an exception");
        expectedOut.WriteLine("In finally, i = 3");
        expectedOut.WriteLine("In finally, i = 4");
        expectedOut.WriteLine("In finally, i = 5");
        expectedOut.WriteLine("In finally, i = 6");

        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }
Exemple #60
0
    static Test()
    {
        // Create test writer object to hold expected output
        System.IO.StringWriter expectedOut = new System.IO.StringWriter();

        // Write expected output to string writer object
        expectedOut.WriteLine("in the try block");
        expectedOut.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15} {16} {17} {18}  {19} {20} {21} {22} {23} {24} {25} {26} {27} {28} {29} {30} {31} {32} ", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33);
        expectedOut.WriteLine("Expected Test Exception");
        expectedOut.WriteLine("in catch now");
        expectedOut.WriteLine("in finally now");

        // Create and initialize test log object
        testLog = new TestUtil.TestLog(expectedOut);
    }