Write() public method

public Write ( char value ) : void
value char
return void
Beispiel #1
1
        /// <summary>
        /// Converts a timestamp  specified in seconds/nanoseconds to a string.
        /// </summary>
        /// <remarks>
        /// If the value is a normalized duration in the range described in <c>field_mask.proto</c>,
        /// <paramref name="diagnosticOnly"/> is ignored. Otherwise, if the parameter is <c>true</c>,
        /// a JSON object with a warning is returned; if it is <c>false</c>, an <see cref="InvalidOperationException"/> is thrown.
        /// </remarks>
        /// <param name="paths">Paths in the field mask</param>
        /// <param name="diagnosticOnly">Determines the handling of non-normalized values</param>
        /// <exception cref="InvalidOperationException">The represented field mask is invalid, and <paramref name="diagnosticOnly"/> is <c>false</c>.</exception>
        internal static string ToJson(IList<string> paths, bool diagnosticOnly)
        {
            var firstInvalid = paths.FirstOrDefault(p => !ValidatePath(p));
            if (firstInvalid == null)
            {
                var writer = new StringWriter();
#if DOTNET35
                var query = paths.Select(JsonFormatter.ToJsonName);
                JsonFormatter.WriteString(writer, string.Join(",", query.ToArray()));
#else
                JsonFormatter.WriteString(writer, string.Join(",", paths.Select(JsonFormatter.ToJsonName)));
#endif
                return writer.ToString();
            }
            else
            {
                if (diagnosticOnly)
                {
                    var writer = new StringWriter();
                    writer.Write("{ \"@warning\": \"Invalid FieldMask\", \"paths\": ");
                    JsonFormatter.Default.WriteList(writer, (IList)paths);
                    writer.Write(" }");
                    return writer.ToString();
                }
                else
                {
                    throw new InvalidOperationException($"Invalid field mask to be converted to JSON: {firstInvalid}");
                }
            }
        }
Beispiel #2
1
		public static string GetHtml (string url, HelpSource helpSource, out Node match)
		{
			string htmlContent = null;
			match = null;
			
			if (helpSource != null)
				htmlContent = AppDelegate.Root.RenderUrl (url, generator, out match, helpSource);
			if (htmlContent == null) {
				// the displayed url have a lower case type code (e.g. t: instead of T:) which confuse monodoc
				if (url.Length > 2 && url[1] == ':')
					url = char.ToUpperInvariant (url[0]) + url.Substring (1);
				// It may also be url encoded so decode it
				url = Uri.UnescapeDataString (url);
				htmlContent = AppDelegate.Root.RenderUrl (url, generator, out match, helpSource);
				if (htmlContent != null && match != null && match.Tree != null)
					helpSource = match.Tree.HelpSource;
			}
			if (htmlContent == null)
				return null;
			
			var html = new StringWriter ();
   			html.Write ("<html>\n<head><title>{0}</title>", url);
			
			if (helpSource != null) {
				if (HtmlGenerator.InlineCss != null)
                    html.Write (" <style type=\"text/css\">{0}</style>\n", HtmlGenerator.InlineCss);
				/*if (helpSource.InlineJavaScript != null)
                    html.Write ("<script type=\"text/JavaScript\">{0}</script>\n", helpSource.InlineJavaScript);*/
            }

            html.Write ("</head><body>");
            html.Write (htmlContent);
            html.Write ("</body></html>\n");
            return html.ToString ();
		}
        protected string InjectAssets(string markup, Match match)
        {
            if (match == null)
            {
                return markup;
            }

            using (var writer = new StringWriter())
            {
                writer.Write(markup.Substring(0, match.Index));

                WriteLinks(writer, @"<link type=""text/css"" rel=""stylesheet"" href=""{0}"" />",
                           Compressor.CompressCss(GetSources(CssLinks)));
                WriteInlines(writer, "<style>", "</style>", CssInlines);
                WriteLinks(writer, @"<script type=""text/javascript"" src=""{0}""></script>",
                           Compressor.CompressJavascript(GetSources(JavascriptLinks)));
                WriteInlines(writer, @"<script type=""text/javascript"">", "</script>", JavascriptInlines);

                WriteInlines(
                    writer,
                    @"<script type=""text/javascript"">jQuery(document).ready(function () {",
                    "});</script>",
                    DomReadyInlines);

                writer.Write(markup.Substring(match.Index));
                return writer.ToString();
            }
        }
Beispiel #4
0
        public override void Insert(IDbAccesser dba, Entity item)
        {
            var idColumn = this.IdentityColumn;
            if (idColumn != null)
            {
                if (_selectSEQSql == null)
                {
                    var seqName = new StringWriter();
                    seqName.Write("SEQ_");
                    this.AppendPrepare(seqName, this.Name);
                    seqName.Write('_');
                    this.AppendPrepare(seqName, idColumn.Name);
                    var seqNameValue = Rafy.DbMigration.Oracle.OracleMigrationProvider.LimitOracleIdentifier(seqName.ToString());

                    //此序列是由 DbMigration 中自动生成的。
                    _selectSEQSql = string.Format(@"SELECT {0}.NEXTVAL FROM DUAL", seqNameValue);
                }
                //由于默认可能不是 int 类型,所以需要类型转换。
                var value = dba.RawAccesser.QueryValue(_selectSEQSql);
                value = TypeHelper.CoerceValue(item.KeyProvider.KeyType, value);
                idColumn.LoadValue(item, value);

                //如果实体的 Id 是在插入的过程中生成的,
                //那么需要在插入组合子对象前,先把新生成的父对象 Id 都同步到子列表中。
                item.SyncIdToChildren();
            }

            base.Insert(dba, item);
        }
        public void TestWrite() {
                StringWriter writer = new StringWriter();

                Assert.AreEqual (String.Empty, writer.ToString());
                
                writer.Write( 'A' );
                Assert.AreEqual ("A", writer.ToString());

                writer.Write( " foo" );
                Assert.AreEqual ("A foo", writer.ToString());

                
                char[] testBuffer = "Test String".ToCharArray();

                writer.Write( testBuffer, 0, 4 );
                Assert.AreEqual ("A fooTest", writer.ToString());

                writer.Write( testBuffer, 5, 6 );
                Assert.AreEqual ("A fooTestString", writer.ToString());

		writer = new StringWriter ();
                writer.Write(null as string);
                Assert.AreEqual ("", writer.ToString());

        }
        public void TestCultureInfoConstructor() {

		StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
		Assert.IsNotNull (writer.GetStringBuilder());
		
		Assert.AreEqual (String.Empty, writer.ToString());
		
		writer.Write( 'A' );
		Assert.AreEqual ("A", writer.ToString());
		
		writer.Write( " foo" );
		Assert.AreEqual ("A foo", writer.ToString());
		
		
		char[] testBuffer = "Test String".ToCharArray();
		
		writer.Write( testBuffer, 0, 4 );
		Assert.AreEqual ("A fooTest", writer.ToString());
		
		writer.Write( testBuffer, 5, 6 );
		Assert.AreEqual ("A fooTestString", writer.ToString());
		
		writer = new StringWriter(CultureInfo.InvariantCulture);
		writer.Write(null as string);
		Assert.AreEqual ("", writer.ToString());
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            StringWriter w = new StringWriter();
            w.WriteLine("Sing a song of {0} pence", 6);
            string s = "A pocket full of rye";
            w.Write(s);
            w.Write(w.NewLine);
            w.Write(string.Format(4 + " and " + 20 + " blackbirds"));
            w.Write(new StringBuilder(" baked in a pie"));
            w.WriteLine();
            Console.WriteLine(w);

            StringBuilder sb = w.GetStringBuilder();
            int i = sb.Length;
            sb.Append("The birds began to sing");
            sb.Insert(i, "when the pie was opened\n");
            sb.AppendFormat("\nWasn't that a {0} to set before the king", "dainty dish");
            Console.WriteLine(w);

            Console.WriteLine();
            StringReader r = new StringReader(w.ToString());
            string t = r.ReadLine();
            Console.WriteLine(t);
            Console.Write((char)r.Read());
            char[] ca = new char[37];
            r.Read(ca, 0, 19);
            Console.Write(ca);
            Console.WriteLine(r.ReadToEnd());

            r.Close();
            w.Close();
            Console.ReadLine();
        }
Beispiel #8
0
        /// <summary>
        /// Converts new lines to break lines.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">text</exception>
        public static string NewLinesToBreakLines(this string text)
        {
            text.ThrowIfNull(nameof(text));

            if (String.IsNullOrWhiteSpace(text))
                return text;

            text = text.Replace(@"\r\n", Environment.NewLine)
                .Replace(@"\r", Environment.NewLine)
                .Replace(@"\n", Environment.NewLine);

            using (StringReader sr = new StringReader(text))
            using (StringWriter sw = new StringWriter(CultureConstants.InvariantCulture))
            {
                //Loop while next character exists
                while (sr.Peek() > -1)
                {
                    // Read a line from the string and writes it to an internal StringBuilder created automatically
                    sw.Write(sr.ReadLine());

                    // Adds an HTML break line as long as it's not the last line
                    if (sr.Peek() > -1)
                        sw.Write("<br>");
                }

                return sw.GetStringBuilder().ToString();
            }
        }
        override protected void SendBuffer(LoggingEvent[] events)
        {

            try
            {
                StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
                string t = Layout.Header;

                if (t != null)
                    writer.Write(t);

                for (int i = 0; i < events.Length; i++)
                {
                    // Render the event and append the text to the buffer
                    RenderLoggingEvent(writer, events[i]);
                }

                t = Layout.Footer;

                if (t != null)
                    writer.Write(t);

                // Use SmtpClient so we can use SSL.
                SmtpClient client = new SmtpClient(SmtpHost, Port);
                client.EnableSsl = true;
                client.Credentials = new NetworkCredential(Username, Password);
                string messageText = writer.ToString();
                MailMessage mail = new MailMessage(From, To, Subject, messageText);
                client.Send(mail);
            }
            catch (Exception e)
            {
                ErrorHandler.Error("Error occurred while sending e-mail notification from SmtpClientSmtpAppender.", e);
            }
        }
        public string Serialize()
        {
            if (Count == 0) {
                return string.Empty;
            }

            if (Count == 1) {
                var first = this.First();
                return string.Format("{0}={1}", first.Key, first.Value);
            }

            using (var writer = new StringWriter()) {
                var first = this.First();
                var firstLine = string.Format("{0}={1};", first.Key, first.Value);
                writer.WriteLine(firstLine);
                for (var i = 1; i < Count; i++) {
                    var parameter = this.ElementAt(i);
                    var nextLine = string.Format(" {0}={1}", parameter.Key, parameter.Value);
                    if (i == Count - 1) {
                        // last
                        writer.Write(nextLine);
                    } else {
                        writer.Write(nextLine);
                        writer.Write(";");
                        writer.Write(Environment.NewLine);
                    }
                }

                return writer.ToString();
            }
        }
		void Run ()
		{
			try {
				using (StreamReader sr = new StreamReader ("downloaded/NormalizationTest.txt")) {
					for (line = 1; sr.Peek () >= 0; line++) {
						ProcessLine (sr.ReadLine ());
					}
				}
			} catch (Exception) {
				Console.Error.WriteLine ("Error at line {0}", line);
				throw;
			}

			TextWriter Output = new StringWriter ();
			foreach (Testcase test in tests) {
				Output.Write ("tests.Add (new Testcase (");
				foreach (string data in test.Data) {
					Output.Write ("\"");
					foreach (char c in data)
						Output.Write ("\\u{0:X04}", (int) c);
					Output.Write ("\", ");
				}
				Output.WriteLine ("{0}));", test.TestType);
			}

			StreamReader template = new StreamReader ("StringNormalizationTestSource.cs");
			string ret = template.ReadToEnd ();
			ret = ret.Replace ("@@@@@@ Replace Here @@@@@@", Output.ToString ());
			Console.WriteLine (ret);
		}
 public void ExecuteCompleted(ExecuteEvent executeEvent)
 {
     Element element = executeEvent.Element;
     if (element.IsNamed("tr"))
     {
         var stringWriter = new StringWriter();
         stringWriter.Write("Execute '");
         var childElements = element.GetChildElements();
         bool firstChild = true;
         foreach (var childElement in childElements)
         {
             if (firstChild)
             {
                 firstChild = false;
             }
             else
             {
                 stringWriter.Write(", ");
             }
             stringWriter.Write(childElement.Text);
         }
         stringWriter.Write("'");
         m_LogWriter.WriteLine(stringWriter.ToString());
     }
     else
     {
         m_LogWriter.WriteLine("Execute '{0}'", element.Text);
     }
 }
        /// <summary>
        /// Use SmtpClient with .EnableSsl = true with UserCredentials
        /// </summary>
        protected override void SendBuffer(LoggingEvent[] events)
        {
            try
            {
                using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
                {
                    if (Layout.Header != null) writer.Write(Layout.Header);

                    foreach (var loggingEvent in events)
                        RenderLoggingEvent(writer, loggingEvent);// Render the event and append the text to the buffer

                    if (Layout.Footer != null) writer.Write(Layout.Footer);

                    var sslClient = new SmtpClient(SmtpHost, Port)
                    {// Use an SSL enabled SmtpClient
                        EnableSsl = true,
                        Credentials = new NetworkCredential(Username, Password)
                    };
                    sslClient.Send(new MailMessage(From, To, Subject, writer.ToString()));
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.Error("Error occurred while sending e-mail notification from SmtpSecureAppender.", ex);
            }
        }
Beispiel #14
0
		public static void Show(Exception e, StackTrace innerStackTrace = null, string customMessage = null)
		{
			var writer = new StringWriter();

			if (customMessage != null)
				WriteCustomMessage(customMessage, writer);
			else
				SetCustomMessageBasedOnTheActualError(writer, e);

			writer.Write("Message: ");
			writer.WriteLine(e.Message);
			if (string.IsNullOrWhiteSpace(UrlUtil.Url) == false)
			{
				writer.Write("Uri: ");
				writer.WriteLine(UrlUtil.Url);
			}
			writer.Write("Server Uri: ");
			writer.WriteLine(GetServerUri(e));

			writer.WriteLine();
			writer.WriteLine("-- Error Information --");
			writer.WriteLine(e.ToString());
			writer.WriteLine();

			if (innerStackTrace != null)
			{
				writer.WriteLine("Inner StackTrace: ");
				writer.WriteLine(innerStackTrace.ToString());
			}
		
			Show(writer.ToString());
		}
        public override string GetSelectCountByKeyQuery(DataRow row)
        {
            StringWriter sw = new StringWriter();
            sw.Write("SELECT COUNT(*) FROM [{0}] WHERE ", this.Table.Table.TableName);
            for (int i = 0; i < this.Unique.Columns.Length; ++i)
            {
                DataColumn column = this.Unique.Columns[i];
                if (i != 0)
                    sw.Write(" AND ");

                if (row[column] is DBNull)
                {
                    sw.Write("{0} IS NULL", column.ColumnName, row[column]);
                    continue;
                }

                if (column.DataType == typeof(string))
                {
                    sw.Write("{0} = '{1}'", column.ColumnName, row[column]);
                    continue;
                }

                sw.Write("{0} = {1}", column.ColumnName, row[column]);
            }

            return sw.ToString();
        }
		public static string GetName(ITypeReference value)
		{
			if (value != null)
			{
				ITypeCollection genericParameters = value.GenericArguments;
				if (genericParameters.Count > 0)
				{
					using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
					{
						for (int i = 0; i < genericParameters.Count; i++)
						{
							if (i != 0)
							{
								writer.Write(",");
							}

							IType genericParameter = genericParameters[i];
							if (genericParameter != null)
							{
								writer.Write(genericParameter.ToString());
							}
						}

						return value.Name + "<" + writer.ToString() + ">";
					}
				}

				return value.Name;
			}

			throw new NotSupportedException();
		}
        protected override void EmitBatch(IEnumerable<LogEvent> events)
        {
            var payload = new StringWriter();
            payload.Write("{\"events\":[");

            var formatter = new JsonFormatter();
            var delimStart = "";
            foreach (var logEvent in events)
            {
                payload.Write(delimStart);
                formatter.Format(logEvent, payload);
                delimStart = ",";
            }

            payload.Write("]}");

            var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
            if (!string.IsNullOrWhiteSpace(_apiKey))
                content.Headers.Add(ApiKeyHeaderName, _apiKey);
    
            var result = _httpClient.PostAsync(BulkUploadResource, content).Result;
            if (!result.IsSuccessStatusCode)
                SelfLog.WriteLine("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result);

            var returned = result.Content.ReadAsStringAsync().Result;
            _minimumAcceptedLevel = SeqApi.ReadEventInputResult(returned);
        }
Beispiel #18
0
        public override void ExecuteResult(ControllerContext context)
        {
            var sw = new StringWriter();

            foreach (var header in ColumnHeaders)
                sw.Write(string.Format("\"{0}\",", header));

            var properties = GetType(Records).GetProperties();

            foreach (var item in Records)
            {
                if (item != null)
                {
                    sw.WriteLine();
                    foreach (var property in properties)
                    {
                        var obj = property.GetValue(item, null);
                        if (obj != null)
                        {
                            var strValue = obj.ToString();
                            sw.Write(string.Format("\"{0}\",", ReplaceSpecialCharacters(strValue)));
                        }
                        else
                            sw.Write("\"\"");
                    }
                }
            }

            WriteFile(FileName, "application/CSV", sw.ToString());
        }
Beispiel #19
0
 public static string Dump(Lexer aLexer)
 {
     using (var xOut = new StringWriter())
     {
         while (true)
         {
             var xToken = aLexer.Scan();
             xOut.Write(xToken.TagValue);
             var xWord = xToken as Word;
             if (xWord != null)
             {
                 xOut.Write("\t");
                 xOut.Write(xWord.Value);
             }
             var xUnknown = xToken as CharToken;
             if (xUnknown != null)
             {
                 xOut.Write("\t");
                 xOut.Write(xUnknown.Value);
             }
             xOut.WriteLine();
             if (xToken.TagValue == Tag.EndOfStream)
             {
                 break;
             }
         }
         return xOut.ToString();
     }
 }
        String IStyleFormatter.Sheet(IEnumerable<IStyleFormattable> rules)
        {
            var sb = Pool.NewStringBuilder();
            var first = true;

            using (var writer = new StringWriter(sb))
            {
                foreach (var rule in rules)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        writer.Write(_newLineString);
                        writer.Write(_newLineString);
                    }

                    rule.ToCss(writer, this);
                }
            }

            return sb.ToPool();
        }
 internal string GenerateDot(Dictionary<string, object> pairs)
 {
     bool flag = false;
     StringWriter writer = new StringWriter();
     foreach (var entry in pairs)
     {
         if (flag)
         {
             writer.Write(", ");
         }
         else
         {
             flag = true;
         }
         if (entry.Value is string)
         {
             writer.Write("{0}=\"{1}\"", entry.Key.ToString(), entry.Value.ToString());
             continue;
         }
         if (entry.Value is GraphvizColor)
         {
             GraphvizColor GraphvizColor = (GraphvizColor) entry.Value;
             writer.Write("{0}=\"#{1}{2}{3}{4}\"", new object[] { entry.Key.ToString(), GraphvizColor.R.ToString("x2").ToUpper(), GraphvizColor.G.ToString("x2").ToUpper(), GraphvizColor.B.ToString("x2").ToUpper(), GraphvizColor.A.ToString("x2").ToUpper() });
             continue;
         }
         if ((entry.Value is GraphvizRankDirection) || (entry.Value is GraphvizPageDirection))
         {
             writer.Write("{0}={1};", entry.Key.ToString(), entry.Value.ToString());
             continue;
         }
         writer.Write(" {0}={1}", entry.Key.ToString(), entry.Value.ToString().ToLower());
     }
     return writer.ToString();
 }
        public void Render(IList<Timeseries> splitPerYear, StringWriter writer)
        {
            WriteSeriesHeaders(splitPerYear, writer);

            for (var i = 0; i < 12; i++)
            {
                var monthNumber = i + 1;
                WriteRowHeader(monthNumber, writer);

                foreach (var series in splitPerYear)
                {
                    var firstMonthInSeries = series[0].Time.Month;
                    var startMonthDelta = firstMonthInSeries - 1;
                    var index = i - startMonthDelta;

                    if (index >= 0 && index < series.Count)
                    {
                        var v = series[index].V;
                        var numberFormat = m_CultureInfo.NumberFormat;
                        var formattedValue = v.ToString(numberFormat);
                        writer.Write(formattedValue);
                    }
                    writer.Write(ColumnSeparator);
                }
                writer.WriteLine();
            }
        }
 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();
 }
 public override string GetArguments(string inputFileName, string outputFileName)
 {
     VideoParameters parms =
         VideoParameterOracle.GetParameters(inputFileName);
     if (parms == null)
         return string.Format(
             "\"{0}\" -o \"{1}\" --videoquality 8 --audioquality 6 --frontend",
             inputFileName, outputFileName);
     else {
         StringBuilder paramsBuilder = new StringBuilder();
         StringWriter paramsWriter = new StringWriter(paramsBuilder);
         if (parms.Height.HasValue && parms.Width.HasValue)
             paramsWriter.Write("-x {0} -y {1} ",
                 parms.Width, parms.Height);
         if (parms.VideoBitrate.HasValue && parms.AudioBitrate.HasValue)
             paramsWriter.Write("-V {0} -A {1} --two-pass ",
                 parms.VideoBitrate, parms.AudioBitrate);
         else
             paramsWriter.Write("--videoquality 8 --audioquality 6 ");
         paramsWriter.Close();
         return string.Format(
             "\"{0}\" -o \"{1}\" {2} --frontend",
                 inputFileName, outputFileName, paramsBuilder.ToString());
     }
 }
Beispiel #25
0
        public override void CreateTable(string tableName, IEnumerable<FieldData> fieldInfos)
        {
            var writer = new StringWriter();
            writer.Write("CREATE TABLE `{0}` (`id` int(11) NOT NULL AUTO_INCREMENT", tableName);
            foreach (var field in fieldInfos)
            {
                if (field.GetField().GetType() == typeof (CharField))
                {
                    writer.Write(", `{0}` varchar(256) NOT NULL", field.GetInfo().Name.ToLower());
                }
                else if (field.GetField().GetType() == typeof(DateTimeField))
                {
                    //updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                    writer.Write(", `{0}` TIMESTAMP DEFAULT CURRENT_TIMESTAMP", field.GetInfo().Name.ToLower());
                }
            }
            writer.Write(", PRIMARY KEY (`id`));");

            var conn = new SQLiteConnection(_connectionStringBuilder.ToString());
            conn.Open();
            var cmd = conn.CreateCommand();
            cmd.CommandText = writer.ToString();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
Beispiel #26
0
        /// <summary>
        /// Send events to Seq.
        /// </summary>
        /// <param name="events">The buffered events to send.</param>
        protected override void SendBuffer(LoggingEvent[] events)
        {
            if (ServerUrl == null)
                return;

            var payload = new StringWriter();
            payload.Write("{\"events\":[");
            LoggingEventFormatter.ToJson(events, payload);
            payload.Write("]}");

            var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
            if (!string.IsNullOrWhiteSpace(ApiKey))
                content.Headers.Add(ApiKeyHeaderName, ApiKey);

            var baseUri = ServerUrl;
            if (!baseUri.EndsWith("/"))
                baseUri += "/";

            using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUri) })
            {
                var result = httpClient.PostAsync(BulkUploadResource, content).Result;
                if (!result.IsSuccessStatusCode)
                    ErrorHandler.Error(string.Format("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result));
            }
        }
Beispiel #27
0
        public static string GetNameWithParameterList(ConstructorInfo mi)
        {
            using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
            {
                writer.Write(mi.Name);
                writer.Write("(");

                ParameterInfo[] parameters = mi.GetParameters();
                for (int i = 0; i < parameters.Length; i++)
                {
                    if (i != 0)
                    {
                        writer.Write(", ");
                    }

                    writer.Write(parameters[i].ParameterType.ToString());
                }

                if (mi.CallingConvention == CallingConventions.VarArgs)
                {
                    if (parameters.Length > 0)
                    {
                        writer.Write(", ");
                    }

                    writer.Write("...");
                }

                writer.Write(")");

                return writer.ToString();
            }
        }
Beispiel #28
0
        public static void ExportAlternates(string path)
        {
            StringBuilder sb = new StringBuilder();

            System.IO.StringWriter sw = new System.IO.StringWriter(sb);

            foreach (string key in _userAllographAlternates.Keys)
            {
                sw.Write(key);
                foreach (Result r in _userAllographAlternates[key])
                {
                    sw.Write("," + r.ToResultCode());
                }
                sw.WriteLine();
            }
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            using (FileStream myStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) {
                StreamWriter sr = new StreamWriter(myStream);
                sr.WriteLine(sb.ToString());
                sr.Flush(); sr.Close();
            }
        }
Beispiel #29
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();
			}
		}
Beispiel #30
0
        static void Main(string[] args)
        {
            StringWriter colorString = new StringWriter();
            Bitmap bitmap = new Bitmap(@"C:\dev\limejs\545\assets\test.png");
            int sizeX = 10;
            int sizeY = 10;

            colorString.Write("[");
            for (int y = 0; y < bitmap.Height; y += sizeY)
                for (int x = 0; x < bitmap.Width; x += sizeX)
                {
                    uint averageR = 0;
                    uint averageG = 0;
                    uint averageB = 0;
                    Color currentColor;

                    for(int innerX = x; innerX < x + sizeX; ++innerX)
                        for (int innerY = y; innerY < y + sizeY; ++innerY)
                        {
                            currentColor = bitmap.GetPixel(innerX, innerY);
                            averageR += currentColor.R;
                            averageG += currentColor.G;
                            averageB += currentColor.B;
                        }

                    averageR /= (uint)(sizeX * sizeY);
                    averageG /= (uint)(sizeX * sizeY);
                    averageB /= (uint)(sizeX * sizeY);

                    colorString.Write("'#" + averageR.ToString("X2") + averageG.ToString("X2") + averageB.ToString("X2") + "',");
                }

            colorString.Write("]");
            Clipboard.SetText(colorString.ToString());
        }
Beispiel #31
0
 private static string GetOfferString(Item item, Offer o, string[] listPrices, string[] salePrices)
 {
     using (StringWriter writer = new StringWriter()) {
         writer.WriteLine("Merchant: " + o.Merchant.Name);
         if (o.Merchant.MerchantId != AmazonComMerchantId)
             writer.WriteLine(
                 "Shipping information by Merchant: http://www.amazon.com/gp/help/seller/shipping.html?seller=" +
                 o.Merchant.MerchantId + "&asin=" + item.ASIN);
         if (o.Merchant.MerchantId == AmazonComMerchantId) {
             if (!o.OfferListing[0].IsEligibleForSuperSaverShipping)
                 writer.Write("Not ");
             writer.WriteLine("Eligible for Super Saver Shipping");
         }
         writer.WriteLine("List Price: " + listPrices[1]);
         if(salePrices != null)
             writer.WriteLine("Sale Price: " + salePrices[1]);
         if (o.OfferListing[0].ShippingCharge != null) {
             writer.Write("Shipping Charge: ");
             foreach (OfferListingShippingCharge charge in o.OfferListing[0].ShippingCharge) {
                 writer.Write("  ");
                 writer.WriteLine(charge.ShippingType + " - " + charge.ShippingPrice.FormattedPrice);
             }
         }
         return writer.ToString();
     }
 }
Beispiel #32
0
        public void TextWriterCanBeLeftOpen(Type writerType)
        {
            var g         = new Graph();
            var writer    = new System.IO.StringWriter();
            var rdfWriter = writerType.GetConstructor(new Type[0]).Invoke(new object[0]) as IRdfWriter;

            rdfWriter.Save(g, writer, true);
            writer.Write("\n"); // This should not throw because the writer is still open
            rdfWriter.Save(g, writer);
            Assert.Throws <ObjectDisposedException>(() => writer.Write("\n"));
        }
Beispiel #33
0
        /// <summary>
        /// 生成不带明细的TXT文件
        /// </summary>
        public static void OutPutTXT(DataTable dt, string Address)
        {
            FileStream fs = new FileStream(Address, FileMode.Create, FileAccess.Write);

            System.IO.StringWriter sw = new System.IO.StringWriter();
            int iColCount             = dt.Columns.Count;

            for (int i = 0; i < iColCount; i++)
            {
                sw.Write("\"" + dt.Columns[i] + "\"");
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
            foreach (DataRow dr in dt.Rows)
            {
                string aa = "";
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        //sw.Write("\"" + dr[i].ToString() + "\"");
                        //aa += "\"" + dr[i].ToString() + "\"";
                        aa += dr[i].ToString();
                    }
                    else
                    {
                        //sw.Write("\"\"");
                        //aa += "\"\"";
                        aa += "";
                    }

                    if (i < iColCount - 1)
                    {
                        //sw.Write(",");
                        aa += ",";
                    }
                }
                //sw.Write(sw.NewLine);
                sw.WriteLine(aa);
            }
            sw.Close();
            StreamWriter sw1 = new StreamWriter(fs, System.Text.Encoding.GetEncoding(("utf-8")));

            sw1.Write(sw);
            sw1.Flush();
            sw1.Close();
            //CommonMethod.OpenFile(Address);
        }
Beispiel #34
0
        private static void ExportTxt(DataTable dt, string prefixname, string encoding, string timeformat)
        {
            if (dt == null || prefixname.Length == 0)
            {
                throw new ArgumentException("待导出的dt为null,无法进行导出!");
                return;
            }
            HttpResponse response = System.Web.HttpContext.Current.Response;
            Encoding     coding   = System.Text.Encoding.GetEncoding(encoding);

            response.HeaderEncoding = coding;
            response.AppendHeader("Content-Disposition", "attachment;filename=" +
                                  System.Web.HttpUtility.UrlEncode(prefixname, coding) + ".txt");
            response.ContentEncoding = coding;

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

            response.ContentType = "text/plain";
            response.Clear();

            foreach (DataColumn dc in dt.Columns)
            {
                oStringWriter.Write(dc.ColumnName + "\t");
            }
            oStringWriter.Write("\r\n");

            foreach (DataRow dr in dt.Rows)
            {
                object cell = null;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    cell = dr.ItemArray[i];
                    if (timeformat.Length > 0 && dt.Columns[i].DataType == typeof(DateTime))
                    {
                        oStringWriter.Write(cell != null && cell != DBNull.Value ? Convert.ToDateTime(cell).ToString(timeformat) + "\t" : "null\t");
                    }
                    else
                    {
                        oStringWriter.Write(cell != null && cell != DBNull.Value ? cell.ToString() + "\t" : "null\t");
                    }
                }

                oStringWriter.Write("\r\n");
            }

            response.Write(oStringWriter.ToString());
            response.End();
        }
 public void ExportarExcel(String nombreArchivo, String tabla)
 {
     try
     {
         HttpContext.Current.Response.Clear();
         HttpContext.Current.Response.Buffer = true;
         HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + nombreArchivo + ".xls");
         HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
         HttpContext.Current.Response.ContentType     = "application/vnd.ms-excel"; //Excel
         System.IO.StringWriter sw = new System.IO.StringWriter();
         sw.WriteLine("<html xmlns='http://www.w3.org/1999/xhtml'>");
         sw.WriteLine("<head>");
         sw.WriteLine("<meta http-equiv='content-type' content='text/html; charset=UTF-8' />");
         sw.WriteLine("<title>");
         sw.WriteLine("Page-");
         sw.WriteLine(Guid.NewGuid().ToString());
         sw.WriteLine("</title>");
         sw.WriteLine("</head>");
         sw.WriteLine("<body>");
         sw.Write(tabla);
         sw.WriteLine("</body>");
         sw.WriteLine("</html>");
         HttpContext.Current.Response.Output.Write(sw.ToString());
         HttpContext.Current.Response.Flush();
         HttpContext.Current.Response.End();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public void GetDataToExport()
        {
            try
            {
                string dataGridID      = Helper.Request(this, "DataGridID");
                string sortField       = Helper.Request(this, "SortField");
                string sortOrder       = Helper.Request(this, "SortOrder");
                string exportType      = Helper.Request(this, "ExportType");
                string searchFiletrs   = Helper.Request(this, "SearchFiletrs");
                string serializeObject = Helper.Request(this, "SerializeObject");
                string toolbarFilters  = Helper.Request(this, "ToolbarFilters");

                GeneralTools.DataGrid.DataGrid dataGrid = ((DataGridSchema)SerializationTools.DeserializeXml(Helper.Decrypt(serializeObject, HttpContext.Current.Session), typeof(DataGridSchema))).GetDataGrid();
                int pageControl = GetPageAssemblyValue(Request.Url.ToString());

                Assembly currentAssembly   = Assembly.GetExecutingAssembly();
                string   pageName          = string.Format("{0}.{1}", currentAssembly.GetName().Name, ((Business.UserControls)pageControl).ToString().Replace('_', '.'));
                Delegate dataBinderHandler = ((UIUserControlBase)Activator.CreateInstance(currentAssembly.GetType(pageName))).GetDataBinder(dataGrid.ID);
                Delegate dataRenderEvent   = ((UIUserControlBase)Activator.CreateInstance(currentAssembly.GetType(pageName))).GetDataRenderHandler(dataGrid.ID);

                string fileName = string.Empty;
                switch (exportType.ToLower())
                {
                case "pdf":
                    fileName = dataGrid.ExportToPdfFile(sortField, sortOrder, searchFiletrs, toolbarFilters, dataBinderHandler, dataRenderEvent);
                    byte[] data = File.ReadAllBytes(fileName);
                    Response.BinaryWrite(data);
                    Response.ContentType = "application/pdf";
                    Response.AppendHeader("content-disposition", "attachment;filename=export.pdf");
                    Response.End();
                    break;

                case "excel":
                    Response.Clear();
                    Response.AddHeader("content-disposition", "attachment;filename=Test.xls");
                    Response.ContentType     = "application/ms-excel";
                    Response.ContentEncoding = System.Text.Encoding.Unicode;
                    Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

                    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
                    string style = @"<style> .textmode { mso-number-format:\@;} </style>";
                    Response.Write(style);
                    stringWriter.Write(dataGrid.ExportToExcel(sortField, sortOrder, searchFiletrs, toolbarFilters, dataBinderHandler, dataRenderEvent));

                    System.Web.UI.HtmlTextWriter htmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
                    this.RenderControl(htmlTextWriter);

                    Response.Write(stringWriter.ToString());
                    Response.End();
                    break;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                Response.End();
            }
        }
        public override void Close()
        {
            if (!_filtered)
            {
                base.Close();
                return;
            }
            if (this.Length == 0)
            {
                _filter.Close();
                base.Close();
                return;
            }

            byte[] bytes;
            string html = _encoding.GetString(this.ToArray());

            int ViewStateStart = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"");

            if (ViewStateStart <= 0)
            {
                bytes = this.ToArray();
            }
            else
            {
                System.IO.StringWriter writer = new System.IO.StringWriter();

                // write the section of html before viewstate
                writer.Write(html.Substring(1, ViewStateStart - 1));

                int ViewStateEnd = html.IndexOf("/>", ViewStateStart) + 2;
                int FormEndStart = html.IndexOf("</form>");
                // write the section after the viewstate and up to the end of the FORM
                writer.Write(html.Substring(ViewStateEnd, html.Length - ViewStateEnd - (html.Length - FormEndStart)));
                // write the viewstate itself
                writer.Write(html.Substring(ViewStateStart, ViewStateEnd - ViewStateStart));
                // now write the FORM footer
                writer.Write(html.Substring(FormEndStart));

                bytes = _encoding.GetBytes(writer.ToString());
            }
            _filter.Write(bytes, 0, bytes.Length);
            _filter.Close();
            base.Close();
        }
Beispiel #38
0
        /// <summary> Pull in static content and store it.</summary>
        /// <returns> True if everything went ok.
        ///
        /// </returns>
        /// <exception cref="ResourceNotFoundException">Resource could not be
        /// found.
        /// </exception>
        public override bool Process()
        {
            System.IO.TextReader reader = null;

            try
            {
                System.IO.StringWriter sw = new System.IO.StringWriter();

                reader = new StreamReader(
                    new StreamReader(
                        resourceLoader.GetResourceStream(name),
                        System.Text.Encoding.GetEncoding(encoding)).BaseStream);

                char[] buf = new char[1024];
                int    len = 0;

                // -1 in java, 0 in .Net
                while ((len = reader.Read(buf, 0, 1024)) > 0)
                {
                    sw.Write(buf, 0, len);
                }

                data = sw.ToString();

                Data = sw.ToString();

                return(true);
            }
            catch (ResourceNotFoundException e)
            {
                // Tell the ContentManager to continue to look through any
                // remaining configured ResourceLoaders.
                throw e;
            }
            catch (System.Exception e)
            {
                string msg = "Cannot process content resource";
                rsvc.Log.Error(msg, e);
                throw new VelocityException(msg, e);
            }
            finally
            {
                if (reader != null)
                {
                    try
                    {
                        reader.Close();
                    }
                    catch (System.Exception)
                    {
                    }
                }
            }
        }
Beispiel #39
0
        public static string GetPerformanceMessage()
        {
            var s = new System.IO.StringWriter();

            foreach (var pc in counters)
            {
                double pct = pc.Value.TotalTime_s / SecondsSinceReset;
                s.Write("{0}:{1,6:0.000}ms({2,6:0.00%}) ", pc.Key, pc.Value.AverageTime_ms, pct);
            }
            return(s.ToString());
        }
Beispiel #40
0
        /// <summary>
        /// 生成TXT文件
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="Address"></param>
        public static void OutPutTXT(string txt, string Address)
        {
            FileStream fs = new FileStream(Address, FileMode.Create, FileAccess.Write);

            System.IO.StringWriter sw = new System.IO.StringWriter();
            sw.Write(txt);
            sw.Close();
            StreamWriter sw1 = new StreamWriter(fs, System.Text.Encoding.GetEncoding(("utf-8")));

            sw1.Write(sw);
            sw1.Flush();
            sw1.Close();
        }
Beispiel #41
0
        void createHtmlFromXsl()
        {
            string resultDoc = projSettings.DestinationPath + projSettings.DocHtmlFileName;

            if (projSettings.StyleName == "OrteliusXml")
            {
                resultDoc = projSettings.DestinationPath + "/orteliusXml.xml";
            }
            string xmlDoc = projSettings.DestinationPath + projSettings.DocXmlFileName;
            string xslDoc = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/styles/" + projSettings.StyleName + ".xsl";

            try
            {
                Processor processor                 = new Processor();
                System.IO.StreamReader reader       = new System.IO.StreamReader(xmlDoc, System.Text.Encoding.UTF8);
                System.IO.TextWriter   stringWriter = new System.IO.StringWriter();

                stringWriter.Write(reader.ReadToEnd());
                stringWriter.Close();

                reader.Close();

                System.IO.TextReader     stringReader = new System.IO.StringReader(stringWriter.ToString());
                System.Xml.XmlTextReader reader2      = new System.Xml.XmlTextReader(stringReader);
                reader2.XmlResolver = null;

                // Load the source document
                XdmNode input = processor.NewDocumentBuilder().Build(reader2);

                // Create a transformer for the stylesheet.
                XsltTransformer transformer = processor.NewXsltCompiler().Compile(new System.Uri(xslDoc)).Load();
                transformer.InputXmlResolver = null;

                // Set the root node of the source document to be the initial context node
                transformer.InitialContextNode = input;

                // Create a serializer
                Serializer serializer = new Serializer();

                serializer.SetOutputFile(resultDoc);

                // Transform the source XML to System.out.
                transformer.Run(serializer);
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
                systemSvar += "Error in xslt rendering:\r\n" + e.ToString();
            }
        }
Beispiel #42
0
    ///描述:将纯文本的SQL脚本导出为文件
    ///作者:
    ///时间:
    ///修改:
    ///原因:
    public void ExportSQLFile(string filename, string data)
    {
        Response.Clear();
        Response.Buffer  = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType     = "application/ms-txt";

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

        Response.Write(writer.ToString());
        Response.End();
    }
Beispiel #43
0
 /// <summary />
 /// <remarks />
 public override string ToString()
 {
     System.IO.StringWriter sw = new System.IO.StringWriter();
     // <foreach>
     // This loop mimics a foreach call. See C# programming language, pg 247
     // Here, the enumerator is seale and does not implement IDisposable
     System.Collections.IEnumerator enumerator = this.List.GetEnumerator();
     for (
         ; enumerator.MoveNext();
         )
     {
         string s = ((string)(enumerator.Current));
         // foreach body
         sw.Write(s);
     }
     // </foreach>
     return(sw.ToString());
 }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        gvConfirmedPayment.AllowPaging = false;
        Context.Response.ClearContent();
        Context.Response.ContentType = "application/ms-excel";
        Context.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "Payments Details"));
        Context.Response.Charset = "";
        System.IO.StringWriter stringwriter = new System.IO.StringWriter();
        HtmlTextWriter         htmlwriter   = new HtmlTextWriter(stringwriter);

        gvConfirmedPayment.RenderControl(htmlwriter);
        htmlwriter.WriteBreak();
        htmlwriter.WriteBreak();
        htmlwriter.WriteLine("<b>Summary</b>");
        htmlwriter.WriteBreak();
        System.IO.StringWriter stringwriter2 = new System.IO.StringWriter();
        HtmlTextWriter         htmlwriter2   = new HtmlTextWriter(stringwriter2);

        gvTransactionDetail.RenderControl(htmlwriter2);
        stringwriter.Write(stringwriter2);
        Context.Response.Write(stringwriter.ToString());
        Context.Response.End();
    }
Beispiel #45
0
 public string Serialize()
 {
     System.IO.StringWriter sw = new System.IO.StringWriter();
     lock (playersTable)
     {
         foreach (string name in playersTable.Keys)
         {
             PlayerDetails details = (PlayerDetails)playersTable[name];
             sw.Write(name);
             sw.Write(";");
             sw.Write(details.guid);
             sw.Write(";");
             sw.Write(details.score.ToString());
             sw.Write(";");
         }
     }
     return(sw.ToString());
 }
Beispiel #46
0
    protected void Submit1_ServerClick1(object sender, EventArgs e)
    {
        string msg = string.Empty;

        #region Validating Input
        if ((fileUploader.PostedFile != null) && (fileUploader.PostedFile.ContentLength > 0))
        {
            string fn = System.IO.Path.GetFileName(fileUploader.PostedFile.FileName);
            if (!fn.ToUpper().StartsWith("FH_TOURISTDETAILS") || !fn.EndsWith(".csv"))
            {
                msg = "You can only select FH_TOURISTDETAILS_XXXXXXX.CSV to upload.";
                System.IO.StringWriter sw = new System.IO.StringWriter();
                sw.Write(msg);
                HtmlTextWriter tw = new HtmlTextWriter(sw);
                //Response.Write(msg);
                base.DisplayAlert(msg);
                return;
            }
        }
        #endregion

        try
        {
            #region Loading the Excel/CSV File
            ArrayList RecordList = new ArrayList();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(fileUploader.PostedFile.InputStream))
            {
                while (sr.Peek() >= 0)
                {
                    string tempString = sr.ReadLine();
                    //recordCollection = tempString.Split(';');
                    RecordList.Add(tempString);
                }
                sr.Close();
            }
            #endregion

            #region Upload File To the Database

            ENums.UploadXMLType uploadXMLType = (ENums.UploadXMLType)Enum.Parse(typeof(ENums.UploadXMLType), uploadType);
            XmlDocument         xmlMappingDoc = XMLHelper.LoadXML(uploadXMLType);
            //XmlDocument xd = new XmlDocument();
            ////xd.LoadXml(uploadXMLType);
            //UploadServices uploadServices = new UploadServices();
            //Response.Write("abc");
            //bool uploaded = uploadServices.HandleUploadedFile(BookingId, uploadXMLType, RecordList);
            bool uploaded = tourisst.processUplodedFile(BookingId, RecordList, xmlMappingDoc);

            #endregion

            #region Validating Response
            if (uploaded)
            {
                msg = "File uploaded and processed successfully.";
                base.DisplayAlert(msg);
                Response.Redirect("~\\ClientUI\\ViewTourists.aspx?bid=" + BookingId.ToString());
            }
            else
            {
                msg = "File is not processed successfully. Please try again.";
                base.DisplayAlert(msg);
            }
            msg = "The file has been uploaded.";
            base.DisplayAlert(msg);
            #endregion
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
            msg = "File is not uploaded successfully, please try again, or contact your system administrator.";
            base.DisplayAlert(msg);
            GF.LogError("uploader.Submit", ex.Message);
            System.IO.StringWriter sw = new System.IO.StringWriter();
            sw.Write(msg);
            HtmlTextWriter tw = new HtmlTextWriter(sw);

            tw.Write(msg + " " + ex.Message);
            tw.Write(ex.StackTrace);

            //Note: Exception.Message returns detailed message that describes the current exception.
            //For security reasons, we do not recommend you return Exception.Message to end users in
            //production environments. It would be better just to put a generic error message.
        }
    }
Beispiel #47
0
    public static int Main(string[] args)
    {
        int status = 0;

        Ice.Communicator communicator = null;

        try
        {
            Console.Error.Write("testing proxy & endpoint hash algorithm collisions... ");
            Console.Error.Flush();
            Dictionary <int, Ice.ObjectPrx> seenProxy    = new Dictionary <int, Ice.ObjectPrx>();
            Dictionary <int, Ice.Endpoint>  seenEndpoint = new Dictionary <int, Ice.Endpoint>();
            int proxyCollisions    = 0;
            int endpointCollisions = 0;
            int i             = 0;
            int maxCollisions = 10;
            int maxIterations = 10000;

            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = Ice.Util.createProperties(ref args);
            //initData.properties.setProperty("Ice.Plugin.IceSSL", "IceSSL:IceSSL.PluginFactory");
            communicator = Ice.Util.initialize(ref args, initData);
            {
                Random rand = new Random();
                for (i = 0; proxyCollisions < maxCollisions &&
                     endpointCollisions < maxCollisions &&
                     i < maxIterations; ++i)
                {
                    System.IO.StringWriter sw = new System.IO.StringWriter();
                    sw.Write(i);
                    sw.Write(":tcp -p ");
                    sw.Write(rand.Next(65536));
                    sw.Write(" -t 10");
                    sw.Write(rand.Next(1000000));
                    sw.Write(":udp -p ");
                    sw.Write(rand.Next(65536));
                    sw.Write(" -h ");
                    sw.Write(rand.Next(100));

                    Ice.ObjectPrx       obj       = communicator.stringToProxy(sw.ToString());
                    List <Ice.Endpoint> endpoints = new List <Ice.Endpoint>(obj.ice_getEndpoints());

                    if (seenProxy.ContainsKey(obj.GetHashCode()))
                    {
                        if (obj.Equals(seenProxy[obj.GetHashCode()]))
                        {
                            continue;
                        }
                        ++proxyCollisions;
                    }
                    else
                    {
                        seenProxy[obj.GetHashCode()] = obj;
                    }

                    foreach (Ice.Endpoint endpoint in endpoints)
                    {
                        if (seenEndpoint.ContainsKey(endpoint.GetHashCode()))
                        {
                            if (endpoint.Equals(seenEndpoint[endpoint.GetHashCode()]))
                            {
                                continue;
                            }
                            ++endpointCollisions;
                        }
                        else
                        {
                            seenEndpoint[endpoint.GetHashCode()] = endpoint;
                        }
                        //
                        // Check the same endpoint produce always the same hash
                        //
                        test(endpoint.GetHashCode() == endpoint.GetHashCode());
                    }
                    //
                    // Check the same proxy produce always the same hash
                    //
                    test(obj.GetHashCode() == obj.GetHashCode());
                }
                test(proxyCollisions < maxCollisions);
                test(endpointCollisions < maxCollisions);
                {
                    Ice.ProxyIdentityKey comparer = new Ice.ProxyIdentityKey();
                    proxyCollisions = 0;
                    seenProxy       = new Dictionary <int, Ice.ObjectPrx>();
                    for (i = 0; proxyCollisions < maxCollisions && i < maxIterations; ++i)
                    {
                        System.IO.StringWriter sw = new System.IO.StringWriter();
                        sw.Write(i);
                        sw.Write(":tcp -p ");
                        sw.Write(rand.Next(65536));
                        sw.Write(" -t 10");
                        sw.Write(rand.Next(1000000));
                        sw.Write(":udp -p ");
                        sw.Write(rand.Next(65536));
                        sw.Write(" -h ");
                        sw.Write(rand.Next(100));

                        Ice.ObjectPrx obj = communicator.stringToProxy(sw.ToString());

                        if (seenProxy.ContainsKey(comparer.GetHashCode(obj)))
                        {
                            ++proxyCollisions;
                        }
                        else
                        {
                            seenProxy[comparer.GetHashCode(obj)] = obj;
                        }
                        //
                        // Check the same proxy produce always the same hash
                        //
                        test(comparer.GetHashCode(obj) == comparer.GetHashCode(obj));
                    }
                    test(proxyCollisions < maxCollisions);
                }
            }

            {
                Random rand = new Random();
                Ice.ProxyIdentityFacetKey comparer = new Ice.ProxyIdentityFacetKey();
                proxyCollisions = 0;
                seenProxy       = new Dictionary <int, Ice.ObjectPrx>();
                for (i = 0; proxyCollisions < maxCollisions && i < maxIterations; ++i)
                {
                    System.IO.StringWriter sw = new System.IO.StringWriter();
                    sw.Write(i);
                    sw.Write(" -f demo:tcp -p ");
                    sw.Write(rand.Next(65536));
                    sw.Write(" -t 10");
                    sw.Write(rand.Next(1000000));
                    sw.Write(":udp -p ");
                    sw.Write(rand.Next(65536));
                    sw.Write(" -h ");
                    sw.Write(rand.Next(100));

                    Ice.ObjectPrx obj = communicator.stringToProxy(sw.ToString());

                    if (seenProxy.ContainsKey(comparer.GetHashCode(obj)))
                    {
                        ++proxyCollisions;
                    }
                    else
                    {
                        seenProxy[comparer.GetHashCode(obj)] = obj;
                    }
                    //
                    // Check the same proxy produce always the same hash
                    //
                    test(comparer.GetHashCode(obj) == comparer.GetHashCode(obj));
                }
                test(proxyCollisions < maxCollisions);
            }

            Ice.ProxyIdentityFacetKey iComparer  = new Ice.ProxyIdentityFacetKey();
            Ice.ProxyIdentityFacetKey ifComparer = new Ice.ProxyIdentityFacetKey();

            Ice.ObjectPrx prx1 = communicator.stringToProxy("Glacier2/router:tcp -p 10010");
            //Ice.ObjectPrx prx2 = communicator.stringToProxy("Glacier2/router:ssl -p 10011");
            Ice.ObjectPrx prx3 = communicator.stringToProxy("Glacier2/router:udp -p 10012");
            Ice.ObjectPrx prx4 = communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010");
            //Ice.ObjectPrx prx5 = communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011");
            Ice.ObjectPrx prx6 = communicator.stringToProxy("Glacier2/router:udp -h zeroc.com -p 10012");
            Ice.ObjectPrx prx7 = communicator.stringToProxy("Glacier2/router:tcp -p 10010 -t 10000");
            //Ice.ObjectPrx prx8 = communicator.stringToProxy("Glacier2/router:ssl -p 10011 -t 10000");
            Ice.ObjectPrx prx9 = communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010 -t 10000");
            //Ice.ObjectPrx prx10 = communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011 -t 10000");

            Dictionary <string, int> proxyMap = new Dictionary <string, int>();
            proxyMap["prx1"] = prx1.GetHashCode();
            //proxyMap["prx2"] = prx2.GetHashCode();
            proxyMap["prx3"] = prx3.GetHashCode();
            proxyMap["prx4"] = prx4.GetHashCode();
            //proxyMap["prx5"] = prx5.GetHashCode();
            proxyMap["prx6"] = prx6.GetHashCode();
            proxyMap["prx7"] = prx7.GetHashCode();
            //proxyMap["prx8"] = prx8.GetHashCode();
            proxyMap["prx9"] = prx9.GetHashCode();
            //proxyMap["prx10"] = prx10.GetHashCode();

            test(communicator.stringToProxy("Glacier2/router:tcp -p 10010").GetHashCode() == proxyMap["prx1"]);
            //test(communicator.stringToProxy("Glacier2/router:ssl -p 10011").GetHashCode() == proxyMap["prx2"]);
            test(communicator.stringToProxy("Glacier2/router:udp -p 10012").GetHashCode() == proxyMap["prx3"]);
            test(communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010").GetHashCode() == proxyMap["prx4"]);
            //test(communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011").GetHashCode() == proxyMap["prx5"]);
            test(communicator.stringToProxy("Glacier2/router:udp -h zeroc.com -p 10012").GetHashCode() == proxyMap["prx6"]);
            test(communicator.stringToProxy("Glacier2/router:tcp -p 10010 -t 10000").GetHashCode() == proxyMap["prx7"]);
            //test(communicator.stringToProxy("Glacier2/router:ssl -p 10011 -t 10000").GetHashCode() == proxyMap["prx8"]);
            test(communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010 -t 10000").GetHashCode() == proxyMap["prx9"]);
            //test(communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011 -t 10000").GetHashCode() == proxyMap["prx10"]);

            test(iComparer.GetHashCode(prx1) == iComparer.GetHashCode(prx1));
            test(ifComparer.GetHashCode(prx1) == ifComparer.GetHashCode(prx1));

            test(iComparer.GetHashCode(prx3) == iComparer.GetHashCode(prx3));
            test(ifComparer.GetHashCode(prx3) == ifComparer.GetHashCode(prx3));

            test(iComparer.GetHashCode(prx4) == iComparer.GetHashCode(prx4));
            test(ifComparer.GetHashCode(prx4) == ifComparer.GetHashCode(prx4));

            test(iComparer.GetHashCode(prx6) == iComparer.GetHashCode(prx6));
            test(ifComparer.GetHashCode(prx6) == ifComparer.GetHashCode(prx6));

            test(iComparer.GetHashCode(prx7) == iComparer.GetHashCode(prx7));
            test(ifComparer.GetHashCode(prx7) == ifComparer.GetHashCode(prx7));

            test(iComparer.GetHashCode(prx9) == iComparer.GetHashCode(prx9));
            test(ifComparer.GetHashCode(prx9) == ifComparer.GetHashCode(prx9));

            Console.Error.WriteLine("ok");

            Console.Error.Write("testing exceptions hash algorithm collisions... ");

            {
                Dictionary <int, Test.OtherException> seenException = new Dictionary <int, Test.OtherException>();
                Random rand = new Random();

                int exceptionCollisions = 0;
                for (i = 0; i < maxIterations &&
                     exceptionCollisions < maxCollisions; ++i)
                {
                    Test.OtherException ex = new Test.OtherException(rand.Next(100), rand.Next(100), 0, false);
                    if (seenException.ContainsKey(ex.GetHashCode()))
                    {
                        if (ex.Equals(seenException[ex.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        exceptionCollisions++;
                    }
                    else
                    {
                        seenException[ex.GetHashCode()] = ex;
                    }
                    //
                    // Check the same exception produce always the same hash
                    //
                    test(ex.GetHashCode() == ex.GetHashCode());
                }
                test(exceptionCollisions < maxCollisions);
            }

            //
            // Same as above but with numbers in high ranges
            //
            {
                Dictionary <int, Test.OtherException> seenException = new Dictionary <int, Test.OtherException>();
                Random rand = new Random();

                int exceptionCollisions = 0;
                for (i = 0; i < maxIterations &&
                     exceptionCollisions < maxCollisions; ++i)
                {
                    Test.OtherException ex = new Test.OtherException(rand.Next(100) * 2 ^ 30, rand.Next(100) * 2 ^ 30, rand.Next(100) * 2 ^ 30, false);
                    if (seenException.ContainsKey(ex.GetHashCode()))
                    {
                        if (ex.Equals(seenException[ex.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        exceptionCollisions++;
                    }
                    else
                    {
                        seenException[ex.GetHashCode()] = ex;
                    }
                    //
                    // Check the same exception produce always the same hash
                    //
                    test(ex.GetHashCode() == ex.GetHashCode());
                }
                test(exceptionCollisions < maxCollisions);
            }

            {
                Dictionary <int, Test.BaseException> seenException = new Dictionary <int, Test.BaseException>();
                Random rand = new Random();

                int exceptionCollisions = 0;
                for (i = 0; i < maxIterations &&
                     exceptionCollisions < maxCollisions; ++i)
                {
                    int v = rand.Next(1000);
                    Test.BaseException ex = new Test.InvalidPointException(v);
                    if (seenException.ContainsKey(ex.GetHashCode()))
                    {
                        if (ex.Equals(seenException[ex.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        exceptionCollisions++;
                    }
                    else
                    {
                        seenException[ex.GetHashCode()] = ex;
                    }

                    //
                    // Check the same exception produce always the same hash
                    //
                    test(ex.GetHashCode() == ex.GetHashCode());

                    ex = new Test.InvalidLengthException(v);
                    if (seenException.ContainsKey(ex.GetHashCode()))
                    {
                        if (ex.Equals(seenException[ex.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        exceptionCollisions++;
                    }
                    else
                    {
                        seenException[ex.GetHashCode()] = ex;
                    }

                    //
                    // Check the same exception produce always the same hash
                    //
                    test(ex.GetHashCode() == ex.GetHashCode());
                }
                test(exceptionCollisions < maxCollisions);
            }
            Console.Error.WriteLine("ok");

            Console.Error.Write("testing struct hash algorithm collisions... ");
            {
                Dictionary <int, Test.PointF> seenPointF = new Dictionary <int, Test.PointF>();
                Random rand             = new Random();
                int    structCollisions = 0;
                for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
                {
                    Test.PointF pf = new Test.PointF((float)rand.NextDouble(), (float)rand.NextDouble(),
                                                     (float)rand.NextDouble());
                    if (seenPointF.ContainsKey(pf.GetHashCode()))
                    {
                        if (pf.Equals(seenPointF[pf.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        structCollisions++;
                    }
                    else
                    {
                        seenPointF[pf.GetHashCode()] = pf;
                    }
                    //
                    // Check the same struct produce always the same hash
                    //
                    test(pf.GetHashCode() == pf.GetHashCode());
                }
                test(structCollisions < maxCollisions);

                Dictionary <int, Test.PointD> seenPointD = new Dictionary <int, Test.PointD>();
                structCollisions = 0;
                for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
                {
                    Test.PointD pd = new Test.PointD(rand.NextDouble(), rand.NextDouble(),
                                                     rand.NextDouble());
                    if (seenPointD.ContainsKey(pd.GetHashCode()))
                    {
                        if (pd.Equals(seenPointD[pd.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        structCollisions++;
                    }
                    else
                    {
                        seenPointD[pd.GetHashCode()] = pd;
                    }
                    //
                    // Check the same struct produce always the same hash
                    //
                    test(pd.GetHashCode() == pd.GetHashCode());
                }
                test(structCollisions < maxCollisions);

                Dictionary <int, Test.Polyline> seenPolyline = new Dictionary <int, Test.Polyline>();
                structCollisions = 0;
                for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
                {
                    Test.Polyline     polyline = new Test.Polyline();
                    List <Test.Point> vertices = new List <Test.Point>();
                    for (int j = 0; j < 100; ++j)
                    {
                        vertices.Add(new Test.Point(rand.Next(100), rand.Next(100)));
                    }
                    polyline.vertices = vertices.ToArray();

                    if (seenPolyline.ContainsKey(polyline.GetHashCode()))
                    {
                        if (polyline.Equals(seenPolyline[polyline.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        structCollisions++;
                    }
                    else
                    {
                        seenPolyline[polyline.GetHashCode()] = polyline;
                    }
                    //
                    // Check the same struct produce always the same hash
                    //
                    test(polyline.GetHashCode() == polyline.GetHashCode());
                }
                test(structCollisions < maxCollisions);

                Dictionary <int, Test.ColorPalette> seenColorPalette = new Dictionary <int, Test.ColorPalette>();
                structCollisions = 0;
                for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
                {
                    Test.ColorPalette colorPalette = new Test.ColorPalette();
                    colorPalette.colors = new Dictionary <int, Test.Color>();
                    for (int j = 0; j < 100; ++j)
                    {
                        colorPalette.colors[j] = new Test.Color(rand.Next(255), rand.Next(255), rand.Next(255), rand.Next(255));
                    }

                    if (seenColorPalette.ContainsKey(colorPalette.GetHashCode()))
                    {
                        if (colorPalette.Equals(seenColorPalette[colorPalette.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        structCollisions++;
                    }
                    else
                    {
                        seenColorPalette[colorPalette.GetHashCode()] = colorPalette;
                    }
                    //
                    // Check the same struct produce always the same hash
                    //
                    test(colorPalette.GetHashCode() == colorPalette.GetHashCode());
                }
                test(structCollisions < maxCollisions);

                Dictionary <int, Test.Color> seenColor = new Dictionary <int, Test.Color>();
                structCollisions = 0;
                for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
                {
                    Test.Color c = new Test.Color(rand.Next(255), rand.Next(255), rand.Next(255), rand.Next(255));
                    if (seenColor.ContainsKey(c.GetHashCode()))
                    {
                        if (c.Equals(seenColor[c.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        structCollisions++;
                    }
                    else
                    {
                        seenColor[c.GetHashCode()] = c;
                    }
                    //
                    // Check the same struct produce always the same hash
                    //
                    test(c.GetHashCode() == c.GetHashCode());
                }
                test(structCollisions < maxCollisions);

                structCollisions = 0;
                Dictionary <int, Test.Draw> seenDraw = new Dictionary <int, Test.Draw>();
                structCollisions = 0;
                for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
                {
                    Test.Draw draw = new Test.Draw(
                        new Test.Color(rand.Next(255), rand.Next(255), rand.Next(255), rand.Next(255)),
                        new Test.Pen(rand.Next(10),
                                     new Test.Color(rand.Next(255), rand.Next(255), rand.Next(255), rand.Next(255))),
                        false);

                    if (seenDraw.ContainsKey(draw.GetHashCode()))
                    {
                        if (draw.Equals(seenDraw[draw.GetHashCode()]))
                        {
                            continue; // same object
                        }
                        structCollisions++;
                    }
                    else
                    {
                        seenDraw[draw.GetHashCode()] = draw;
                    }
                    //
                    // Check the same struct produce always the same hash
                    //
                    test(draw.GetHashCode() == draw.GetHashCode());
                }
                test(structCollisions < maxCollisions);
            }
            Console.Error.WriteLine("ok");

            if (communicator != null)
            {
                communicator.destroy();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            status = 1;
        }

        return(status);
    }
Beispiel #48
0
    public override void Run(string[] args)
    {
        using Communicator communicator = Initialize(ref args);
        Console.Error.Write("testing proxy & endpoint hash algorithm collisions... ");
        Console.Error.Flush();
        var seenProxy          = new Dictionary <int, IObjectPrx>();
        var seenEndpoint       = new Dictionary <int, Endpoint>();
        int proxyCollisions    = 0;
        int endpointCollisions = 0;
        int i             = 0;
        int maxCollisions = 10;
        int maxIterations = 10000;

        {
            var rand = new Random();
            for (i = 0; proxyCollisions < maxCollisions &&
                 endpointCollisions < maxCollisions &&
                 i < maxIterations; ++i)
            {
                var sw = new System.IO.StringWriter();
                sw.Write(i);
                sw.Write(":tcp -p ");
                sw.Write(rand.Next(65536));
                sw.Write(" -t 10");
                sw.Write(rand.Next(1000000));
                sw.Write(":udp -p ");
                sw.Write(rand.Next(65536));
                sw.Write(" -h ");
                sw.Write(rand.Next(100));

                var obj       = IObjectPrx.Parse(sw.ToString(), communicator);
                var endpoints = new List <Endpoint>(obj.Endpoints);

                if (seenProxy.ContainsKey(obj.GetHashCode()))
                {
                    if (obj.Equals(seenProxy[obj.GetHashCode()]))
                    {
                        continue;
                    }
                    ++proxyCollisions;
                }
                else
                {
                    seenProxy[obj.GetHashCode()] = obj;
                }

                foreach (Endpoint endpoint in endpoints)
                {
                    if (seenEndpoint.ContainsKey(endpoint.GetHashCode()))
                    {
                        if (endpoint.Equals(seenEndpoint[endpoint.GetHashCode()]))
                        {
                            continue;
                        }
                        ++endpointCollisions;
                    }
                    else
                    {
                        seenEndpoint[endpoint.GetHashCode()] = endpoint;
                    }
                    //
                    // Check the same endpoint produce always the same hash
                    //
                    TestHelper.Assert(endpoint.GetHashCode() == endpoint.GetHashCode());
                }
                //
                // Check the same proxy produce always the same hash
                //
                TestHelper.Assert(obj.GetHashCode() == obj.GetHashCode());
            }
            TestHelper.Assert(proxyCollisions < maxCollisions);
            TestHelper.Assert(endpointCollisions < maxCollisions);
            {
                var comparer = new ProxyIdentityComparer();
                proxyCollisions = 0;
                seenProxy       = new Dictionary <int, IObjectPrx>();
                for (i = 0; proxyCollisions < maxCollisions && i < maxIterations; ++i)
                {
                    var sw = new System.IO.StringWriter();
                    sw.Write(i);
                    sw.Write(":tcp -p ");
                    sw.Write(rand.Next(65536));
                    sw.Write(" -t 10");
                    sw.Write(rand.Next(1000000));
                    sw.Write(":udp -p ");
                    sw.Write(rand.Next(65536));
                    sw.Write(" -h ");
                    sw.Write(rand.Next(100));

                    var obj = IObjectPrx.Parse(sw.ToString(), communicator);

                    if (seenProxy.ContainsKey(comparer.GetHashCode(obj)))
                    {
                        ++proxyCollisions;
                    }
                    else
                    {
                        seenProxy[comparer.GetHashCode(obj)] = obj;
                    }
                    //
                    // Check the same proxy produce always the same hash
                    //
                    TestHelper.Assert(comparer.GetHashCode(obj) == comparer.GetHashCode(obj));
                }
                TestHelper.Assert(proxyCollisions < maxCollisions);
            }
        }

        {
            var rand     = new Random();
            var comparer = new ProxyIdentityFacetComparer();
            proxyCollisions = 0;
            seenProxy       = new Dictionary <int, IObjectPrx>();
            for (i = 0; proxyCollisions < maxCollisions && i < maxIterations; ++i)
            {
                var sw = new System.IO.StringWriter();
                sw.Write(i);
                sw.Write(" -f demo:tcp -p ");
                sw.Write(rand.Next(65536));
                sw.Write(" -t 10");
                sw.Write(rand.Next(1000000));
                sw.Write(":udp -p ");
                sw.Write(rand.Next(65536));
                sw.Write(" -h ");
                sw.Write(rand.Next(100));

                var obj = IObjectPrx.Parse(sw.ToString(), communicator);

                if (seenProxy.ContainsKey(comparer.GetHashCode(obj)))
                {
                    ++proxyCollisions;
                }
                else
                {
                    seenProxy[comparer.GetHashCode(obj)] = obj;
                }
                //
                // Check the same proxy produce always the same hash
                //
                TestHelper.Assert(comparer.GetHashCode(obj) == comparer.GetHashCode(obj));
            }
            TestHelper.Assert(proxyCollisions < maxCollisions);
        }

        var iComparer  = new ProxyIdentityComparer();
        var ifComparer = new ProxyIdentityFacetComparer();

        var prx1 = IObjectPrx.Parse("Glacier2/router:tcp -p 10010", communicator);
        //Ice.ObjectPrx prx2 = communicator.stringToProxy("Glacier2/router:ssl -p 10011");
        var prx3 = IObjectPrx.Parse("Glacier2/router:udp -p 10012", communicator);
        var prx4 = IObjectPrx.Parse("Glacier2/router:tcp -h zeroc.com -p 10010", communicator);
        //Ice.ObjectPrx prx5 = communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011");
        var prx6 = IObjectPrx.Parse("Glacier2/router:udp -h zeroc.com -p 10012", communicator);
        var prx7 = IObjectPrx.Parse("Glacier2/router:tcp -p 10010 -t 10000", communicator);
        //Ice.ObjectPrx prx8 = communicator.stringToProxy("Glacier2/router:ssl -p 10011 -t 10000");
        var prx9 = IObjectPrx.Parse("Glacier2/router:tcp -h zeroc.com -p 10010 -t 10000", communicator);
        //Ice.ObjectPrx prx10 = communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011 -t 10000");

        var proxyMap = new Dictionary <string, int>
        {
            ["prx1"] = prx1.GetHashCode(),
            //proxyMap["prx2"] = prx2.GetHashCode();
            ["prx3"] = prx3.GetHashCode(),
            ["prx4"] = prx4.GetHashCode(),
            //proxyMap["prx5"] = prx5.GetHashCode();
            ["prx6"] = prx6.GetHashCode(),
            ["prx7"] = prx7.GetHashCode(),
            //proxyMap["prx8"] = prx8.GetHashCode();
            ["prx9"] = prx9.GetHashCode()
        };

        //proxyMap["prx10"] = prx10.GetHashCode();

        TestHelper.Assert(IObjectPrx.Parse("Glacier2/router:tcp -p 10010", communicator).GetHashCode() == proxyMap["prx1"]);
        //TestHelper.Assert(communicator.stringToProxy("Glacier2/router:ssl -p 10011").GetHashCode() == proxyMap["prx2"]);
        TestHelper.Assert(IObjectPrx.Parse("Glacier2/router:udp -p 10012", communicator).GetHashCode() == proxyMap["prx3"]);
        TestHelper.Assert(IObjectPrx.Parse("Glacier2/router:tcp -h zeroc.com -p 10010", communicator).GetHashCode() == proxyMap["prx4"]);
        //TestHelper.Assert(communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011").GetHashCode() == proxyMap["prx5"]);
        TestHelper.Assert(IObjectPrx.Parse("Glacier2/router:udp -h zeroc.com -p 10012", communicator).GetHashCode() == proxyMap["prx6"]);
        TestHelper.Assert(IObjectPrx.Parse("Glacier2/router:tcp -p 10010 -t 10000", communicator).GetHashCode() == proxyMap["prx7"]);
        //TestHelper.Assert(communicator.stringToProxy("Glacier2/router:ssl -p 10011 -t 10000").GetHashCode() == proxyMap["prx8"]);
        TestHelper.Assert(IObjectPrx.Parse("Glacier2/router:tcp -h zeroc.com -p 10010 -t 10000", communicator).GetHashCode() == proxyMap["prx9"]);
        //TestHelper.Assert(communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011 -t 10000").GetHashCode() == proxyMap["prx10"]);

        TestHelper.Assert(iComparer.GetHashCode(prx1) == iComparer.GetHashCode(prx1));
        TestHelper.Assert(ifComparer.GetHashCode(prx1) == ifComparer.GetHashCode(prx1));

        TestHelper.Assert(iComparer.GetHashCode(prx3) == iComparer.GetHashCode(prx3));
        TestHelper.Assert(ifComparer.GetHashCode(prx3) == ifComparer.GetHashCode(prx3));

        TestHelper.Assert(iComparer.GetHashCode(prx4) == iComparer.GetHashCode(prx4));
        TestHelper.Assert(ifComparer.GetHashCode(prx4) == ifComparer.GetHashCode(prx4));

        TestHelper.Assert(iComparer.GetHashCode(prx6) == iComparer.GetHashCode(prx6));
        TestHelper.Assert(ifComparer.GetHashCode(prx6) == ifComparer.GetHashCode(prx6));

        TestHelper.Assert(iComparer.GetHashCode(prx7) == iComparer.GetHashCode(prx7));
        TestHelper.Assert(ifComparer.GetHashCode(prx7) == ifComparer.GetHashCode(prx7));

        TestHelper.Assert(iComparer.GetHashCode(prx9) == iComparer.GetHashCode(prx9));
        TestHelper.Assert(ifComparer.GetHashCode(prx9) == ifComparer.GetHashCode(prx9));

        Console.Error.WriteLine("ok");

        Console.Error.Write("testing exceptions hash algorithm collisions... ");

        {
            var seenException = new Dictionary <int, Test.OtherException>();
            var rand          = new Random();

            int exceptionCollisions = 0;
            for (i = 0; i < maxIterations && exceptionCollisions < maxCollisions; ++i)
            {
                var ex = new Test.OtherException(rand.Next(100), rand.Next(100), 0, false);
                if (seenException.ContainsKey(ex.GetHashCode()))
                {
                    if (ex.Equals(seenException[ex.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    exceptionCollisions++;
                }
                else
                {
                    seenException[ex.GetHashCode()] = ex;
                }
                //
                // Check the same exception produce always the same hash
                //
                TestHelper.Assert(ex.GetHashCode() == ex.GetHashCode());
            }
            TestHelper.Assert(exceptionCollisions < maxCollisions);
        }

        //
        // Same as above but with numbers in high ranges
        //
        {
            var seenException = new Dictionary <int, Test.OtherException>();
            var rand          = new Random();

            int exceptionCollisions = 0;
            for (i = 0; i < maxIterations && exceptionCollisions < maxCollisions; ++i)
            {
                var ex = new Test.OtherException((rand.Next(100) * 2) ^ 30,
                                                 (rand.Next(100) * 2) ^ 30,
                                                 (rand.Next(100) * 2) ^ 30,
                                                 false);

                if (seenException.ContainsKey(ex.GetHashCode()))
                {
                    if (ex.Equals(seenException[ex.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    exceptionCollisions++;
                }
                else
                {
                    seenException[ex.GetHashCode()] = ex;
                }
                //
                // Check the same exception produce always the same hash
                //
                TestHelper.Assert(ex.GetHashCode() == ex.GetHashCode());
            }
            TestHelper.Assert(exceptionCollisions < maxCollisions);
        }

        {
            var seenException = new Dictionary <int, Test.BaseException>();
            var rand          = new Random();

            int exceptionCollisions = 0;
            for (i = 0; i < maxIterations && exceptionCollisions < maxCollisions; ++i)
            {
                int v = rand.Next(1000);
                Test.BaseException ex = new Test.InvalidPointException(v);
                if (seenException.ContainsKey(ex.GetHashCode()))
                {
                    if (ex.Equals(seenException[ex.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    exceptionCollisions++;
                }
                else
                {
                    seenException[ex.GetHashCode()] = ex;
                }

                //
                // Check the same exception produce always the same hash
                //
                TestHelper.Assert(ex.GetHashCode() == ex.GetHashCode());

                ex = new Test.InvalidLengthException(v);
                if (seenException.ContainsKey(ex.GetHashCode()))
                {
                    if (ex.Equals(seenException[ex.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    exceptionCollisions++;
                }
                else
                {
                    seenException[ex.GetHashCode()] = ex;
                }

                //
                // Check the same exception produce always the same hash
                //
                TestHelper.Assert(ex.GetHashCode() == ex.GetHashCode());
            }
            TestHelper.Assert(exceptionCollisions < maxCollisions);
        }
        Console.Error.WriteLine("ok");

        Console.Error.Write("testing struct hash algorithm collisions... ");
        {
            var seenPointF       = new Dictionary <int, Test.PointF>();
            var rand             = new Random();
            int structCollisions = 0;
            for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
            {
                var pf = new Test.PointF((float)rand.NextDouble(),
                                         (float)rand.NextDouble(),
                                         (float)rand.NextDouble());
                if (seenPointF.ContainsKey(pf.GetHashCode()))
                {
                    if (pf.Equals(seenPointF[pf.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    structCollisions++;
                }
                else
                {
                    seenPointF[pf.GetHashCode()] = pf;
                }
                //
                // Check the same struct produce always the same hash
                //
                TestHelper.Assert(pf.GetHashCode() == pf.GetHashCode());
            }
            TestHelper.Assert(structCollisions < maxCollisions);

            var seenPointD = new Dictionary <int, Test.PointD>();
            structCollisions = 0;
            for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
            {
                var pd = new Test.PointD(rand.NextDouble(), rand.NextDouble(), rand.NextDouble());
                if (seenPointD.ContainsKey(pd.GetHashCode()))
                {
                    if (pd.Equals(seenPointD[pd.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    structCollisions++;
                }
                else
                {
                    seenPointD[pd.GetHashCode()] = pd;
                }
                //
                // Check the same struct produce always the same hash
                //
                TestHelper.Assert(pd.GetHashCode() == pd.GetHashCode());
            }
            TestHelper.Assert(structCollisions < maxCollisions);

            var seenPolyline = new Dictionary <int, Test.Polyline>();
            structCollisions = 0;
            for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
            {
                var polyline = new Test.Polyline();
                var vertices = new List <Test.Point>();
                for (int j = 0; j < 100; ++j)
                {
                    vertices.Add(new Test.Point(rand.Next(100), rand.Next(100)));
                }
                polyline.vertices = vertices.ToArray();

                if (seenPolyline.ContainsKey(polyline.GetHashCode()))
                {
                    if (polyline.Equals(seenPolyline[polyline.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    structCollisions++;
                }
                else
                {
                    seenPolyline[polyline.GetHashCode()] = polyline;
                }
                //
                // Check the same struct produce always the same hash
                //
                TestHelper.Assert(polyline.GetHashCode() == polyline.GetHashCode());
            }
            TestHelper.Assert(structCollisions < maxCollisions);

            var seenColorPalette = new Dictionary <int, Test.ColorPalette>();
            structCollisions = 0;
            for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
            {
                var colorPalette = new Test.ColorPalette();
                colorPalette.colors = new Dictionary <int, Test.Color>();
                for (int j = 0; j < 100; ++j)
                {
                    colorPalette.colors[j] = new Test.Color(rand.Next(255),
                                                            rand.Next(255),
                                                            rand.Next(255),
                                                            rand.Next(255));
                }

                if (seenColorPalette.ContainsKey(colorPalette.GetHashCode()))
                {
                    if (colorPalette.Equals(seenColorPalette[colorPalette.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    structCollisions++;
                }
                else
                {
                    seenColorPalette[colorPalette.GetHashCode()] = colorPalette;
                }
                //
                // Check the same struct produce always the same hash
                //
                TestHelper.Assert(colorPalette.GetHashCode() == colorPalette.GetHashCode());
            }
            TestHelper.Assert(structCollisions < maxCollisions);

            var seenColor = new Dictionary <int, Test.Color>();
            structCollisions = 0;
            for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
            {
                var c = new Test.Color(rand.Next(255), rand.Next(255), rand.Next(255), rand.Next(255));
                if (seenColor.ContainsKey(c.GetHashCode()))
                {
                    if (c.Equals(seenColor[c.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    structCollisions++;
                }
                else
                {
                    seenColor[c.GetHashCode()] = c;
                }
                //
                // Check the same struct produce always the same hash
                //
                TestHelper.Assert(c.GetHashCode() == c.GetHashCode());
            }
            TestHelper.Assert(structCollisions < maxCollisions);

            var seenDraw = new Dictionary <int, Test.Draw>();
            structCollisions = 0;
            for (i = 0; i < maxIterations && structCollisions < maxCollisions; ++i)
            {
                var draw = new Test.Draw(
                    new Test.Color(rand.Next(255), rand.Next(255), rand.Next(255), rand.Next(255)),
                    new Test.Pen(rand.Next(10),
                                 new Test.Color(rand.Next(255), rand.Next(255), rand.Next(255), rand.Next(255))),
                    false);

                if (seenDraw.ContainsKey(draw.GetHashCode()))
                {
                    if (draw.Equals(seenDraw[draw.GetHashCode()]))
                    {
                        continue; // same object
                    }
                    structCollisions++;
                }
                else
                {
                    seenDraw[draw.GetHashCode()] = draw;
                }
                //
                // Check the same struct produce always the same hash
                //
                TestHelper.Assert(draw.GetHashCode() == draw.GetHashCode());
            }
            TestHelper.Assert(structCollisions < maxCollisions);
        }
        Console.Error.WriteLine("ok");
    }
Beispiel #49
0
        protected void DownWord()
        {
            string wordTemplate = "";
            var    model        = new Eyousoft_yhq.BLL.Product().GetModel(Utils.GetQueryStringValue("routeid"));

            if (model != null)
            {
                #region 文本内容
                wordTemplate = @"
                <html>
                <head>
                    <title>打印预览</title>
                    <style type=""text/css"">
                    body {{color:#000000;font-size:12px;font-family:""宋体"";background:#fff; margin:0px;}}
                    img {{border: thin none;}}
                    table {{border-collapse:collapse;width:790px;}}
                    td {{font-size: 12px; line-height:18px;color: #000000;  }}	
                    .headertitle {{font-family:""黑体""; font-size:25px; line-height:120%; font-weight:bold;}}
                    </style>
                </head>
                <body>
                    <div id=""divAllHtml"" style=""width: 760px; margin: 0 auto;"">
        <div id=""divContent"">
            <table width=""696"" border=""0"" align=""center"" cellpadding=""0"" cellspacing=""0"">
                <tr>
                    <td height=""40"" align=""center"">
                        <b class=""font24"">
                            {0}</b>
                    </td>
                </tr>
            </table>
            <table width=""696"" border=""0"" align=""center"" cellpadding=""0"" cellspacing=""0"" runat=""server""
                id=""TPlanFeature"" class=""borderline_2"">
                <tr>
                    <td height=""30"" class=""small_title"">
                        <b class=""font16"">产品介绍</b>
                    </td>
                </tr>
                <tr>
                    <td class=""td_text"">
                        {1}
                    </td>
                </tr>
            </table>
            <table width=""696"" cellspacing=""0"" cellpadding=""0"" border=""0"" align=""center"" id=""TAll""
                runat=""server"" class=""borderline_2"">
                <tbody>
                    <tr>
                        <td height=""30"" class=""small_title"">
                            <b class=""font16"">参考行程</b>
                        </td>
                    </tr>
                    <tr>
                        <td class=""td_text"">
                            {2}
                        </td>
                    </tr>
                </tbody>
            </table>
            <div id=""TOption"" runat=""server"">
                <table width=""696"" cellspacing=""0"" cellpadding=""0"" border=""0"" align=""center"" class=""list_2"">
                    <tbody>
                        <tr>
                            <td height=""30"" class=""small_title"">
                                <b class=""font16"">出团须知</b>
                            </td>
                        </tr>
                        <tr>
                            <td class=""td_text"">
                               {3}
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div runat=""server"" id=""TPlanService"">
                <table width=""696"" border=""0"" align=""center"" cellpadding=""0"" cellspacing=""0"" runat=""server""
                    id=""TService"" class=""borderline_2"">
                    <tr>
                        <td height=""30"" class=""small_title"">
                            <b class=""font16"">价格标准</b>
                        </td>
                    </tr>
                    <tr>
                        <td class=""td_text borderline_2"">
                           市场价格:{4},会员价格:{5}
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
                </body>
                </html>";
                #endregion

                HttpContext.Current.Response.Clear();
                string saveFileName       = HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddhhssffff") + ".doc", System.Text.Encoding.Default);
                System.IO.StringWriter tw = new System.IO.StringWriter();

                tw.Write(string.Format(wordTemplate, model.ProductName, model.ProductDis, model.TourDis, model.SendTourKnow, model.MarketPrice.ToString("C0"), model.AppPrice.ToString("C0")).ToString());
                WriteFile(tw.ToString(), saveFileName);
                FileInfo Inf = new FileInfo(Server.MapPath(@"TemFile/" + saveFileName));
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + saveFileName);
                HttpContext.Current.Response.Charset         = "GB2312";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
                HttpContext.Current.Response.ContentType     = "application/ms-word ";
                Page.EnableViewState = false;

                HttpContext.Current.Response.WriteFile(Inf.FullName);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }
        private object?Invoke(string funcName, CallInfo callInfo, object?[] args)
        {
            int posCount = callInfo.ArgumentCount - callInfo.ArgumentNames.Count;
            var argNames = Enumerable.Repeat((string?)null, posCount).Concat(callInfo.ArgumentNames).ToArray();

            Invoker GetInvoker(bool construct)
            {
                var code = new StringWriter();

                code.WriteLine($"#line 1 \"{FileName}\"");
                code.Write("return (global::Int19h.Bannerlord.CSharp.Scripting.Script.Invoker)(args => ");
                if (construct)
                {
                    code.Write("new ");
                }
                code.Write($"{funcName}(");
                for (int i = 0; i < args.Length; ++i)
                {
                    if (i != 0)
                    {
                        code.Write(", ");
                    }

                    var argName = argNames[i];
                    if (argName != null)
                    {
                        code.Write($"{argName}: ");
                    }
                    code.Write($"args[{i}]");
                }
                code.WriteLine("));");

                var script = State.Script.ContinueWith <Invoker>(code.ToString());

                Scripts.IgnoreVisibility(script);
                try {
                    return(script.RunAsync().GetAwaiter().GetResult().ReturnValue);
                } catch (CompilationErrorException) {
                    if (construct)
                    {
                        return(GetInvoker(false));
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            var invoker       = GetInvoker(false);
            var oldScriptPath = ScriptGlobals.ScriptPath;

            ScriptGlobals.ScriptPath = FileName;
            args = args.Select(arg => ScriptArgument.Wrap(arg)).ToArray();
            try {
                invoker(args);
                return(null);
            } catch (TargetInvocationException ex) {
                ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                throw;
            } finally {
                ScriptGlobals.ScriptPath = oldScriptPath;
            }
        }
Beispiel #51
0
        static public CompileResult Evaluate(string code, bool autoCompleteComma = true)
        {
            if (autoCompleteComma && !code.EndsWith(";"))
            {
                code += ";";
            }

            var result = new CompileResult();

            result.code = code;

            // find commands and expand it if found.
            if (RuntimeCommands.ConvertIntoCodeIfCommand(ref code) ||
                Commands.ConvertIntoCodeIfCommand(ref code))
            {
                // the give code is a command and converted into an actua code.
            }

            // eval the code using Mono.
            object ret            = null;
            bool   hasReturnValue = false;

//		var originalOutput = Mono.CSharp.Evaluator.MessageOutput;
            var  errorWriter = new System.IO.StringWriter();
            bool isPartial   = false;

//		Mono.CSharp.Evaluator.MessageOutput = errorWriter;
            SetEvaluatorMessageOutput(errorWriter);
            try {
//			isPartial = Mono.CSharp.Evaluator.Evaluate(code, out ret, out hasReturnValue) != null;
                isPartial = evaluatorInstance.Evaluate(code, out ret, out hasReturnValue) != null;
            } catch (System.Exception e) {
                errorWriter.Write(e.Message);
            }
//		Mono.CSharp.Evaluator.MessageOutput = originalOutput;
            SetDefaultEvaluatorMessageOutput();

            var error = errorWriter.ToString();

            if (!string.IsNullOrEmpty(error))
            {
                error = error.Replace("{interactive}", "");
                var lastLineBreakPos = error.LastIndexOf('\n');
                if (lastLineBreakPos != -1)
                {
                    error = error.Remove(lastLineBreakPos);
                }
                result.type  = CompileResult.Type.Error;
                result.error = error;
                return(result);
            }
            errorWriter.Dispose();

            if (isPartial)
            {
                result.type = CompileResult.Type.Partial;
                return(result);
            }

            result.type  = CompileResult.Type.Success;
            result.value = (hasReturnValue && ret != null) ? ret : "null";
            return(result);
        }
Beispiel #52
0
    static public System.IO.StringWriter ExportToExcelXML(DataSet source)
    {
        System.IO.StringWriter excelDoc;

        excelDoc = new System.IO.StringWriter();

        StringBuilder ExcelXML = new StringBuilder();

        ExcelXML.Append("<xml version>\r\n<Workbook ");

        ExcelXML.Append("xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");

        ExcelXML.Append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n ");

        ExcelXML.Append("xmlns:x=\"urn:schemas- microsoft-com:office:");

        ExcelXML.Append("excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:");

        ExcelXML.Append("office:spreadsheet\">\r\n <Styles>\r\n ");

        ExcelXML.Append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n ");

        ExcelXML.Append("<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>");

        ExcelXML.Append("\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>");

        ExcelXML.Append("\r\n <Protection/>\r\n </Style>\r\n ");

        ExcelXML.Append("<Style ss:ID=\"BoldColumn\">\r\n <Font ");

        ExcelXML.Append("x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n ");

        ExcelXML.Append("<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat");

        ExcelXML.Append(" ss:Format=\"@\"/>\r\n </Style>\r\n <Style ");

        ExcelXML.Append("ss:ID=\"Decimal\">\r\n <NumberFormat ");

        ExcelXML.Append("ss:Format=\"0.0000\"/>\r\n </Style>\r\n ");

        ExcelXML.Append("<Style ss:ID=\"Integer\">\r\n <NumberFormat ");

        ExcelXML.Append("ss:Format=\"0\"/>\r\n </Style>\r\n <Style ");

        ExcelXML.Append("ss:ID=\"DateLiteral\">\r\n <NumberFormat ");
        ExcelXML.Append("ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n ");

        //ExcelXML.Append("<Style ss:ID=\"s28\">\r\n");

        //ExcelXML.Append("<Alignment ss:Horizontal=\"Left\" ss:Vertical=\"Top\" ss:ReadingOrder=\"LeftToRight\" ss:WrapText=\"1\"/>\r\n");

        //ExcelXML.Append("<Font x:CharSet=\"1\" ss:Size=\"9\" ss:Color=\"#808080\" ss:Underline=\"Single\"/>\r\n");

        //ExcelXML.Append("<Interior ss:Color=\"#FFFFFF\" ss:Pattern=\"Solid\"/></Style>\r\n");

        ExcelXML.Append("</Styles>\r\n ");

        string startExcelXML = ExcelXML.ToString();

        const string endExcelXML = "</Workbook>";

        int rowCount = 0;

        int sheetCount = 1;

        excelDoc.Write(startExcelXML);

        excelDoc.Write("<Worksheet ss:Name=\"Report_Sheet" + sheetCount + "\">");

        excelDoc.Write("<Table>");

        ///Header Part

        // Add any Header for the report

        ///


        //excelDoc.Write("<Row ss:AutoFitHeight=\"0\" ss:Height=\"6.75\"/>\r\n");

        //excelDoc.Write("<Row><Cell ss:MergeAcross=\"10\" ss:StyleID=\"s28\"><Data ss:Type=\"String\">");

        //excelDoc.Write("HEADER TEXT");

        //excelDoc.Write("</Data></Cell>");

        //excelDoc.Write("<Cell ss:MergeAcross=\"1\" ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");

        //excelDoc.Write("Report Date");

        //excelDoc.Write("</Data></Cell>");

        //excelDoc.Write("<Cell ss:MergeAcross=\"1\" ss:StyleID=\"DateLiteral\"><Data ss:Type=\"String\">");

        //excelDoc.Write(DateTime.Now.ToShortDateString());

        //excelDoc.Write("</Data></Cell></Row>");

        //excelDoc.Write("<Row ss:AutoFitHeight=\"0\" ss:Height=\"10\"/>\r\n");

        ///Complete


        excelDoc.Write("<Row>");

        for (int x = 0; x < source.Tables[0].Columns.Count; x++)
        {
            excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");

            excelDoc.Write(source.Tables[0].Columns[x].ColumnName);

            excelDoc.Write("</Data></Cell>");
        }



        excelDoc.Write("</Row>");

        foreach (DataRow x in source.Tables[0].Rows)
        {
            rowCount++;

            //if the number of rows is > 63000 create a new page to continue output


            if (rowCount == 63000)
            {
                rowCount = 0;

                sheetCount++;

                excelDoc.Write("</Table>");

                excelDoc.Write(" </Worksheet>");

                excelDoc.Write("<Worksheet ss:Name=\"Report_Sheet" + sheetCount + "\">");

                excelDoc.Write("<Table>");



                excelDoc.Write("<Row>");

                for (int xi = 0; xi < source.Tables[0].Columns.Count; xi++)
                {
                    excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");

                    excelDoc.Write(source.Tables[0].Columns[xi].ColumnName);

                    excelDoc.Write("</Data></Cell>");
                }

                excelDoc.Write("</Row>");
            }

            excelDoc.Write("<Row>");

            for (int y = 0; y < source.Tables[0].Columns.Count; y++)
            {
                string XMLstring = x[y].ToString();

                XMLstring = XMLstring.Trim();

                //XMLstring = XMLstring.Replace("&", "&");

                //XMLstring = XMLstring.Replace(">", ">");

                //XMLstring = XMLstring.Replace("<", "<");

                excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" + "<Data ss:Type=\"String\">");

                excelDoc.Write("<![CDATA[" + XMLstring + "]]>");

                excelDoc.Write("</Data></Cell>");
            }

            excelDoc.Write("</Row>");
        }

        ///Ending Tag


        ///

        ///Complete

        excelDoc.Write("</Table>");

        excelDoc.Write(" </Worksheet>");


        excelDoc.Write(endExcelXML);

        return(excelDoc);
    }
        private void BtnGenerateLocation_Click(object sender, EventArgs e)
        {
            hr  = 8;
            min = 30;
            sec = 0;

            String query6 = "select Session,Room,'1' from RoomSession where Room LIKE '%" + cmbGenerateLocation2.Text + "%'";

            SqlCommand cmd = new SqlCommand(query6, con);

            con.Open();
            DataTable     dt  = new DataTable();
            SqlDataReader sdr = cmd.ExecuteReader();

            dt.Load(sdr);

            con.Close();

            dgridLocationTimetable.ColumnCount     = 8;
            dgridLocationTimetable.Columns[0].Name = "TimeSlot";
            dgridLocationTimetable.Columns[1].Name = "Monday";
            dgridLocationTimetable.Columns[2].Name = "Tuesday";
            dgridLocationTimetable.Columns[3].Name = "Wednesday";
            dgridLocationTimetable.Columns[4].Name = "Thursday";
            dgridLocationTimetable.Columns[5].Name = "Friday";
            dgridLocationTimetable.Columns[6].Name = "Saturday";
            dgridLocationTimetable.Columns[7].Name = "Sunday";

            System.IO.StringWriter sw;
            string output;
            int    xCount = 1;
            int    yCount = 0;

            string[,] Tablero = new string[5, 8];


            for (int k = 0; k < Tablero.GetLength(0); k++)
            {
                for (int l = 0; l < Tablero.GetLength(1); l++)
                {
                    Tablero[k, l] = " --- ";
                }
            }

            // Loop through each row in the table.
            foreach (DataRow row in dt.Rows)
            {
                sw = new System.IO.StringWriter();

                // Loop through each column.
                foreach (DataColumn col in dt.Columns)
                {
                    // Output the value of each column's data.
                    sw.Write(row[col].ToString() + "\n");
                }

                output = sw.ToString();

                // Trim off the trailing ", ", so the output looks correct.
                if (output.Length > 2)
                {
                    output = output.Substring(0, output.Length - 2);
                }


                if (yCount == 5)
                {
                    yCount = 0;
                    xCount++;
                }
                try
                {
                    Tablero[yCount, xCount] = output;
                    yCount++;
                }
                catch (Exception ex)
                {
                }
            }

            do
            {
                foreach (DataGridViewRow row in dgridLocationTimetable.Rows)
                {
                    try
                    {
                        dgridLocationTimetable.Rows.Remove(row);
                    }
                    catch (Exception) { }
                }
            } while (dgridLocationTimetable.Rows.Count > 1);


            for (int k = 0; k < Tablero.GetLength(0); k++)
            {
                var arlist1 = new System.Collections.ArrayList();

                for (int l = 0; l < Tablero.GetLength(1); l++)
                {
                    arlist1.Add(Tablero[k, l]);
                }

                string srrr  = (string)arlist1[1];
                string srrr2 = srrr.Substring(srrr.Length - 2);

                string[] row = new string[] {
                    hr + "." + min,
                    (string)arlist1[1],
                    (string)arlist1[2],
                    (string)arlist1[3],
                    (string)arlist1[4],
                    (string)arlist1[5],
                    (string)arlist1[6],
                    (string)arlist1[7]
                };

                try
                {
                    timeCalc(int.Parse(srrr2.Trim()), 0, 0);
                }
                catch (Exception ex)
                {
                }

                dgridLocationTimetable.Rows.Add(row);
            }
        }
        private string BuildInternal()
        {
            var nsisMake = DetectNsisMake();

            VerifyMinimumSupportedVersion(nsisMake);

            string regRootKey   = null;
            string regSubKey    = null;
            string regValueName = null;

            if (Prerequisite.RegKeyValue != null)
            {
                var regKeyTokens = Prerequisite.RegKeyValue.Split(':');

                if (regKeyTokens.Length != 3)
                {
                    throw new ArgumentException($"Prerequisite.RegKeyValue: {Prerequisite.RegKeyValue}.\nThis value must comply with the following pattern: <RegistryHive>:<KeyPath>:<ValueName>.");
                }

                regRootKey   = regKeyTokens[0];
                regSubKey    = regKeyTokens[1];
                regValueName = regKeyTokens[2];
            }

            var nsiFile = IO.Path.ChangeExtension(OutputFile, ".nsi");

            if (nsiFile == null)
            {
                throw new InvalidOperationException("NSI script file name can't be null.");
            }

            var builder = new StringBuilder();

            using (var writer = new IO.StringWriter(builder))
            {
                writer.WriteLine("Unicode true");
                writer.WriteLine("ManifestSupportedOS all");

                AddIncludes(writer);

                AddMacros(writer);

                if (IconFile != null)
                {
                    writer.WriteLine($"Icon \"{IO.Path.GetFullPath(IconFile)}\"");
                }
                writer.WriteLine($"OutFile \"{IO.Path.GetFullPath(OutputFile)}\"");

                writer.WriteLine($"RequestExecutionLevel {ExecutionLevelToString(RequestExecutionLevel)}");
                writer.WriteLine("SilentInstall silent");

                AddVersionInformation(writer);

                writer.WriteLine("Function .onInit");
                writer.WriteLine("InitPluginsDir");

                // Read command line parameters
                writer.WriteLine("${GetParameters} $R0");

                var versionCheckScript = OSValidation.BuildVersionCheckScriptPart();
                if (!string.IsNullOrEmpty(versionCheckScript))
                {
                    writer.Write(versionCheckScript);
                }

                AddSplashScreen(writer);

                AddPrerequisiteFile(writer, regRootKey, regSubKey, regValueName);

                AddPrimaryFile(writer);

                writer.WriteLine("end:");
                writer.WriteLine("FunctionEnd");

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

            NsiSourceGenerated?.Invoke(builder);

            IO.File.WriteAllText(nsiFile, builder.ToString());

            var output = ExecuteNsisMake(nsisMake, $"/INPUTCHARSET UTF8 {nsiFile} {OptionalArguments}");

            if (!string.IsNullOrEmpty(output))
            {
                Console.WriteLine(output);
            }

            // Return null if the OutputFile is failed to generate
            if (!IO.File.Exists(OutputFile))
            {
                return(null);
            }

            if (!Compiler.PreserveTempFiles)
            {
                IO.File.Delete(nsiFile);
            }

            DigitalSignature?.Apply(OutputFile);

            return(OutputFile);
        }
        public string GetData()
        {
            System.IO.StringWriter sw = new System.IO.StringWriter();
            sw.WriteLine("BEGIN:VCALENDAR");
            sw.WriteLine("VERSION:2.0");
            foreach (vEvent ev in this.Events)
            {
                sw.WriteLine("BEGIN:VEVENT");

                foreach (Attendee attendee in ev.Attendees)
                {
                    sw.WriteLine(string.Format("ATTENDEE;CN={0};ROLE={1};RSVP={2};MAILTO:{3}", attendee.Contact.Name, attendee.Role, "True", attendee.Contact.Email));
                }

                sw.Write("DTSTART:"); sw.WriteLine(GetUniversalDate(ev.Start));
                sw.Write("DTEND:"); sw.WriteLine(GetUniversalDate(ev.End));

                sw.Write("LOCATION:"); sw.WriteLine(ev.Location);

                //sw.WriteLine("TRANSP:OPAQUE");
                //sw.WriteLine("SEQUENCE");
                sw.Write("UID:"); sw.WriteLine(ev.Uid);

                //sw.WriteLine("DTSTAMP");

                sw.Write("DESCRIPTION:"); sw.WriteLine(ev.Description);

                sw.Write("SUMMARY:"); sw.WriteLine(ev.Summary);

                sw.Write("PRIORITY:"); sw.WriteLine(ev.Priority.ToString());

                sw.Write("CLASS:"); sw.WriteLine(ev.Classification.ToString());

                // Alarms
                //foreach(

                sw.WriteLine("END:VEVENT");
            }

            sw.WriteLine("END:VCALENDAR");

            return(sw.ToString());
            //TODO : CRLFSPACE
            //System.IO.StringWriter sw = new System.IO.StringWriter();
            //sw.WriteLine("BEGIN:VCARD");
            //sw.WriteLine("VERSION:3.0");
            //if (this.FullName != null) sw.WriteLine("FN:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.FullName));
            //if (this.DisplayName != null) sw.WriteLine("NAME:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.DisplayName));
            //if (this.GeneratorId != null) sw.WriteLine("PRODID:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.GeneratorId));
            //if (this.Mailer != null) sw.WriteLine("MAILER:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.Mailer));
            //if (this.Nickname != null) sw.WriteLine("NICKNAME:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.Nickname));
            //if (this.Note != null) sw.WriteLine("NOTE:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.Note));
            //if (this.Role != null) sw.WriteLine("ROLE:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.Role));
            //if (this.SortText != null) sw.WriteLine("SORT-STRING:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.SortText));
            //if (this.Source != null) sw.WriteLine("SOURCE:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.Source));
            //if (this.TimeZone != null) sw.WriteLine("TZ:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.TimeZone));
            //if (this.Title != null) sw.WriteLine("TITLE:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.Title));
            //if (this.AccessClass != null) sw.WriteLine("CLASS:" + ActiveUp.Net.Groupware.vCard.Parser.Escape(this.AccessClass));
            //if (this.Addresses.Count > 0) foreach (ActiveUp.Net.Groupware.vCard.Address address in this.Addresses) sw.WriteLine(address.GetFormattedLine());
            //if (this.EmailAddresses.Count > 0) foreach (ActiveUp.Net.Groupware.vCard.EmailAddress email in this.EmailAddresses) sw.WriteLine(email.GetFormattedLine());
            //if (this.Labels.Count > 0) foreach (ActiveUp.Net.Groupware.vCard.Label label in this.Labels) sw.WriteLine(label.GetFormattedLine());
            //if (this.TelephoneNumbers.Count > 0) foreach (ActiveUp.Net.Groupware.vCard.TelephoneNumber number in this.TelephoneNumbers) sw.WriteLine(number.GetFormattedLine());
            //if (this.Name != null) sw.WriteLine(this.Name.GetFormattedLine());
            //if (this.Birthday != System.DateTime.MinValue) sw.WriteLine("BDAY:" + this.Birthday.ToString("yyyy-MM-dd"));
            //if (this.GeographicalPosition != null && (this.GeographicalPosition.Latitude != 0 && this.GeographicalPosition.Longitude != 0)) sw.WriteLine("GEO:" + this.GeographicalPosition.Latitude.ToString() + ";" + this.GeographicalPosition.Longitude.ToString());
            ////if(this.Organization!=null && this.Organization.Length>0)
            //if (this.Organization != null && this.Organization.Count > 0)
            //{
            //    string organization = "ORG:";
            //    foreach (string str in this.Organization) organization += ActiveUp.Net.Groupware.vCard.Parser.Escape(str) + ",";
            //    organization = organization.TrimEnd(',');
            //    sw.WriteLine(organization);
            //}
            ////if (this.Categories != null && this.Categories.Length > 0)
            //if (this.Categories != null && this.Categories.Count > 0)
            //{
            //    string categories = "CATEGORIES:";
            //    foreach (string str in this.Categories) categories += ActiveUp.Net.Groupware.vCard.Parser.Escape(str) + ",";
            //    categories = categories.TrimEnd(',');
            //    sw.WriteLine(categories);
            //}
            //if (this.Photo != null && this.Photo.Length > 0)
            //{
            //    string binary = "PHOTO:" + System.Convert.ToBase64String(this.Photo);
            //    sw.WriteLine(binary);
            //}
            //sw.WriteLine("REV:" + System.DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"));
            //sw.WriteLine("END:VCARD");
            //return ActiveUp.Net.Groupware.vCard.Parser.Fold(sw.ToString());
        }
Beispiel #56
0
    protected void btnText_Click(object sender, EventArgs e)
    {
        string    sSql = "", StrAppend = "";
        DataTable dtNewDetails = new DataTable();
        DataTable dtCheck      = new DataTable();

        //DataTable dtSmry = new DataTable();
        System.IO.StringWriter    sWriter;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sWriter = new System.IO.StringWriter(sb);


        if (ViewState["PrintDetails"] != null)
        {
            dtNewDetails = (DataTable)ViewState["PrintDetails"];
        }

        try
        {
            //objLog.WriteLog("CheBukFormatPrint.aspx: btnText_Click");
            if (dtNewDetails.Rows.Count > 0)
            {
                //objLog.WriteLog("CheBukFormatPrint.aspx: btnText_Click:Record Count" +dtNewDetails.Rows.Count);
                foreach (DataRow drPrint in dtNewDetails.Rows)
                {
                    //objLog.WriteLog("CheBukFormatPrint.aspx: btnText_Click:Processing First Record");
                    if (StrAppend == "")
                    {
                        StrAppend = "~";
                    }

                    if (StrAppend == "0")
                    {
                        StrAppend = "~";
                    }

                    StrAppend  = drPrint["Serial No"].ToString() + "~";
                    StrAppend += drPrint["City Code"].ToString() + "~";
                    StrAppend += drPrint["Bank code"].ToString() + "~";
                    StrAppend += drPrint["Branch Code"].ToString() + "~";
                    StrAppend += drPrint["Reference Code"].ToString() + "~";
                    StrAppend += drPrint["MICR Code"].ToString() + "~";
                    StrAppend += drPrint["Account No."].ToString() + "~";
                    StrAppend += drPrint["Transaction Code"].ToString() + "~";
                    StrAppend += drPrint["Customer Name"].ToString() + "~";
                    StrAppend += drPrint["Jointholder Name"].ToString() + "~";
                    StrAppend += drPrint["Jointholder Name2"].ToString() + "~";
                    StrAppend += drPrint["Sign Authority"].ToString() + "~";
                    StrAppend += drPrint["SA2"].ToString() + "~";
                    StrAppend += drPrint["SA2"].ToString() + "~";
                    StrAppend += drPrint["Address1"].ToString() + "~";
                    StrAppend += drPrint["Address2"].ToString() + "~";
                    StrAppend += drPrint["Address3"].ToString() + "~";
                    StrAppend += drPrint["Address4"].ToString() + "~";
                    StrAppend += drPrint["Address5"].ToString() + "~";
                    StrAppend += drPrint["City Name"].ToString() + "~";
                    StrAppend += drPrint["PINCODE"].ToString() + "~";
                    StrAppend += drPrint["Res Tel No."].ToString() + "~";
                    StrAppend += drPrint["Off Tel No"].ToString() + "~";
                    StrAppend += drPrint["Mob No"].ToString() + "~";
                    StrAppend += drPrint["Book Size"].ToString() + "~";
                    StrAppend += drPrint["No. of Leaves"].ToString() + "~";

                    StrAppend += drPrint["Bearer/Order"].ToString() + "~";
                    StrAppend += drPrint["At Par Y/N"].ToString() + "~";
                    StrAppend += drPrint["Product Code"].ToString() + "~";
                    StrAppend += drPrint["From Leaf Num"].ToString() + "~";
                    StrAppend += drPrint["To Leaf Num"].ToString() + "~";

                    StrAppend += drPrint["AddOpenField1"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField2"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField3"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField4"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField5"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField6"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField7"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField8"].ToString() + "~";
                    StrAppend += drPrint["AddOpenField9"].ToString();

                    // StrAppend += drPrint["IFSC Code"].ToString();

                    sWriter.Write(StrAppend);
                    sWriter.WriteLine();
                    StrAppend = "";


                    sSql  = " UPDATE CHEQUEH SET  CHQH_PRINTEDYN = 'Y' ";
                    sSql += " WHERE CHQH_SNO= '" + drPrint["Cheque Sno"].ToString() + "'";
                    objDataFetch.loginconnection = Session["constring"].ToString();
                    objDataFetch.ExecuteQuery(sSql);
                }
                sWriter.Close();
                string sLogPath = HttpContext.Current.Server.MapPath("PRINT/" + getLogFileName());
                System.IO.File.WriteAllText(sLogPath, sWriter.ToString());
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Text File Successfully written to " + sLogPath + " ')</script>");
                return;
            }
//objLog.WriteLog("CheBukFormatPrint.aspx: btnText_Click:successfully Completed");
            else
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('No data found')</script>");
                return;
            }
        }
        catch (Exception ex)
        {
            objLog.WriteLog("ChkBukDisp Exception in btnText_Click Event : " + ex.Message);
            string m = ex.Message;
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Could Not Convert to Text File')</script>");
            //       //AK+LS 02/04/2016 missing log
        }
        finally
        {
            if (oraConn.State == ConnectionState.Open)
            {
                oraConn.Close();
            }
            oraConn.Dispose();
            OracleConnection.ClearAllPools();
            objLog.WriteLog("CheBukDisp.aspx---> btnText_Click---> btnText_Click event reached finally block");
            // //AK+LS 02/04/2016 log missing
        }
        //AK+LS 02/04/2016 finally block missing
    }