Beispiel #1
0
        public static void Main(string[] args)
        {
            nick = "SecureIRC";
            owner = "SecureIRC";
            server = "irc.entalyan.com";
            port = 6999;
            chan = "#SecureIRC";
            pass = ""; //Enter just the password

            //Connect to irc server and get input and output text streams from TcpClient.
            sock.Connect(server, port);
            if (!sock.Connected)
            {
                Console.WriteLine("Failed to connect!");
                return;
            }
            input = new System.IO.StreamReader(sock.GetStream());
            output = new System.IO.StreamWriter(sock.GetStream());

            //Starting USER and NICK login commands 
            output.Write(
                "PASS " + nick + ":" + pass + "\r\n" +
                "USER " + nick + " 0 * :" + owner + "\r\n" +
                "NICK " + nick + "\r\n" +
                "PRIVMSG #SecureIRC Successful login at: " + DateTime.Now.ToString() + "\r\n"
            );
            output.Flush();

            Listen();

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

        }
        /// <summary>
        /// Formats a complete HTML document describing the given 
        /// <see cref="Error"/> instance.
        /// </summary>

        public override void Format(TextWriter writer, Error error)
        {
            if (writer == null) throw new ArgumentNullException("writer");
            if (error == null) throw new ArgumentNullException("error");

            var page = new ErrorMailHtmlPage(error);
            writer.Write(page.TransformText());
        }
Beispiel #3
0
 protected override void DumpChildren(TextWriter Out, uint Depth)
 {
     foreach (VEntry e in Fields.Values) {
     Indent(Out, Depth);
     Out.Write(e.Name);
     Out.WriteLine(" =");
     e.Value.Dump(Out, Depth+1);
     }
 }
/**        Need to take note of AlwaysDoubleQuotePropertyNames when writing property type
Always escape property name with double quotes
**/
 int writeTypeAliasProperty(TextWriter writer, Object to, TypeAliaser typeAliaser, int currentFramePropertyCount)
        {
            if (typeAliaser != null)
            {
                if (currentFramePropertyCount > 0) writer.Write(',');
                string strAliasPropertyWrapper = AlwaysDoubleQuotePropertyNames ? "\"" : "";
                writer.Write(strAliasPropertyWrapper + this.TypeAliasProperty + strAliasPropertyWrapper + ":\"" + typeAliaser(to.GetType()) + "\"");
                return 1;
            }
            else
            {
                return 0;
            }
        }
Beispiel #5
0
        // This method is REQUIRED if the template contains any Razor helpers, but you may choose to implement it differently
        //
        /// <summary>
        /// Conditionally writes an attribute to a TextWriter.
        /// </summary>
        /// <param name="writer">The TextWriter to which to write the attribute.</param>
        /// <param name="name">The name of the attribute.</param>
        /// <param name="prefix">The prefix of the attribute.</param>
        /// <param name="suffix">The suffix of the attribute.</param>
        /// <param name="values">Attribute values, each specifying a prefix, value and whether it's a literal.</param>
        ///<remarks>Used by Razor helpers to write attributes.</remarks>
        protected static void WriteAttributeTo(System.IO.TextWriter writer, string name, string prefix, string suffix, params Tuple <string, object, bool>[] values)
        {
            // this is based on System.Web.WebPages.WebPageExecutingBase
            // Copyright (c) Microsoft Open Technologies, Inc.
            // Licensed under the Apache License, Version 2.0
            if (values.Length == 0)
            {
                // Explicitly empty attribute, so write the prefix and suffix
                writer.Write(prefix);
                writer.Write(suffix);
                return;
            }

            bool first          = true;
            bool wroteSomething = false;

            for (int i = 0; i < values.Length; i++)
            {
                Tuple <string, object, bool> attrVal = values [i];
                string attPrefix = attrVal.Item1;
                object value     = attrVal.Item2;
                bool   isLiteral = attrVal.Item3;

                if (value == null)
                {
                    // Nothing to write
                    continue;
                }

                // The special cases here are that the value we're writing might already be a string, or that the
                // value might be a bool. If the value is the bool 'true' we want to write the attribute name instead
                // of the string 'true'. If the value is the bool 'false' we don't want to write anything.
                //
                // Otherwise the value is another object (perhaps an IHtmlString), and we'll ask it to format itself.
                string stringValue;
                bool?  boolValue = value as bool?;
                if (boolValue == true)
                {
                    stringValue = name;
                }
                else if (boolValue == false)
                {
                    continue;
                }
                else
                {
                    stringValue = value as string;
                }

                if (first)
                {
                    writer.Write(prefix);
                    first = false;
                }
                else
                {
                    writer.Write(attPrefix);
                }

                if (isLiteral)
                {
                    writer.Write(stringValue ?? value);
                }
                else
                {
                    WriteTo(writer, stringValue ?? value);
                }
                wroteSomething = true;
            }
            if (wroteSomething)
            {
                writer.Write(suffix);
            }
        }
Beispiel #6
0
 // This method is REQUIRED, but you may choose to implement it differently
 //
 /// <summary>Writes a literal value to the template output without HTML escaping it.</summary>
 /// <param name="value">The literal value.</param>
 protected void WriteLiteral(string value)
 {
     __razor_writer.Write(value);
 }
Beispiel #7
0
 protected void dump_SimboloAbstracto(System.IO.TextWriter cout, int n, SimboloAbstracto sym)
 {
     cout.Write(Utilidades.pad(n));
     cout.WriteLine(sym.Texto);
 }
Beispiel #8
0
        public static Test.ITestIntfPrx allTests(TestHelper helper)
        {
            Communicator?communicator = helper.Communicator();

            TestHelper.Assert(communicator != null);
            string sref = "test:" + helper.GetTestEndpoint(0);
            var    obj  = IObjectPrx.Parse(sref, communicator);

            TestHelper.Assert(obj != null);
            var proxy = Test.ITestIntfPrx.UncheckedCast(obj);

            TestHelper.Assert(proxy != null);

            System.IO.TextWriter output = helper.GetWriter();

            output.Write("testing enum values... ");
            output.Flush();

            TestHelper.Assert((int)Test.ByteEnum.benum1 == 0);
            TestHelper.Assert((int)Test.ByteEnum.benum2 == 1);
            TestHelper.Assert((int)Test.ByteEnum.benum3 == Test.Constants.ByteConst1);
            TestHelper.Assert((int)Test.ByteEnum.benum4 == Test.Constants.ByteConst1 + 1);
            TestHelper.Assert((int)Test.ByteEnum.benum5 == Test.Constants.ShortConst1);
            TestHelper.Assert((int)Test.ByteEnum.benum6 == Test.Constants.ShortConst1 + 1);
            TestHelper.Assert((int)Test.ByteEnum.benum7 == Test.Constants.IntConst1);
            TestHelper.Assert((int)Test.ByteEnum.benum8 == Test.Constants.IntConst1 + 1);
            TestHelper.Assert((int)Test.ByteEnum.benum9 == Test.Constants.LongConst1);
            TestHelper.Assert((int)Test.ByteEnum.benum10 == Test.Constants.LongConst1 + 1);
            TestHelper.Assert((int)Test.ByteEnum.benum11 == Test.Constants.ByteConst2);

            TestHelper.Assert((int)Test.ShortEnum.senum1 == 3);
            TestHelper.Assert((int)Test.ShortEnum.senum2 == 4);
            TestHelper.Assert((int)Test.ShortEnum.senum3 == Test.Constants.ByteConst1);
            TestHelper.Assert((int)Test.ShortEnum.senum4 == Test.Constants.ByteConst1 + 1);
            TestHelper.Assert((int)Test.ShortEnum.senum5 == Test.Constants.ShortConst1);
            TestHelper.Assert((int)Test.ShortEnum.senum6 == Test.Constants.ShortConst1 + 1);
            TestHelper.Assert((int)Test.ShortEnum.senum7 == Test.Constants.IntConst1);
            TestHelper.Assert((int)Test.ShortEnum.senum8 == Test.Constants.IntConst1 + 1);
            TestHelper.Assert((int)Test.ShortEnum.senum9 == Test.Constants.LongConst1);
            TestHelper.Assert((int)Test.ShortEnum.senum10 == Test.Constants.LongConst1 + 1);
            TestHelper.Assert((int)Test.ShortEnum.senum11 == Test.Constants.ShortConst2);

            TestHelper.Assert((int)Test.IntEnum.ienum1 == 0);
            TestHelper.Assert((int)Test.IntEnum.ienum2 == 1);
            TestHelper.Assert((int)Test.IntEnum.ienum3 == Test.Constants.ByteConst1);
            TestHelper.Assert((int)Test.IntEnum.ienum4 == Test.Constants.ByteConst1 + 1);
            TestHelper.Assert((int)Test.IntEnum.ienum5 == Test.Constants.ShortConst1);
            TestHelper.Assert((int)Test.IntEnum.ienum6 == Test.Constants.ShortConst1 + 1);
            TestHelper.Assert((int)Test.IntEnum.ienum7 == Test.Constants.IntConst1);
            TestHelper.Assert((int)Test.IntEnum.ienum8 == Test.Constants.IntConst1 + 1);
            TestHelper.Assert((int)Test.IntEnum.ienum9 == Test.Constants.LongConst1);
            TestHelper.Assert((int)Test.IntEnum.ienum10 == Test.Constants.LongConst1 + 1);
            TestHelper.Assert((int)Test.IntEnum.ienum11 == Test.Constants.IntConst2);
            TestHelper.Assert((int)Test.IntEnum.ienum12 == Test.Constants.LongConst2);

            TestHelper.Assert((int)Test.SimpleEnum.red == 0);
            TestHelper.Assert((int)Test.SimpleEnum.green == 1);
            TestHelper.Assert((int)Test.SimpleEnum.blue == 2);

            output.WriteLine("ok");

            output.Write("testing enum operations... ");
            output.Flush();
            {
                (Test.ByteEnum r, Test.ByteEnum o) = proxy.opByte(Test.ByteEnum.benum1);
                TestHelper.Assert(r == Test.ByteEnum.benum1 && o == Test.ByteEnum.benum1);
                (r, o) = proxy.opByte(Test.ByteEnum.benum11);
                TestHelper.Assert(r == Test.ByteEnum.benum11 && o == Test.ByteEnum.benum11);
            }

            {
                (Test.ShortEnum r, Test.ShortEnum o) = proxy.opShort(Test.ShortEnum.senum1);
                TestHelper.Assert(r == Test.ShortEnum.senum1 && o == Test.ShortEnum.senum1);
                (r, o) = proxy.opShort(Test.ShortEnum.senum11);
                TestHelper.Assert(r == Test.ShortEnum.senum11 && o == Test.ShortEnum.senum11);
            }

            {
                (Test.IntEnum r, Test.IntEnum o) = proxy.opInt(Test.IntEnum.ienum1);
                TestHelper.Assert(r == Test.IntEnum.ienum1 && o == Test.IntEnum.ienum1);
                (r, o) = proxy.opInt(Test.IntEnum.ienum11);
                TestHelper.Assert(r == Test.IntEnum.ienum11 && o == Test.IntEnum.ienum11);
                (r, o) = proxy.opInt(Test.IntEnum.ienum12);
                TestHelper.Assert(r == Test.IntEnum.ienum12 && o == Test.IntEnum.ienum12);
            }

            {
                (Test.SimpleEnum r, Test.SimpleEnum o) = proxy.opSimple(Test.SimpleEnum.green);
                TestHelper.Assert(r == Test.SimpleEnum.green && o == Test.SimpleEnum.green);
            }

            output.WriteLine("ok");

            output.Write("testing enum sequences operations... ");
            output.Flush();

            {
                var b1 = new Test.ByteEnum[11]
                {
                    Test.ByteEnum.benum1,
                    Test.ByteEnum.benum2,
                    Test.ByteEnum.benum3,
                    Test.ByteEnum.benum4,
                    Test.ByteEnum.benum5,
                    Test.ByteEnum.benum6,
                    Test.ByteEnum.benum7,
                    Test.ByteEnum.benum8,
                    Test.ByteEnum.benum9,
                    Test.ByteEnum.benum10,
                    Test.ByteEnum.benum11
                };

                (Test.ByteEnum[] b3, Test.ByteEnum[] b2) = proxy.opByteSeq(b1);

                for (int i = 0; i < b1.Length; ++i)
                {
                    TestHelper.Assert(b1[i] == b2[i]);
                    TestHelper.Assert(b1[i] == b3[i]);
                }
            }

            {
                var s1 = new Test.ShortEnum[11]
                {
                    Test.ShortEnum.senum1,
                    Test.ShortEnum.senum2,
                    Test.ShortEnum.senum3,
                    Test.ShortEnum.senum4,
                    Test.ShortEnum.senum5,
                    Test.ShortEnum.senum6,
                    Test.ShortEnum.senum7,
                    Test.ShortEnum.senum8,
                    Test.ShortEnum.senum9,
                    Test.ShortEnum.senum10,
                    Test.ShortEnum.senum11
                };

                (Test.ShortEnum[] s3, Test.ShortEnum[] s2) = proxy.opShortSeq(s1);

                for (int i = 0; i < s1.Length; ++i)
                {
                    TestHelper.Assert(s1[i] == s2[i]);
                    TestHelper.Assert(s1[i] == s3[i]);
                }
            }

            {
                var i1 = new Test.IntEnum[11]
                {
                    Test.IntEnum.ienum1,
                    Test.IntEnum.ienum2,
                    Test.IntEnum.ienum3,
                    Test.IntEnum.ienum4,
                    Test.IntEnum.ienum5,
                    Test.IntEnum.ienum6,
                    Test.IntEnum.ienum7,
                    Test.IntEnum.ienum8,
                    Test.IntEnum.ienum9,
                    Test.IntEnum.ienum10,
                    Test.IntEnum.ienum11
                };

                (Test.IntEnum[] i3, Test.IntEnum[] i2) = proxy.opIntSeq(i1);

                for (int i = 0; i < i1.Length; ++i)
                {
                    TestHelper.Assert(i1[i] == i2[i]);
                    TestHelper.Assert(i1[i] == i3[i]);
                }
            }

            {
                var s1 = new Test.SimpleEnum[3]
                {
                    Test.SimpleEnum.red,
                    Test.SimpleEnum.green,
                    Test.SimpleEnum.blue
                };

                (Test.SimpleEnum[] s3, Test.SimpleEnum[] s2) = proxy.opSimpleSeq(s1);

                for (int i = 0; i < s1.Length; ++i)
                {
                    TestHelper.Assert(s1[i] == s2[i]);
                    TestHelper.Assert(s1[i] == s3[i]);
                }
            }

            output.WriteLine("ok");
            return(proxy);
        }
Beispiel #9
0
 public void SaveAs(System.IO.TextWriter _textwriter)
 {
     this.AddRule(true, "Default", null, null, null, defaultRuleActionType, defaultRuleProxyID);
     _textwriter.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
     _textwriter.Write("\r\n<ProxifierProfile version=\"101\" platform=\"Windows\" product_id=\"1\" product_minver=\"310\">");
     _textwriter.Write("\r\n" + profileOptions());
     if (this.innerProxyList.Count > 0)
     {
         _textwriter.Write("\r\n" + profileProxyList());
     }
     else
     {
         _textwriter.Write("\r\n  <ProxyList />");
     }
     if (this.innerChainList.Count > 0)
     {
         _textwriter.Write("\r\n" + profileChain());
     }
     else
     {
         _textwriter.Write("\r\n  <ChainList />");
     }
     _textwriter.Write("\r\n  <RuleList>");
     if (this.innerRuleList.Count > 0)
     {
         _textwriter.Write("\r\n" + profileRuleList());
     }
     _textwriter.Write("\r\n  </RuleList>");
     _textwriter.Write("\r\n</ProxifierProfile>");
     _textwriter.Flush();
 }
Beispiel #10
0
		public virtual void  xmlSerializeRootClose(TextWriter outWriter)
		{
			outWriter.Write("</" + GetType().FullName + ">\n");
		}
Beispiel #11
0
 protected override void WriteTriviaTo(System.IO.TextWriter writer)
 {
     writer.Write(Text);
 }
Beispiel #12
0
        public static void RunWithController(TestHelper helper, IControllerPrx controller)
        {
            Communicator?communicator = helper.Communicator;

            TestHelper.Assert(communicator != null);
            bool ice1 = TestHelper.GetTestProtocol(communicator.GetProperties()) == Protocol.Ice1;

            var timeout = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), communicator);

            System.IO.TextWriter output = helper.Output;
            output.Write("testing connect timeout... ");
            output.Flush();
            {
                Dictionary <string, string>?properties = communicator.GetProperties();
                properties["Ice.ConnectTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                // Expect ConnectTimeoutException.
                controller.HoldAdapter(-1);
                try
                {
                    to.Op();
                    TestHelper.Assert(false);
                }
                catch (ConnectTimeoutException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                // Expect success.
                controller.HoldAdapter(100);
                timeout.Op();
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeout... ");
            output.Flush();
            {
                timeout.IcePing(); // Makes sure a working connection is associated with the proxy
                Connection?connection = timeout.GetConnection();
                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(100)).SleepAsync(1000).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                }
                timeout.IcePing();

                TestHelper.Assert(connection == timeout.GetConnection());
                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(1000)).SleepAsync(100).Wait();
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                    TestHelper.Assert(false);
                }
                TestHelper.Assert(connection == timeout.GetConnection());

                try
                {
                    timeout.Clone(invocationTimeout: TimeSpan.FromMilliseconds(100)).Sleep(1000);
                    TestHelper.Assert(false);
                }
                catch (OperationCanceledException)
                {
                }
            }
            output.WriteLine("ok");

            output.Write("testing close timeout... ");
            output.Flush();
            {
                Dictionary <string, string> properties = communicator.GetProperties();
                properties["Ice.CloseTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                Connection?connection  = to.GetConnection();
                Connection?connection2 = timeout.GetConnection();  // No close timeout

                TestHelper.Assert(connection != null && connection2 != null);

                controller.HoldAdapter(-1);

                // Make sure there's no ReadAsync pending
                _ = to.IcePingAsync();
                _ = timeout.IcePingAsync();

                var semaphore = new System.Threading.SemaphoreSlim(0);
                connection.Closed += (sender, args) => semaphore.Release();
                connection.GoAwayAsync();
                TestHelper.Assert(semaphore.Wait(500));

                connection2.Closed += (sender, args) => semaphore.Release();
                connection2.GoAwayAsync();
                TestHelper.Assert(!semaphore.Wait(500));

                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            output.WriteLine("ok");

            if (!ice1)
            {
                output.Write("testing deadlines... ");
                output.Flush();
                {
                    var comm1 = new Communicator(communicator.GetProperties());

                    comm1.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                        (target, request, next, cancel) =>
                    {
                        request.BinaryContextOverride.Add(10, ostr =>
                        {
                            var deadline = (request.Deadline - DateTime.UnixEpoch).TotalMilliseconds;
                            ostr.WriteVarLong((long)deadline);
                        });
                        return(next(target, request, cancel));
                    });

                    for (int i = 1000; i < 5000;)
                    {
                        i += 33;
                        ITimeoutPrx to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm1).Clone(
                            invocationTimeout: TimeSpan.FromMilliseconds(i));
                        TestHelper.Assert(to.CheckDeadline());
                    }
                }
                output.WriteLine("ok");
            }
            controller.Shutdown();
        }
Beispiel #13
0
        private static void Serialize(System.IO.TextWriter writer, IEnumerable <KeyValuePair <string, JValue> > value, int indentLevel, bool prettyPrint = false)
        {
            if (prettyPrint)
            {
                writer.WriteLine('{');
            }
            else
            {
                writer.Write('{');
            }

            int maxKeyLength = 0;

            if (prettyPrint)
            {
                foreach (var item in value)
                {
                    maxKeyLength = Math.Max(maxKeyLength, item.Key.Length);
                }

                maxKeyLength += 1;
            }

            bool isFirst = true;

            foreach (var item in value)
            {
                if (isFirst == false)
                {
                    if (prettyPrint)
                    {
                        writer.WriteLine(',');
                    }
                    else
                    {
                        writer.Write(',');
                    }
                }
                else
                {
                    isFirst = false;
                }

                if (prettyPrint)
                {
                    Indent(writer, indentLevel + 1);
                }

                writer.Write('"');
                writer.Write(item.Key);
                writer.Write('"');
                writer.Write(':');
                if (prettyPrint)
                {
                    Spaces(writer, maxKeyLength - item.Key.Length);
                }
                Serialize(writer, item.Value, indentLevel + 1, prettyPrint);
            }

            if (prettyPrint)
            {
                writer.WriteLine();
                Indent(writer, indentLevel);
            }

            writer.Write('}');
        }
Beispiel #14
0
 private static void WriteElementEnd(string elementName,
                                     System.IO.TextWriter writer)
 {
     writer.Write("</{0}>", elementName);
 }
Beispiel #15
0
 public void Print(System.IO.TextWriter output)
 {
     output.Write("IntegerConstant:{" + Constant.ToString() + "}");
 }
Beispiel #16
0
 public override void Write(char value)
 {
     InnerWriter.Write(value);
 }
 private void writePropertyName(string propertyName, TextWriter writer)
 {
     bool escapeRequired = this.AlwaysDoubleQuotePropertyNames || (propertyName.IndexOf('.') >= 0);
     if (escapeRequired) writer.Write('\"');
     writer.Write(propertyName);
     if (escapeRequired) writer.Write('\"');
 }
Beispiel #18
0
    /*
** Print a single opcode.  This routine is used for debugging only.
*/
    static void sqlite3VdbePrintOp( FILE pOut, int pc, Op pOp )
    {
      string zP4;
      string zPtr = null;
      string zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
      if ( pOut == null ) pOut = System.Console.Out;
      zP4 = displayP4( pOp, zPtr, 50 );
      string zOut = "";
      sqlite3_snprintf( 999, ref zOut, zFormat1, pc,
      sqlite3OpcodeName( pOp.opcode ), pOp.p1, pOp.p2, pOp.p3, zP4, pOp.p5,
#if  SQLITE_DEBUG
 pOp.zComment != null ? pOp.zComment : ""
#else
""
#endif
 );
      pOut.Write( zOut );
      //fflush(pOut);
    }
Beispiel #19
0
        public static async Task RunAsync(TestHelper helper)
        {
            bool ice2 = helper.Protocol == Protocol.Ice2;
            var  prx  = IMyObjectPrx.Parse(helper.GetTestProxy("test"), helper.Communicator !);

            System.IO.TextWriter output = helper.Output;

            output.Write("testing retry... ");
            output.Flush();
            TestHelper.Assert(prx.AddWithRetry(33, 12) == 45);
            output.WriteLine("ok");

            output.Write("testing remote exception... ");
            output.Flush();
            try
            {
                prx.BadAdd(33, 12);
                TestHelper.Assert(false);
            }
            catch (InvalidInputException)
            {
                // expected
            }
            output.WriteLine("ok");

            output.Write("testing ONE... ");
            output.Flush();
            try
            {
                prx.NotExistAdd(33, 12);
                TestHelper.Assert(false);
            }
            catch (ObjectNotExistException)
            {
                // expected
            }
            output.WriteLine("ok");

            output.Write("testing exceptions raised by the interceptor... ");
            output.Flush();
            var exceptions = new List <(string operation, string kind)>
            {
                ("raiseBeforeDispatch", "invalidInput"),
                ("raiseBeforeDispatch", "notExist"),
                ("raiseAfterDispatch", "invalidInput"),
                ("raiseAfterDispatch", "notExist")
            };

            foreach ((string operation, string kind) in exceptions)
            {
                var ctx = new Dictionary <string, string>
                {
                    { operation, kind }
                };

                try
                {
                    prx.IcePing(ctx);
                    TestHelper.Assert(false);
                }
                catch (InvalidInputException) when(kind == "invalidInput")
                {
                }
                catch (ObjectNotExistException) when(kind == "notExist")
                {
                }
            }
            output.WriteLine("ok");

            output.Write("testing invocation interceptors... ");
            output.Flush();
            {
                var tasks             = new List <Task>();
                var invocationContext = new AsyncLocal <int>();
                await using var communicator = new Communicator(prx.Communicator.GetProperties());

                communicator.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                    (target, request, next, cancel) =>
                {
                    request.WritableContext["interceptor-1"] = "interceptor-1";
                    if (ice2)
                    {
                        request.BinaryContextOverride.Add(110, ostr => ostr.WriteInt(110));
                    }
                    return(next(target, request, cancel));
                },
                    async(target, request, next, cancel) =>
                {
                    TestHelper.Assert(request.Context["interceptor-1"] == "interceptor-1");
                    request.WritableContext["interceptor-2"] = "interceptor-2";
                    if (ice2)
                    {
                        request.BinaryContextOverride.Add(120, ostr => ostr.WriteInt(120));
                    }
                    IncomingResponseFrame response = await next(target, request, cancel);
                    TestHelper.Assert(invocationContext.Value == int.Parse(request.Context["local-user"]));
                    if (ice2)
                    {
                        TestHelper.Assert(response.BinaryContext.ContainsKey(110));
                        TestHelper.Assert(response.BinaryContext[110].Read(istr => istr.ReadInt()) == 110);
                        TestHelper.Assert(response.BinaryContext.ContainsKey(120));
                        TestHelper.Assert(response.BinaryContext[120].Read(istr => istr.ReadInt()) == 120);
                    }
                    return(response);
                });

                await communicator.ActivateAsync();

                for (int i = 0; i < 10; ++i)
                {
                    invocationContext.Value = i;
                    var  prx1 = IMyObjectPrx.Parse(prx.ToString() !, communicator);
                    Task t    = prx1.Op1Async(new Dictionary <string, string> {
                        { "local-user", $"{i}" }
                    });
                    tasks.Add(t);
                }
                Task.WaitAll(tasks.ToArray());
            }

            {
                IncomingResponseFrame?response = null;
                int invocations = 0;
                // An interceptor can stop the chain and directly return a response without calling next,
                // the first invocation calls next and subsequent invocations reuse the first response.
                await using var communicator = new Communicator(prx.Communicator.GetProperties());

                communicator.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                    (target, request, next, cancel) =>
                {
                    request.WritableContext["interceptor-1"] = "interceptor-1";
                    return(next(target, request, cancel));
                },
                    async(target, request, next, cancel) =>
                {
                    if (response == null)
                    {
                        response = await next(target, request, cancel);
                    }
                    return(response);
                },
                    (target, request, next, cancel) =>
                {
                    invocations++;
                    TestHelper.Assert(response == null);
                    return(next(target, request, cancel));
                });

                TestHelper.Assert(communicator.DefaultInvocationInterceptors.Count == 3);
                await communicator.ActivateAsync();

                TestHelper.Assert(communicator.DefaultInvocationInterceptors.Count == 4);

                var prx1 = IMyObjectPrx.Parse(prx.ToString() !, communicator);

                // Truly reference equal
                TestHelper.Assert(prx1.InvocationInterceptors == communicator.DefaultInvocationInterceptors);

                prx1.Op1(new Dictionary <string, string> {
                    { "local-user", "10" }
                });
                prx1.Op1(new Dictionary <string, string> {
                    { "local-user", "11" }
                });
                prx1.Op1(new Dictionary <string, string> {
                    { "local-user", "12" }
                });
                TestHelper.Assert(invocations == 1);
            }

            {
                // throwing from an interceptor stops the interceptor chain
                await using var communicator = new Communicator(prx.Communicator.GetProperties());
                communicator.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                    (target, request, next, cancel) =>
                {
                    request.WritableContext["interceptor-1"] = "interceptor-1";
                    return(next(target, request, cancel));
                },
                    (target, request, next, cancel) =>
                {
                    TestHelper.Assert(request.Context["interceptor-1"] == "interceptor-1");
                    throw new InvalidOperationException("stop interceptor chain");
                },
                    (target, request, next, cancel) =>
                {
                    TestHelper.Assert(false);
                    return(next(target, request, cancel));
                });
                await communicator.ActivateAsync();

                var prx1 = IMyObjectPrx.Parse(prx.ToString() !, communicator);
                try
                {
                    prx1.Op1();
                    TestHelper.Assert(false);
                }
                catch (InvalidOperationException)
                {
                }
            }
            output.WriteLine("ok");

            output.Write("testing binary context... ");
            output.Flush();

            if (ice2)
            {
                for (int size = 128; size < 4096; size *= 2)
                {
                    var token = new Token(1, "mytoken", Enumerable.Range(0, size).Select(i => (byte)2).ToArray());

                    {
                        using var request = OutgoingRequestFrame.WithArgs(prx,
                                                                          "opWithBinaryContext",
                                                                          idempotent: false,
                                                                          compress: false,
                                                                          format: default,
                                                                          context: null,
                                                                          token,
                                                                          Token.IceWriter);
                        request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                        request.BinaryContextOverride.Add(3, ostr => ostr.WriteShort((short)size));
                        request.BinaryContextOverride.Add(
                            2,
                            ostr => ostr.WriteSequence(
                                Enumerable.Range(0, 10).Select(i => $"string-{i}").ToArray(),
                                (ostr, s) => ostr.WriteString(s)));

                        using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
                    }

                    {
                        // repeat with compressed frame
                        using OutgoingRequestFrame request = OutgoingRequestFrame.WithArgs(prx,
                                                                                           "opWithBinaryContext",
                                                                                           idempotent: false,
                                                                                           compress: false,
                                                                                           format: default,
                                                                                           context: null,
                                                                                           token,
                                                                                           Token.IceWriter);
                        request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                        request.BinaryContextOverride.Add(3, ostr => ostr.WriteShort((short)size));
                        request.BinaryContextOverride.Add(
                            2,
                            ostr => ostr.WriteSequence(
                                Enumerable.Range(0, 10).Select(i => $"string-{i}").ToArray(),
                                (ostr, s) => ostr.WriteString(s)));

                        TestHelper.Assert(request.CompressPayload() == CompressionResult.Success);
                        using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
                    }

                    {
                        // repeat compressed the frame before writing the context
                        using OutgoingRequestFrame request = OutgoingRequestFrame.WithArgs(prx,
                                                                                           "opWithBinaryContext",
                                                                                           idempotent: false,
                                                                                           compress: false,
                                                                                           format: default,
                                                                                           context: null,
                                                                                           token,
                                                                                           Token.IceWriter);

                        TestHelper.Assert(request.CompressPayload() == CompressionResult.Success);

                        request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                        request.BinaryContextOverride.Add(3, ostr => ostr.WriteShort((short)size));
                        request.BinaryContextOverride.Add(
                            2,
                            ostr => ostr.WriteSequence(
                                Enumerable.Range(0, 10).Select(i => $"string-{i}").ToArray(),
                                (ostr, s) => ostr.WriteString(s)));

                        using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
                    }
                }
            }
            else
            {
                var token = new Token(1, "mytoken", Enumerable.Range(0, 256).Select(i => (byte)2).ToArray());
                using var request = OutgoingRequestFrame.WithArgs(prx,
                                                                  "opWithBinaryContext",
                                                                  idempotent: false,
                                                                  compress: false,
                                                                  format: default,
                                                                  context: null,
                                                                  token,
                                                                  Token.IceWriter);
                try
                {
                    request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                    TestHelper.Assert(false);
                }
                catch (NotSupportedException)
                {
                }
                using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
            }
            output.WriteLine("ok");

            output.Write("testing per proxy invocation interceptors... ");
            output.Flush();
            {
                var communicator = helper.Communicator !;

                SortedDictionary <string, string>?context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(!context.ContainsKey("context3"));
                prx = prx.Clone(invocationInterceptors: ImmutableList.Create <InvocationInterceptor>(
                                    (target, request, next, cancel) =>
                {
                    request.WritableContext["context2"] = "proxy";
                    request.WritableContext["context3"] = "proxy";
                    return(next(target, request, cancel));
                }).AddRange(communicator.DefaultInvocationInterceptors));
                context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(context["context3"] == "proxy");

                // Calling next twice doesn't change the result
                prx = prx.Clone(invocationInterceptors: ImmutableList.Create <InvocationInterceptor>(
                                    (target, request, next, cancel) =>
                {
                    request.WritableContext["context2"] = "proxy";
                    request.WritableContext["context3"] = "proxy";
                    _ = next(target, request, cancel);
                    return(next(target, request, cancel));
                }).AddRange(communicator.DefaultInvocationInterceptors));
                context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(context["context3"] == "proxy");

                // Cloning the proxy preserve its interceptors
                prx     = prx.Clone(invocationTimeout: TimeSpan.FromSeconds(10));
                context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(context["context3"] == "proxy");

                // The server increments the result with each call when using the invocation interceptor we
                // return a cached response, and we will see the same result with each call.
                IncomingResponseFrame?response = null;
                prx = prx.Clone(invocationInterceptors: ImmutableList.Create <InvocationInterceptor>(
                                    async(target, request, next, cancel) =>
                {
                    response ??= await next(target, request, cancel);
                    return(response);
                }).AddRange(communicator.DefaultInvocationInterceptors));
                TestHelper.Assert(prx.Op3() == 0);
                TestHelper.Assert(prx.Op3() == 0);

                // After clearing the invocation interceptors we should see the result increase with each call
                prx = prx.Clone(invocationInterceptors: communicator.DefaultInvocationInterceptors);
                TestHelper.Assert(prx.Op3() == 1);
                TestHelper.Assert(prx.Op3() == 2);
            }
            output.WriteLine("ok");
            await prx.ShutdownAsync();
        }
Beispiel #20
0
        private void EmitLocals(string caption, TextWriter writer)
        {
            if (StackVarsOut.Count <= 0)
                return;

            writer.Write(caption);
            SortedList<string, string> list = new SortedList<string, string>();
            foreach (KeyValuePair<Storage, int> de in StackVarsOut)
            {
                Storage id = (Storage)de.Key;
                StringWriter sb = new StringWriter();
                id.Write(sb);
                string sName = sb.ToString();

                list[sName] = string.Format("{0}({1})", sName, de.Value);
            }
            foreach (string s in list.Values)
            {
                writer.Write(" ");
                writer.Write(s);
            }
            writer.WriteLine();
        }
Beispiel #21
0
            /// <summary>
            /// Writes fielddef as JSON. Do not call this method directly, instead call rowset.ToJSON() or use JSONWriter class
            /// </summary>
            void IJsonWritable.WriteAsJson(System.IO.TextWriter wri, int nestingLevel, JsonWritingOptions options)
            {
                var attr = this[null];

                if (attr != null && attr.NonUI)
                {
                    wri.Write("{}");
                    return;  //nothing to write for NONUI
                }

                bool   typeIsNullable;
                string tp = JSONMappings.MapCLRTypeToJSON(m_Type, out typeIsNullable);

                var map = new Dictionary <string, object>
                {
                    { "Name", m_Name },
                    { "Order", m_Order },
                    { "Type", tp },
                    { "Nullable", typeIsNullable }
                };

                //20190322 DKh inner schema
                if (typeof(Doc).IsAssignableFrom(this.NonNullableType))
                {
                    map["IsDataDoc"]   = true;
                    map["IsAmorphous"] = typeof(IAmorphousData).IsAssignableFrom(this.NonNullableType);
                    map["IsForm"]      = typeof(Form).IsAssignableFrom(this.NonNullableType);

                    if (typeof(TypedDoc).IsAssignableFrom(this.NonNullableType))
                    {
                        var innerSchema = Schema.GetForTypedDoc(this.NonNullableType);
                        if (innerSchema.Any(fd => typeof(TypedDoc).IsAssignableFrom(fd.Type)))
                        {
                            map["DataDocSchema"] = "@complex";
                        }
                        else
                        {
                            map["DataDocSchema"] = innerSchema;
                        }
                    }
                }

                if (attr != null)
                {
                    map.Add("IsKey", attr.Key);
                    map.Add("IsRequired", attr.Required);
                    map.Add("Visible", attr.Visible);
                    if (attr.Default != null)
                    {
                        map.Add("Default", attr.Default);
                    }
                    if (attr.CharCase != CharCase.AsIs)
                    {
                        map.Add("CharCase", attr.CharCase);
                    }
                    if (attr.Kind != DataKind.Text)
                    {
                        map.Add("Kind", attr.Kind);
                    }
                    if (attr.MinLength != 0)
                    {
                        map.Add("MinLen", attr.MinLength);
                    }
                    if (attr.MaxLength != 0)
                    {
                        map.Add("MaxLen", attr.MaxLength);
                    }
                    if (attr.Min != null)
                    {
                        map.Add("Min", attr.Min);
                    }
                    if (attr.Max != null)
                    {
                        map.Add("Max", attr.Max);
                    }
                    if (attr.ValueList != null)
                    {
                        map.Add("ValueList", attr.ValueList);
                    }
                    if (attr.Description != null)
                    {
                        map.Add("Description", attr.Description);
                    }
                    //metadata content is in the internal format and not dumped
                }

                JsonWriter.WriteMap(wri, map, nestingLevel, options);
            }
Beispiel #22
0
        public static async Task RunAsync(TestHelper helper)
        {
            Communicator communicator = helper.Communicator;

            System.IO.TextWriter output = helper.Output;
            var initial = IInitialPrx.Parse(helper.GetTestProxy("initial", 0), communicator);

            output.Write("getting proxies for interface hierarchy... ");
            output.Flush();
            MA.IAPrx? ia  = initial.Iaop();
            MB.IB1Prx?ib1 = initial.Ib1op();
            MB.IB2Prx?ib2 = initial.Ib2op();
            MA.ICPrx? ic  = initial.Icop();
            TestHelper.Assert(ia != null);
            TestHelper.Assert(ib1 != null);
            TestHelper.Assert(ib2 != null);
            TestHelper.Assert(ic != null);
            TestHelper.Assert(ia != ib1);
            TestHelper.Assert(ia != ib2);
            TestHelper.Assert(ia != ic);
            TestHelper.Assert(ib1 != ic);
            TestHelper.Assert(ib2 != ic);
            output.WriteLine("ok");

            output.Write("invoking proxy operations on interface hierarchy... ");
            output.Flush();
            MA.IAPrx? iao;
            MB.IB1Prx?ib1o;
            MB.IB2Prx?ib2o;
            MA.ICPrx? ico;

            iao = ia.Iaop(ia);
            TestHelper.Assert(iao !.Equals(ia));
            iao = ia.Iaop(ib1);
            TestHelper.Assert(iao !.Equals(ib1));
            iao = ia.Iaop(ib2);
            TestHelper.Assert(iao !.Equals(ib2));
            iao = ia.Iaop(ic);
            TestHelper.Assert(iao !.Equals(ic));
            iao = ib1.Iaop(ia);
            TestHelper.Assert(iao !.Equals(ia));
            iao = ib1.Iaop(ib1);
            TestHelper.Assert(iao !.Equals(ib1));
            iao = ib1.Iaop(ib2);
            TestHelper.Assert(iao !.Equals(ib2));
            iao = ib1.Iaop(ic);
            TestHelper.Assert(iao !.Equals(ic));
            iao = ib2.Iaop(ia);
            TestHelper.Assert(iao !.Equals(ia));
            iao = ib2.Iaop(ib1);
            TestHelper.Assert(iao !.Equals(ib1));
            iao = ib2.Iaop(ib2);
            TestHelper.Assert(iao !.Equals(ib2));
            iao = ib2.Iaop(ic);
            TestHelper.Assert(iao !.Equals(ic));
            iao = ic.Iaop(ia);
            TestHelper.Assert(iao !.Equals(ia));
            iao = ic.Iaop(ib1);
            TestHelper.Assert(iao !.Equals(ib1));
            iao = ic.Iaop(ib2);
            TestHelper.Assert(iao !.Equals(ib2));
            iao = ic.Iaop(ic);
            TestHelper.Assert(iao !.Equals(ic));

            iao = ib1.Ib1op(ib1);
            TestHelper.Assert(iao !.Equals(ib1));
            ib1o = ib1.Ib1op(ib1);
            TestHelper.Assert(ib1o !.Equals(ib1));
            iao = ib1.Ib1op(ic);
            TestHelper.Assert(iao !.Equals(ic));
            ib1o = ib1.Ib1op(ic);
            TestHelper.Assert(ib1o !.Equals(ic));
            iao = ic.Ib1op(ib1);
            TestHelper.Assert(iao !.Equals(ib1));
            ib1o = ic.Ib1op(ib1);
            TestHelper.Assert(ib1o !.Equals(ib1));
            iao = ic.Ib1op(ic);
            TestHelper.Assert(iao !.Equals(ic));
            ib1o = ic.Ib1op(ic);
            TestHelper.Assert(ib1o !.Equals(ic));

            iao = ib2.Ib2op(ib2);
            TestHelper.Assert(iao !.Equals(ib2));
            ib2o = ib2.Ib2op(ib2);
            TestHelper.Assert(ib2o !.Equals(ib2));
            iao = ib2.Ib2op(ic);
            TestHelper.Assert(iao !.Equals(ic));
            ib2o = ib2.Ib2op(ic);
            TestHelper.Assert(ib2o !.Equals(ic));
            iao = ic.Ib2op(ib2);
            TestHelper.Assert(iao !.Equals(ib2));
            ib2o = ic.Ib2op(ib2);
            TestHelper.Assert(ib2o !.Equals(ib2));
            iao = ic.Ib2op(ic);
            TestHelper.Assert(iao !.Equals(ic));
            ib2o = ic.Ib2op(ic);
            TestHelper.Assert(ib2o !.Equals(ic));

            iao = ic.Icop(ic);
            TestHelper.Assert(iao !.Equals(ic));
            ib1o = ic.Icop(ic);
            TestHelper.Assert(ib1o !.Equals(ic));
            ib2o = ic.Icop(ic);
            TestHelper.Assert(ib2o !.Equals(ic));
            ico = ic.Icop(ic);
            TestHelper.Assert(ico !.Equals(ic));
            output.WriteLine("ok");
            await initial.ShutdownAsync();
        }
Beispiel #23
0
        public static IMyClassPrx Run(TestHelper helper)
        {
            Communicator?communicator = helper.Communicator();

            TestHelper.Assert(communicator != null);
            var         cl     = IMyClassPrx.Parse(helper.GetTestProxy("test", 0), communicator);
            IMyClassPrx oneway = cl.Clone(oneway: true);

            System.IO.TextWriter output = helper.GetWriter();
            output.Write("testing Invoke... ");
            output.Flush();

            {
                var request = OutgoingRequestFrame.WithEmptyParamList(oneway, "opOneway", idempotent: false);

                // Whether the proxy is oneway or not does not matter for Invoke's oneway parameter.

                IncomingResponseFrame response = cl.Invoke(request, oneway: true);
                TestHelper.Assert(response.ReplyStatus == ReplyStatus.OK);

                response = cl.Invoke(request, oneway: false);
                TestHelper.Assert(response.ReplyStatus == ReplyStatus.UserException);

                response = oneway.Invoke(request, oneway: true);
                TestHelper.Assert(response.ReplyStatus == ReplyStatus.OK);

                response = oneway.Invoke(request, oneway: false);
                TestHelper.Assert(response.ReplyStatus == ReplyStatus.UserException);

                request = OutgoingRequestFrame.WithParamList(cl, "opString", idempotent: false,
                                                             format: null, context: null, TestString, OutputStream.IceWriterFromString);
                response = cl.Invoke(request);
                (string s1, string s2) = response.ReadReturnValue(communicator, istr =>
                {
                    string s1 = istr.ReadString();
                    string s2 = istr.ReadString();
                    return(s1, s2);
                });
                TestHelper.Assert(s1.Equals(TestString) && s2.Equals(TestString));
            }

            for (int i = 0; i < 2; ++i)
            {
                Dictionary <string, string>?ctx = null;
                if (i == 1)
                {
                    ctx = new Dictionary <string, string>
                    {
                        ["raise"] = ""
                    };
                }

                var request = OutgoingRequestFrame.WithEmptyParamList(cl, "opException", idempotent: false, context: ctx);
                IncomingResponseFrame response = cl.Invoke(request);
                try
                {
                    response.ReadVoidReturnValue(communicator);
                }
                catch (MyException)
                {
                    // expected
                }
                catch
                {
                    TestHelper.Assert(false);
                }
            }

            output.WriteLine("ok");

            output.Write("testing InvokeAsync... ");
            output.Flush();

            {
                var request = OutgoingRequestFrame.WithEmptyParamList(oneway, "opOneway", idempotent: false);
                IncomingResponseFrame response;
                try
                {
                    response = oneway.InvokeAsync(request, oneway: true).AsTask().Result;
                }
                catch
                {
                    TestHelper.Assert(false);
                }

                request = OutgoingRequestFrame.WithParamList(cl, "opString", idempotent: false,
                                                             format: null, context: null, TestString, OutputStream.IceWriterFromString);

                response = cl.InvokeAsync(request).AsTask().Result;
                (string s1, string s2) = response.ReadReturnValue(communicator, istr =>
                {
                    string s1 = istr.ReadString();
                    string s2 = istr.ReadString();
                    return(s1, s2);
                });
                TestHelper.Assert(s1.Equals(TestString));
                TestHelper.Assert(s2.Equals(TestString));
            }

            {
                var request = OutgoingRequestFrame.WithEmptyParamList(cl, "opException", idempotent: false);
                IncomingResponseFrame response = cl.InvokeAsync(request).AsTask().Result;

                try
                {
                    response.ReadVoidReturnValue(communicator);
                    TestHelper.Assert(false);
                }
                catch (MyException)
                {
                }
                catch
                {
                    TestHelper.Assert(false);
                }
            }

            output.WriteLine("ok");
            return(cl);
        }
Beispiel #24
0
 public void Write(System.IO.TextWriter sr)
 {
     sr.Write(ToString());
 }
 protected override void WriteSelfEnd(System.IO.TextWriter writer)
 {
     writer.Write("</tr>");
 }
Beispiel #26
0
 protected void dumpLineaColumna(System.IO.TextWriter cout, int n)
 {
     cout.Write(Utilidades.pad(n) + "#" + linea + ":" + columna + ": ");
 }
Beispiel #27
0
        public static IInitialPrx Run(TestHelper helper)
        {
            Communicator?communicator = helper.Communicator;

            TestHelper.Assert(communicator != null);
            System.IO.TextWriter output = helper.Output;
            output.Write("testing stringToProxy... ");
            output.Flush();
            var initial = IInitialPrx.Parse(helper.GetTestProxy("initial", 0), communicator);

            output.WriteLine("ok");

            {
                output.Write("testing types without package... ");
                output.Flush();
                NoNamespace.C1?c1 = initial.GetNoNamespaceC2AsC1();
                TestHelper.Assert(c1 != null);
                TestHelper.Assert(c1 is NoNamespace.C2);
                NoNamespace.C2?c2 = initial.GetNoNamespaceC2AsC2();
                TestHelper.Assert(c2 != null);
                try
                {
                    initial.ThrowNoNamespaceE2AsE1();
                    TestHelper.Assert(false);
                }
                catch (NoNamespace.E1 ex)
                {
                    TestHelper.Assert(ex is NoNamespace.E2);
                }
                try
                {
                    initial.ThrowNoNamespaceE2AsE2();
                    TestHelper.Assert(false);
                }
                catch (NoNamespace.E2)
                {
                    // Expected
                }
                try
                {
                    initial.ThrowNoNamespaceNotify();
                    TestHelper.Assert(false);
                }
                catch (NoNamespace.@notify)
                {
                    // Expected
                }
                output.WriteLine("ok");
            }

            {
                output.Write("testing types with package... ");
                output.Flush();

                {
                    WithNamespace.C1?c1 = initial.GetWithNamespaceC2AsC1();
                    TestHelper.Assert(c1 != null);
                    TestHelper.Assert(c1 is WithNamespace.C2);
                    WithNamespace.C2?c2 = initial.GetWithNamespaceC2AsC2();
                    TestHelper.Assert(c2 != null);
                    try
                    {
                        initial.ThrowWithNamespaceE2AsE1();
                        TestHelper.Assert(false);
                    }
                    catch (WithNamespace.E1 ex)
                    {
                        TestHelper.Assert(ex is WithNamespace.E2);
                    }
                    try
                    {
                        initial.ThrowWithNamespaceE2AsE2();
                        TestHelper.Assert(false);
                    }
                    catch (WithNamespace.E2)
                    {
                        // Expected
                    }
                    output.WriteLine("ok");
                }
            }
            return(initial);
        }
Beispiel #28
0
 // This method is REQUIRED if the template contains any Razor helpers, but you may choose to implement it differently
 //
 /// <summary>Writes a literal value to the TextWriter without HTML escaping it.</summary>
 /// <param name="writer">The TextWriter to which to write the literal.</param>
 /// <param name="value">The literal value.</param>
 protected static void WriteLiteralTo(System.IO.TextWriter writer, string value)
 {
     writer.Write(value);
 }
Beispiel #29
0
 protected override void WriteMetadata(System.IO.TextWriter writer)
 {
     writer.Write(MetaGenerator._edmxJson);
 }
        public void writeAsJson(Object o, TextWriter writer, TypeAliaser typeAliaser=null)
        {
            if (LeafDefaultSet != null && OmitDefaultLeafValuesInJs && OmitMarkAsArrayFunction)
            {
                throw new Exception("Leaf defaulting requires Array marker for js code");
            }


            ObjectIDGenerator idGenerator = null;

            if (UseReferences)
            {
                idGenerator=new ObjectIDGenerator();
            }
            Stack<ExploreStackFrame> exploreStack = new Stack<ExploreStackFrame>();
            Explorer explorerImpl = ExplorerFactory();
            ((Explorer)explorerImpl).NodeExpander = NodeExpander;
            MoveAway down = delegate (Object from, string propertyName, Object to, bool isIndexed, int? index)
            {
                ExploreStackFrame currentFrame = exploreStack.Count>0 ? exploreStack.Peek():null;
                if (currentFrame != null)
                {
                    if (currentFrame.propertyCount > 0) writer.Write(", ");
                    currentFrame.propertyCount++;
                }
                if (from != null && propertyName != null)
                {
                    writePropertyName(propertyName, writer);
                    writer.Write(":");
                }
                ExploreStackFrame childFrame = new ExploreStackFrame();
                exploreStack.Push(childFrame);
                writeIndent(writer, exploreStack);
                if (UseReferences)
                {
                    bool firstTime;
                    long objectid = idGenerator.GetId(to, out firstTime);
                    if (firstTime)
                    {
                        // could be done like this ! (function() {var x=[1,2]; x.id="uuu";return x;})()
                        if (!isIndexed)
                        {
                            writer.Write("{" + this.IdTag + ":" + objectid + ' ');
                            childFrame.propertyCount++;
                            childFrame.propertyCount += writeTypeAliasProperty(writer, to, typeAliaser, childFrame.propertyCount);
                            
                        }
                        else
                        {
                            // no need for type alias
                            writer.Write(AttachId2ArrayFunctionName + "(" + objectid + ",[");
                        }
                        
                    }
                    else
                    {
                        writer.Write("{" + this.ReferenceTag + ":" + objectid);
                        return false;
                    }
                }
                else // !Use References
                {
                    if (!isIndexed)
                    {
                        writer.Write('{');
                        // todo -- check this out ............
                        childFrame.propertyCount += writeTypeAliasProperty(writer, to, typeAliaser, childFrame.propertyCount);
                    }
                    else
                    {
                        if (!OmitMarkAsArrayFunction)
                        {
                            writer.Write(markAsArrayFunctionName);
                            writer.Write("([");
                        }
                        else
                        {
                            writer.Write("[");
                        }
                    }
                }

                return true;
            };

            MoveBack up = (from, propertyName, to, isIndexed) => 
                {
                    if (!isIndexed) writer.Write('}');
                    else
                    {
                        writer.Write(']');
                        // is there a function wrapper ?
                        if (!OmitMarkAsArrayFunction || UseReferences) writer.Write(")");
                    }
                    exploreStack.Pop();
                    writeIndent(writer, exploreStack);
                };

            OnLeaf leaf = (from, propertyName, to, index) => 
              {
                  //check for default leaf values
                  if (!this.OmitDefaultLeafValuesInJs ||
                      !isDefaultLeafValue(from, propertyName, to, LeafDefaultSet))
                  {
                     ExploreStackFrame currentFrame = exploreStack.Peek();
                     if (currentFrame.propertyCount > 0) writer.Write(", ");
                     currentFrame.propertyCount++;
                     if (propertyName!=null)
                     {
                         writePropertyName(propertyName, writer);
                         writer.Write(":");                     
                     }
                  writeLeafValue(writer, to, propertyName);
                  }
              };
            explorerImpl.explore(o, down, up, leaf);
        }
Beispiel #31
0
 public override void WriteText(Cosmos.Assembler.Assembler aAssembler, System.IO.TextWriter aOutput)
 {
     aOutput.Write(this.GetAsText());
 }
 void writeIndent(TextWriter writer, Stack<ExploreStackFrame> exploreStack)
 {
     if (IndentSize != null)
     {
         writer.Write(NewLine);
         int fullIndentSize = ((int)IndentSize) * exploreStack.Count;
         for (int done = 0; done < fullIndentSize; done++)
         {
             writer.Write(' ');
         }
     }
 }
Beispiel #33
0
        public static void allTestsWithController(TestHelper helper, IControllerPrx controller)
        {
            Communicator?communicator = helper.Communicator();

            TestHelper.Assert(communicator != null);

            var timeout = ITimeoutPrx.Parse($"timeout:{helper.GetTestEndpoint(0)}", communicator);

            System.IO.TextWriter output = helper.GetWriter();
            output.Write("testing connect timeout... ");
            output.Flush();
            {
                var properties = communicator.GetProperties();
                properties["Ice.ConnectTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse($"timeout:{helper.GetTestEndpoint(0)}", comm);

                // Expect ConnectTimeoutException.
                controller.holdAdapter(-1);
                try
                {
                    to.op();
                    TestHelper.Assert(false);
                }
                catch (ConnectTimeoutException)
                {
                    // Expected.
                }
                controller.resumeAdapter();
                timeout.op(); // Ensure adapter is active.
            }
            {
                //
                // Expect success.
                //
                controller.holdAdapter(100);
                timeout.op();
            }
            output.WriteLine("ok");

            // The sequence needs to be large enough to fill the write/recv buffers
            byte[] seq = new byte[2000000];

            output.Write("testing connection timeout... ");
            output.Flush();
            {
                //
                // Expect TimeoutException.
                //
                controller.holdAdapter(-1);
                timeout.GetConnection() !.Acm = new Acm(TimeSpan.FromMilliseconds(50),
                                                        AcmClose.OnInvocationAndIdle,
                                                        AcmHeartbeat.Off);
                try
                {
                    timeout.sendData(seq);
                    TestHelper.Assert(false);
                }
                catch (ConnectionTimeoutException)
                {
                    // Expected.
                }
                controller.resumeAdapter();
                timeout.op(); // Ensure adapter is active.
            }
            {
                //
                // Expect success.
                //
                controller.holdAdapter(100);
                try
                {
                    timeout.sendData(new byte[1000000]);
                }
                catch (ConnectionTimeoutException)
                {
                    TestHelper.Assert(false);
                }
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeout... ");
            output.Flush();
            {
                timeout.IcePing(); // Makes sure a working connection is associated with the proxy
                var connection = timeout.GetConnection();
                var to         = timeout.Clone(invocationTimeout: 100);
                TestHelper.Assert(connection == to.GetConnection());
                try
                {
                    to.sleep(1000);
                    TestHelper.Assert(false);
                }
                catch (TimeoutException)
                {
                }
                timeout.IcePing();
                to = timeout.Clone(invocationTimeout: 1000);
                TestHelper.Assert(connection == to.GetConnection());
                try
                {
                    to.sleep(100);
                }
                catch (TimeoutException)
                {
                    TestHelper.Assert(false);
                }
                TestHelper.Assert(connection == to.GetConnection());
            }
            {
                //
                // Expect TimeoutException.
                //
                var to = timeout.Clone(invocationTimeout: 100);
                try
                {
                    to.sleepAsync(1000).Wait();
                }
                catch (AggregateException ex) when(ex.InnerException is TimeoutException)
                {
                }
                timeout.IcePing();
            }
            {
                //
                // Expect success.
                //
                var to = timeout.Clone(invocationTimeout: 1000);
                to.sleepAsync(100).Wait();
            }

            output.WriteLine("ok");

            output.Write("testing close timeout... ");
            output.Flush();
            {
                var properties = communicator.GetProperties();
                properties["Ice.CloseTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse($"timeout:{helper.GetTestEndpoint(0)}", comm);

                var connection  = to.GetConnection();
                var connection2 = timeout.GetConnection(); // No close timeout

                TestHelper.Assert(connection != null && connection2 != null);

                controller.holdAdapter(-1);

                // Make sure there's no ReadAsync pending
                _ = to.IcePingAsync();
                _ = timeout.IcePingAsync();

                var semaphore = new System.Threading.SemaphoreSlim(0);
                connection.Closed += (sender, args) => semaphore.Release();
                connection.Close(ConnectionClose.Gracefully);
                TestHelper.Assert(semaphore.Wait(500));

                connection2.Closed += (sender, args) => semaphore.Release();
                connection2.Close(ConnectionClose.Gracefully);
                TestHelper.Assert(!semaphore.Wait(500));

                controller.resumeAdapter();
                timeout.op(); // Ensure adapter is active.
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeouts with collocated calls... ");
            output.Flush();
            {
                communicator.SetProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

                var adapter = communicator.CreateObjectAdapter("TimeoutCollocated");
                adapter.Activate();

                var proxy = adapter.AddWithUUID(new Timeout(), ITimeoutPrx.Factory).Clone(invocationTimeout: 100);
                try
                {
                    proxy.sleep(500);
                    TestHelper.Assert(false);
                }
                catch (TimeoutException)
                {
                }

                try
                {
                    proxy.sleepAsync(500).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is TimeoutException)
                {
                }
                adapter.Dispose();
            }
            output.WriteLine("ok");

            controller.shutdown();
        }
 /// <summary>
 /// Writes CSV Representation of <paramref name="CSVData"/>
 /// to <paramref name="TextWriter"/>
 /// </summary>
 /// <param name="TextWriter"><see cref="System.IO.TextWriter"/> destination to write CSV Text</param>
 /// <param name="CSVData"><see cref="IEnumerable{T}"/> of Values to Serialize to CSV</param>
 /// <param name="IncludeHeaderRow">
 /// Indicates whether to add a header row at the top of the file with the Column Names
 /// </param>
 public void Serialize(System.IO.TextWriter TextWriter, IEnumerable<T> CSVData, bool IncludeHeaderRow = true)
     => TextWriter.Write(Serialize(CSVData, IncludeHeaderRow));
Beispiel #35
0
        /// <summary>
        /// 呈现本元素的数据
        /// </summary>
        /// <param name="writer"></param>
        public override void Render(System.IO.TextWriter writer)
        {
            VariableTag tag   = this;
            object      value = this.VarExpression.GetValue();

            //调用自定函数处理此变量的值
            if (this.CallFunctions.Count > 0)
            {
                foreach (var exp in this.CallFunctions)
                {
                    object method = exp.GetValue();
                    if (!Utility.IsNothing(method))
                    {
                        UserDefinedFunction func;
                        if (this.OwnerTemplate.UserDefinedFunctions.TryGetValue(method.ToString(), out func))
                        {
                            value = func(new object[] { value });
                        }
                    }
                }
            }

            if (Utility.IsNothing(value))
            {
                return;
            }

            bool   formated = false;
            string text     = string.Empty;
            string format   = this.Format == null ? string.Empty : this.Format.GetTextValue();

            if (value is string)
            {
                //字符串
                text = (string)value;
            }
            else
            {
                //非字符串.则判断处理format
                if (!string.IsNullOrEmpty(format))
                {
                    IFormattable iformat = value as IFormattable;
                    if (iformat != null)
                    {
                        text     = iformat.ToString(format, CultureInfo.InvariantCulture);
                        formated = true;
                    }
                }
                //非IFormattable接口.则直接取字符串处理
                if (!formated)
                {
                    //如果数据是IEnumerable,IEnumerator接口则进行数据拼凑
                    IEnumerator ie = null;
                    if (value is IEnumerable)
                    {
                        ie = ((IEnumerable)value).GetEnumerator();
                    }
                    else if (value is IEnumerator)
                    {
                        ie = (IEnumerator)value;
                    }
                    if (ie != null)
                    {
                        StringBuilder buffer = new StringBuilder();
                        ie.Reset();
                        while (ie.MoveNext())
                        {
                            if (buffer.Length != 0)
                            {
                                buffer.Append(",");
                            }
                            buffer.Append(ie.Current);
                        }
                        text = buffer.ToString();
                    }
                    else
                    {
                        text = value.ToString();
                    }
                }
            }

            if (text.Length > 0)
            {
                bool removeHtml   = this.RemoveHtml == null ? false : Utility.ConverToBoolean(this.RemoveHtml.GetTextValue());
                bool textEncode   = this.TextEncode == null ? false : Utility.ConverToBoolean(this.TextEncode.GetTextValue());
                bool htmlEncode   = this.HtmlEncode == null ? false : Utility.ConverToBoolean(this.HtmlEncode.GetTextValue());
                bool xmlEncode    = this.XmlEncode == null ? false : Utility.ConverToBoolean(this.XmlEncode.GetTextValue());
                bool jsEncode     = this.JsEncode == null ? false : Utility.ConverToBoolean(this.JsEncode.GetTextValue());
                bool urlEncode    = this.UrlEncode == null ? false : Utility.ConverToBoolean(this.UrlEncode.GetTextValue());
                bool compressText = this.CompressText == null ? false : Utility.ConverToBoolean(this.CompressText.GetTextValue());

                int      length     = this.Length == null ? 0 : Utility.ConverToInt32(this.Length.GetTextValue());
                string   appendText = this.AppendText == null ? string.Empty : this.AppendText.GetTextValue();
                Encoding charset    = this.Charset == null ? this.OwnerTemplate.Charset : Utility.GetEncodingFromCharset(this.Charset.GetTextValue(), this.OwnerTemplate.Charset);

                if (removeHtml)
                {
                    text = Utility.RemoveHtmlCode(text);
                }
                if (length > 0)
                {
                    text = Utility.CutString(text, length, charset, appendText);
                }
                if (textEncode)
                {
                    text = Utility.TextEncode(text);
                }
                else if (htmlEncode)
                {
                    text = HttpUtility.HtmlEncode(text);
                }
                if (xmlEncode)
                {
                    text = Utility.XmlEncode(text);
                }
                if (jsEncode)
                {
                    text = Utility.JsEncode(text);
                }
                if (urlEncode)
                {
                    text = HttpUtility.UrlEncode(text, charset);
                }
                if (compressText)
                {
                    text = Utility.CompressText(text);
                }

                if (!formated && !string.IsNullOrEmpty(format))
                {
                    text = string.Format(format, text);
                }


                writer.Write(text);
            }
        }
Beispiel #36
0
		public virtual void  xmlSerializeRootOpen(TextWriter outWriter)
		{
			StringBuilder buf = new StringBuilder(100);
			buf.Append("<");
			buf.Append(GetType().FullName + " ");
			buf.Append("text=\"" + encode(getText()) + "\" type=\"" + Type + "\">\n");
			outWriter.Write(buf.ToString());
		}
Beispiel #37
0
 protected static void Indent(TextWriter Out, uint Depth)
 {
     for (uint i = 0; i < Depth; i++) {
     Out.Write("  ");
     }
 }
Beispiel #38
0
 /// <summary>
 /// Runs the test.
 /// </summary>
 /// <param name="name">Name.</param>
 /// <param name="testMethod">Test method.</param>
 /// <param name="output">Output.</param>
 public static void RunTest(string name, Action testMethod, TextWriter output = null)
 {
     if (output == null)
         output = Console.Out;
     string _oldNL = output.NewLine;
     try
     {
         output.WriteLine(_runTestFormatStart, name);
         testMethod();
         output.WriteLine(_runTestFormatSuccess, name);
     }
     catch (FaultException<ExceptionDetail> ex)
     {
         output.WriteLine(_runTestFormatError, name);
         output.WriteLine(_runTestFormatException, ex.GetType().FullName, ex.Message, ex.StackTrace);
         foreach (DictionaryEntry de in ex.Data)
             output.Write("\t{0} = {1}\n", de.Key.ToString(), de.Value.ToString());
         int indent = 0;
         for (ExceptionDetail detail = ex.Detail; detail != null; detail = detail.InnerException)
             output.WriteLine(string.Concat(" ------ Inner Exception ------\n",
                 string.Format(_runTestFormatException, detail.Type, detail.Message, detail.StackTrace))
                 .Replace("\n", string.Concat("\n", new string(' ', ++indent * 2))).TrimStart('\n'));
     }
     catch (Exception ex)
     {
         output.WriteLine(_runTestFormatError, name);
         output.WriteLine(_runTestFormatException, ex.GetType().FullName, ex.Message, ex.StackTrace);
         foreach (DictionaryEntry de in ex.Data)
             output.Write("\t{0} = {1}\n", de.Key.ToString(), de.Value.ToString());
         int indent = 0;
         for (Exception innerEx = ex.InnerException; innerEx != null; innerEx = innerEx.InnerException)
             output.WriteLine(string.Concat("\n ------ Inner Exception ------\n",
                 string.Format(_runTestFormatException, innerEx.GetType().FullName, innerEx.Message, innerEx.StackTrace))
                 .Replace("\n", string.Concat("\n", new string(' ', ++indent * 2))).TrimStart('\n'));
     }
     finally
     {
         output.NewLine = _oldNL;			// you COULD wrap this in a using() if you write a class implementing IDisposable with this line in Dispose()
     }
 }
Beispiel #39
0
 public void Write(string s)
 {
     output.Write(s);
 }
Beispiel #40
0
 public override void WriteText(Assembler aAssembler, System.IO.TextWriter aOutput)
 {
     aOutput.Write("; ");
     aOutput.Write(Text);
 }
Beispiel #41
0
        public static void Generate(List <Extraction.Doctest> doctests, System.IO.TextWriter writer)
        {
            var blocks = new List <string>();

            string nl = Environment.NewLine;

            blocks.Add(
                $"// This file was automatically generated by doctest-csharp.{nl}" +
                $"// !!! DO NOT EDIT OR APPEND !!!{nl}");

            // Header blocks

            string header = Style.MergeHeaders(doctests);

            if (header.Length > 0)
            {
                blocks.Add(header);
            }

            blocks.Add($"using NUnit.Framework;{nl}");

            // Doctests

            List <Style.NamespacedDoctests> groupedDoctests = Style.GroupConsecutiveDoctestsByNamespace(doctests);

            var namespaceCount = new Dictionary <string, int>();

            foreach (var namespacedDoctests in groupedDoctests)
            {
                if (!namespaceCount.ContainsKey(namespacedDoctests.Namespace))
                {
                    namespaceCount[namespacedDoctests.Namespace] = 0;
                }

                namespaceCount[namespacedDoctests.Namespace]++;

                var block = new System.IO.StringWriter();

                block.WriteLine(
                    namespacedDoctests.Namespace == ""
                        ? "namespace Tests"
                        : $"namespace {namespacedDoctests.Namespace}.Tests");

                block.WriteLine("{"); // namespace opening

                block.WriteLine(
                    namespaceCount[namespacedDoctests.Namespace] > 1
                        ? $"    public class DocTests{namespaceCount[namespacedDoctests.Namespace]}"
                        : "    public class DocTests");

                block.WriteLine("    {"); // class opening

                for (var i = 0; i < namespacedDoctests.Doctests.Count; i++)
                {
                    if (i > 0)
                    {
                        block.WriteLine();
                    }

                    var doctest = namespacedDoctests.Doctests[i];
                    block.WriteLine("        [Test]");
                    block.WriteLine($"        public void AtLine{doctest.Line}AndColumn{doctest.Column}");
                    block.WriteLine("        {"); // method opening

                    block.WriteLine(
                        doctest.Body == ""
                            ? Style.Indent("// Empty doctest", 3)
                            : Style.Indent(doctest.Body, 3));

                    block.WriteLine("        }"); // method closing
                }

                block.WriteLine("    }"); // class closing
                block.WriteLine("}");     // namespace closing

                blocks.Add(block.ToString());
            }

            blocks.Add(
                $"// This file was automatically generated by doctest-csharp.{nl}" +
                $"// !!! DO NOT EDIT OR APPEND !!!{nl}");

            // Join blocks

            foreach (string block in blocks)
            {
                if (!block.EndsWith(Environment.NewLine))
                {
                    throw new InvalidOperationException(
                              $"Expected block to end with a new line, but got: {block}");
                }
            }

            for (var i = 0; i < blocks.Count; i++)
            {
                if (i > 0)
                {
                    writer.WriteLine();
                }

                // All block must end with a new-line character, so do not add a new line here.
                writer.Write(blocks[i]);
            }
        }
Beispiel #42
0
 public void Write(ContentItem item, string propertyName, System.IO.TextWriter writer)
 {
     writer.Write(item[propertyName]);
 }
Beispiel #43
0
 public override void WriteId(System.IO.TextWriter trapFile)
 {
     trapFile.Write(TransformedPath.DatabaseId);
     trapFile.Write(";sourcefile");
 }