public HelloResponse Any(Hello request) { String response = esbProxy.Invoke("ESB_COM_WS", "HelloAction", "Hello From ServiceStack!"); return new HelloResponse { Result = "Hello, {0}!".Fmt(request.Name) }; }
public void Test_Hello_No_Features_Set() { var features = new List<short>(); var hello = new Hello("couchbase-net-sdk/2.1.4", features.ToArray(), Transcoder, 0, 0); var result = IOService.Execute(hello); Assert.IsTrue(result.Success); }
public void Test_KeySeqnoObserver() { var configuration = new ClientConfiguration { Servers = new List<Uri> { new Uri(ConfigurationManager.AppSettings["bootstrapUrl"]) } }; var key = "Test_KeySeqnoObserver"; using (var cluster = new Cluster(configuration)) { using (var bucket = cluster.OpenBucket()) { bucket.Remove(key); } } configuration.Initialize(); var provider = new CarrierPublicationProvider( configuration, (pool) => new PooledIOService(pool), (config, endpoint) => new ConnectionPool<Connection>(config, endpoint), SaslFactory.GetFactory(), new DefaultConverter(), new DefaultTranscoder(new DefaultConverter(), new DefaultSerializer())); var configInfo = provider.GetConfig("default"); var features = new List<short>(); features.Add((short)ServerFeatures.MutationSeqno); var keyMapper = configInfo.GetKeyMapper(); var mappedNode = keyMapper.MapKey(key); var node = mappedNode.LocatePrimary(); foreach (var server in configInfo.Servers.Where(x=>x.IsDataNode)) { var hello = new Hello("couchbase-net-sdk/2.1.4", features.ToArray(), provider.Transcoder, 0, 0); var result3 = server.Send(hello); Assert.IsTrue(result3.Success); } var result = node.Send(new Add<string>(key, "", (VBucket)mappedNode, new DefaultTranscoder(new DefaultConverter(), new DefaultSerializer()), 1000)); var clusterController = new Mock<IClusterController>(); clusterController.Setup(x => x.Transcoder).Returns(new DefaultTranscoder()); var pending = new ConcurrentDictionary<uint, IOperation>(); var keyObserver = new KeySeqnoObserver("thekey", pending, configInfo, clusterController.Object, 0, 1000); var durabilityReached = keyObserver.Observe(result.Token, ReplicateTo.Zero, PersistTo.One); Assert.IsTrue(durabilityReached); }
public object Any(Hello request) { return new HelloResponse { Result = "Hello, {0}{1}!".Fmt( request.Title != null ? request.Title + ". " : "", request.Name) }; }
public static void Main() { Hello h = new Hello("stranger"); GoodBye g = new GoodBye("my friend"); Farewell f = new Farewell("you fool"); h.speak(); g.speak(); f.speak(); }
public object Any(Hello request) { if (string.IsNullOrEmpty(request.Name)) { throw new ArgumentNullException("Name"); } return new HelloResponse { Result = "Hello " + request.Name }; }
public void Test_Hello_With_Features_MutationSeqno_And_TcpNodelay_Set() { var features = new List<short>(); features.Add((short)ServerFeatures.MutationSeqno); features.Add((short)ServerFeatures.TcpNoDelay); var hello = new Hello("couchbase-net-sdk/2.1.4", features.ToArray(), Transcoder, 0, 0); var result = IOService.Execute(hello); Assert.IsTrue(result.Success); }
public void ExecuteTest() { // Initialise Instance var target = new Hello { Message = "World" }; // Invoke the Workflow var actual = WorkflowInvoker.Invoke(target); // Test the result Assert.AreEqual("Hello World", actual); }
public static void Encode(IByteWriter stream, Hello encodedHello) { Uint32.Encode(stream, encodedHello.LedgerVersion); Uint32.Encode(stream, encodedHello.OverlayVersion); Uint32.Encode(stream, encodedHello.OverlayMinVersion); Hash.Encode(stream, encodedHello.NetworkID); XdrEncoding.WriteString(stream, encodedHello.VersionStr); XdrEncoding.EncodeInt32(encodedHello.ListeningPort, stream); NodeID.Encode(stream, encodedHello.PeerID); AuthCert.Encode(stream, encodedHello.Cert); Uint256.Encode(stream, encodedHello.Nonce); }
public object Any(Hello request) { var response = new HelloResponse { Result = "Hello, " + request.Name }; if (Request.Files.Length > 0) { response.Result += ".\nFiles: {0}, name: {1}, size: {2} bytes".Fmt(Request.Files.Length, Request.Files[0].FileName, Request.Files[0].ContentLength); } return response; }
static void Main() { Foo foo = new Bar (81); Hello hello = new Hello (0x12345678); object obj = foo; object boxed = hello; ValueType value = hello; Console.WriteLine (foo); Console.WriteLine (obj); Console.WriteLine (boxed); Console.WriteLine (value); }
public object Any(Hello request) { //Issue 1 //This now fails. var campaign = new Campaign(); campaign.TrackingId = 0; campaign.CampaignPhone = "none"; campaign.CostAmount = 0M; campaign.EndDate = 0L; campaign.StartDate = SystemClock.Instance.Now.Ticks / NodaConstants.TicksPerMillisecond; campaign.FixedCost = 0M; campaign.IsActive = true; campaign.IsRetread = true; campaign.IsFactorTrustApp = true; campaign.IsFactorTrustLeads = true; campaign.IsDuplicate = true; campaign.IsEmail = true; campaign.MasterId = 0; campaign.IsFirmOffer = false; campaign.LeadDelCostTypeId = 0; campaign.LeadDelRespTypeId = 0; campaign.LeadDelTypeId = 0; campaign.LeadRoutingTypeId = 0; campaign.Name = "Exception Campaign"; campaign.IsExceptionCampaign = true; campaign.IsDefaultCampaign = false; campaign.IsActive = true; var rowId = Db.Insert(campaign, true); //Issue 2 // This is also broken /* var campaigns = Db.Dictionary<int, string>(Db. From<Campaign>(). Select(x => new { x.Id, x.Name }). Where(x => x.IsActive));*/ // but yet, this works /*var campaigns = Db.Dictionary<int, string>("select id, name from campaign where isactive = 1");*/ return new HelloResponse { Result = "Hello, {0}!".Fmt(request.Name) }; }
public static Hello Decode(IByteReader stream) { Hello decodedHello = new Hello(); decodedHello.LedgerVersion = Uint32.Decode(stream); decodedHello.OverlayVersion = Uint32.Decode(stream); decodedHello.OverlayMinVersion = Uint32.Decode(stream); decodedHello.NetworkID = Hash.Decode(stream); decodedHello.VersionStr = XdrEncoding.ReadString(stream); decodedHello.ListeningPort = XdrEncoding.DecodeInt32(stream); decodedHello.PeerID = NodeID.Decode(stream); decodedHello.Cert = AuthCert.Decode(stream); decodedHello.Nonce = Uint256.Decode(stream); return decodedHello; }
static void Main(string[] args) { ChannelServices.RegisterChannel(new TcpClientChannel()); ChannelServices.RegisterChannel(new HttpClientChannel()); RemotingConfiguration.RegisterWellKnownClientType( typeof(Wrox.ProfessionalCSharp.Hello), "tcp://localhost:8086/Hi"); /* Hello obj = (Hello)Activator.GetObject( typeof(Wrox.ProfessionalCSharp.Hello), "tcp://localhost:8086/Hi"); */ Hello obj = new Hello(); // Hello obj = (Hello)RemotingServices.Connect(typeof(Wrox.ProfessionalCSharp.Hello), // "http://localhost:8085/Hi"); if (obj == null) { Console.WriteLine("could not locate server"); return; } MySerialized ser = obj.GetMySerialized(); if (!RemotingServices.IsTransparentProxy(ser)) { Console.WriteLine("ser is not a transparent proxy"); } ser.Foo(); MyRemote rem = obj.GetMyRemote(); if (RemotingServices.IsTransparentProxy(rem)) { Console.WriteLine("rem is a transparent proxy"); } rem.Foo(); /* MySerialized ser1 = new MySerialized(1); obj.InSerialized(ser1); Console.WriteLine(ser1.A); MySerialized ser2 = new MySerialized(2); obj.RefSerialized(ref ser2); Console.WriteLine(ser2.A); MySerialized ser3; obj.OutSerialized(out ser3); Console.WriteLine(ser3.A); */ }
public void TestHello() { var hello = new Hello(); hello.PrintHello("Hello world"); Assert.That(hello.add(1, 1), Is.EqualTo(2)); Assert.That(hello.add(5, 5), Is.EqualTo(10)); Assert.IsTrue(hello.test1(3, 3.0f)); Assert.IsFalse(hello.test1(2, 3.0f)); var foo = new Foo { A = 4, B = 7 }; Assert.That(hello.AddFoo(foo), Is.EqualTo(11)); Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11)); Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11)); Assert.That(hello.AddFooRef(foo), Is.EqualTo(11)); unsafe { var pointer = foo.SomePointer; var pointerPointer = foo.SomePointerPointer; for (int i = 0; i < 4; i++) { Assert.AreEqual(i, pointer[i]); Assert.AreEqual(i, (*pointerPointer)[i]); } } var bar = new Bar { A = 4, B = 7 }; Assert.That(hello.AddBar(bar), Is.EqualTo(11)); Assert.That(bar.RetItem1(), Is.EqualTo(Bar.Item.Item1)); var retFoo = hello.RetFoo(7, 2.0f); Assert.That(retFoo.A, Is.EqualTo(7)); Assert.That(retFoo.B, Is.EqualTo(2.0)); var foo2 = new Foo2 { A = 4, B = 2, C = 3 }; Assert.That(hello.AddFoo(foo2), Is.EqualTo(6)); Assert.That(hello.AddFoo2(foo2), Is.EqualTo(9)); var bar2 = new Bar2 { A = 4, B = 7, C = 3 }; Assert.That(hello.AddBar2(bar2), Is.EqualTo(14)); Assert.That(hello.RetEnum(Enum.A), Is.EqualTo(0)); Assert.That(hello.RetEnum(Enum.B), Is.EqualTo(2)); Assert.That(hello.RetEnum(Enum.C), Is.EqualTo(5)); //Assert.That(hello.RetEnum(Enum.D), Is.EqualTo(-2147483648)); Assert.That(hello.RetEnum(Enum.E), Is.EqualTo(1)); Assert.That(hello.RetEnum(Enum.F), Is.EqualTo(-9)); }
public void TestPrimitiveConstCharStringInOut() { var hello = new Hello(); string str; hello.StringOut(out str); Assert.That(str, Is.EqualTo("HelloStringOut")); hello.StringOutRef(out str); Assert.That(str, Is.EqualTo("HelloStringOutRef")); str = "Hello"; hello.StringInOut(ref str); Assert.That(str, Is.EqualTo("StringInOut")); str = "Hello"; hello.StringInOutRef(ref str); Assert.That(str, Is.EqualTo("StringInOutRef")); }
public void Test_Hello_With_Feature_MutationSeqno_Set() { var features = new List<short>(); features.Add((short)ServerFeatures.MutationSeqno); var hello = new Hello("couchbase-net-sdk/2.1.4", features.ToArray(), Transcoder, 0, 0); var result = IOService.Execute(hello); Assert.IsTrue(result.Success); var key = "bar"; var delete = new Delete(key, GetVBucket(), Transcoder, OperationLifespanTimeout); var deleteResult = IOService.Execute(delete); var add = new Add<string>(key, "foo", GetVBucket(), Transcoder, OperationLifespanTimeout); var result2 =IOService.Execute(add); Assert.IsNotNull(result2.Token); }
static int Main() { AppDomain domain = AppDomain.CreateDomain ("Test"); // @MDB LINE: main Assembly ass = Assembly.GetExecutingAssembly (); Hello hello = (Hello) domain.CreateInstanceAndUnwrap (ass.FullName, "Hello"); Console.WriteLine ("TEST: {0}", hello); hello.World (); Hello bar = new Hello (); bar.World (); hello.World (); // @MDB BREAKPOINT: main2 bar.World (); AppDomain.Unload (domain); // @MDB BREAKPOINT: unload return 0; }
public void ExecuteTest2() { // Initialise Instance var target = new Hello { Message = "World" }; // Declare additional parameters var parameters = new Dictionary<string, object> { { "Message2", " hope you are well" }, }; // Create the Workflow object WorkflowInvoker invoker = new WorkflowInvoker(target); // Create a Mock build detail object IBuildDetail t = new MockIBuildDetail { BuildNumber = "MyBuildNumber" }; invoker.Extensions.Add(t); // Invoke the workflow var actual = invoker.Invoke(parameters); // Test the result wich is now accessed via the named Result key Assert.AreEqual("Hello World hope you are well from MyBuildNumber", actual["Result"]); }
/// <summary> /// Receive a ZreMsg from the socket. /// </summary> public void Receive(IReceivingSocket input) { bool more; if (input is RouterSocket) { Msg routingIdMsg = new Msg(); routingIdMsg.InitEmpty(); try { input.Receive(ref routingIdMsg); if (!routingIdMsg.HasMore) { throw new MessageException("No routing id"); } if (m_routingId == null || m_routingId.Length == routingIdMsg.Size) { m_routingId = new byte[routingIdMsg.Size]; } Buffer.BlockCopy(routingIdMsg.Data, 0, m_routingId, 0, m_routingId.Length); } finally { routingIdMsg.Close(); } } else { RoutingId = null; } Msg msg = new Msg(); msg.InitEmpty(); try { input.Receive(ref msg); m_offset = 0; m_buffer = msg.Data; more = msg.HasMore; UInt16 signature = GetNumber2(); if (signature != (0xAAA0 | 1)) { throw new MessageException("Invalid signature"); } // Get message id and parse per message type Id = (MessageId)GetNumber1(); switch (Id) { case MessageId.Hello: Hello.Read(this); break; case MessageId.Whisper: Whisper.Read(this); break; case MessageId.Shout: Shout.Read(this); break; case MessageId.Join: Join.Read(this); break; case MessageId.Leave: Leave.Read(this); break; case MessageId.Ping: Ping.Read(this); break; case MessageId.PingOk: PingOk.Read(this); break; default: throw new MessageException("Bad message id"); } // Receive message content for types with content switch (Id) { case MessageId.Whisper: Whisper.Content = input.ReceiveMultipartMessage(); break; case MessageId.Shout: Shout.Content = input.ReceiveMultipartMessage(); break; } } finally { m_buffer = null; msg.Close(); } }
/// <summary> /// Send the ZreMsg to the socket. /// </summary> public void Send(IOutgoingSocket output) { if (output is RouterSocket) { output.SendMoreFrame(RoutingId); } int frameSize = 2 + 1; // Signature and message ID switch (Id) { case MessageId.Hello: frameSize += Hello.GetFrameSize(); break; case MessageId.Whisper: frameSize += Whisper.GetFrameSize(); break; case MessageId.Shout: frameSize += Shout.GetFrameSize(); break; case MessageId.Join: frameSize += Join.GetFrameSize(); break; case MessageId.Leave: frameSize += Leave.GetFrameSize(); break; case MessageId.Ping: frameSize += Ping.GetFrameSize(); break; case MessageId.PingOk: frameSize += PingOk.GetFrameSize(); break; } // Now serialize message into the buffer Msg msg = new Msg(); msg.InitPool(frameSize); try { m_offset = 0; m_buffer = msg.Data; // put signature PutNumber2(0xAAA0 | 1); // put message id PutNumber1((byte)Id); switch (Id) { case MessageId.Hello: Hello.Write(this); break; case MessageId.Whisper: Whisper.Write(this); break; case MessageId.Shout: Shout.Write(this); break; case MessageId.Join: Join.Write(this); break; case MessageId.Leave: Leave.Write(this); break; case MessageId.Ping: Ping.Write(this); break; case MessageId.PingOk: PingOk.Write(this); break; } // Send the data frame var more = Id == MessageId.Whisper || Id == MessageId.Shout; output.Send(ref msg, more); // Send message content for types with content switch (Id) { case MessageId.Whisper: if (Whisper.Content == null) { Whisper.Content = new NetMQMessage(); Whisper.Content.PushEmptyFrame(); } output.SendMultipartMessage(Whisper.Content); break; case MessageId.Shout: if (Shout.Content == null) { Shout.Content = new NetMQMessage(); Shout.Content.PushEmptyFrame(); } output.SendMultipartMessage(Shout.Content); break; } } finally { m_buffer = null; msg.Close(); } }
public object Any(Hello request) { return(new HelloResponse { Result = "Hello, " + request.Name + ". Today is: " + request.Day }); }
private static void Main(String[] args) { // Obtém dados através dos argumentos string host = args[0]; ushort port = Convert.ToUInt16(args[1]); string loginFile = args[2]; string domain = args[3]; string entity = args[4]; byte[] password = new ASCIIEncoding().GetBytes(args.Length > 5 ? args[5] : entity); // Cria conexão e a define como conexão padrão tanto para entrada como saída. // O uso exclusivo da conexão padrão (sem uso de current e callback de despacho) só é recomendado para aplicações que criem apenas uma conexão e desejem utilizá-la em todos os casos. Para situações diferentes, consulte o manual do SDK OpenBus e/ou outras demos. ORBInitializer.InitORB(); OpenBusContext context = ORBInitializer.Context; Connection conn = context.ConnectByAddress(host, port); context.SetDefaultConnection(conn); string helloIDLType = Repository.GetRepositoryID(typeof(Hello)); ServiceOfferDesc[] offers = null; try { // Faz o login conn.LoginByPassword(entity, password, domain); // Inicia o processo de autenticação compartilhada e serializa os dados SharedAuthSecret secret = conn.StartSharedAuth(); byte[] encoded = context.EncodeSharedAuth(secret); // Escreve o segredo da autenticação compartilhada em um arquivo. Talvez // seja importante para a aplicação encriptar esses dados. Além // disso, escreveremos apenas uma vez esses dados, que têm validade igual // ao lease do login atual. Caso o cliente demore a executar, esses dados // não funcionarão, portanto uma outra forma mais dinâmica seria mais // eficaz. No entanto, isso foge ao escopo dessa demo. File.WriteAllBytes(loginFile, encoded); // Faz busca utilizando propriedades geradas automaticamente e propriedades definidas pelo serviço específico // propriedade gerada automaticamente ServiceProperty autoProp = new ServiceProperty("openbus.component.interface", helloIDLType); // propriedade definida pelo serviço hello ServiceProperty prop = new ServiceProperty("offer.domain", "Demo SharedAuth"); ServiceProperty[] properties = { prop, autoProp }; offers = context.OfferRegistry.findServices(properties); } catch (AccessDenied) { Console.WriteLine(Resources.ClientAccessDenied + entity + "."); } catch (ServiceFailure e) { Console.WriteLine(Resources.BusServiceFailureErrorMsg); Console.WriteLine(e); } catch (TRANSIENT) { Console.WriteLine(Resources.BusTransientErrorMsg); } catch (COMM_FAILURE) { Console.WriteLine(Resources.BusCommFailureErrorMsg); } catch (Exception e) { NO_PERMISSION npe = null; if (e is TargetInvocationException) { // caso seja uma exceção lançada pelo SDK, será uma NO_PERMISSION npe = e.InnerException as NO_PERMISSION; } if ((npe == null) && (!(e is NO_PERMISSION))) { // caso não seja uma NO_PERMISSION não é uma exceção esperada então deixamos passar. throw; } npe = npe ?? (NO_PERMISSION)e; if (npe.Minor == NoLoginCode.ConstVal) { Console.WriteLine(Resources.NoLoginCodeErrorMsg); } else { throw; } } // analiza as ofertas encontradas bool failed = true; if (offers != null) { if (offers.Length < 1) { Console.WriteLine(Resources.ServiceNotFound); } else { if (offers.Length > 1) { Console.WriteLine(Resources.ServiceFoundMoreThanExpected); } foreach (ServiceOfferDesc serviceOfferDesc in offers) { Console.WriteLine(Resources.ServiceFoundTesting); try { MarshalByRefObject helloObj = serviceOfferDesc.service_ref.getFacet(helloIDLType); if (helloObj == null) { Console.WriteLine(Resources.FacetNotFoundInOffer); continue; } Hello hello = helloObj as Hello; if (hello == null) { Console.WriteLine(Resources.FacetFoundWrongType); continue; } Console.WriteLine(Resources.OfferFound); // utiliza o serviço hello.sayHello(); failed = false; break; } catch (TRANSIENT) { Console.WriteLine(Resources.ServiceTransientErrorMsg); } catch (COMM_FAILURE) { Console.WriteLine(Resources.ServiceCommFailureErrorMsg); } catch (Exception e) { NO_PERMISSION npe = null; if (e is TargetInvocationException) { // caso seja uma exceção lançada pelo SDK, será uma NO_PERMISSION npe = e.InnerException as NO_PERMISSION; } if ((npe == null) && (!(e is NO_PERMISSION))) { // caso não seja uma NO_PERMISSION não é uma exceção esperada então deixamos passar. throw; } npe = npe ?? (NO_PERMISSION)e; bool found = false; string message = String.Empty; switch (npe.Minor) { case NoLoginCode.ConstVal: message = Resources.NoLoginCodeErrorMsg; found = true; break; case UnknownBusCode.ConstVal: message = Resources.UnknownBusCodeErrorMsg; found = true; break; case UnverifiedLoginCode.ConstVal: message = Resources.UnverifiedLoginCodeErrorMsg; found = true; break; case InvalidRemoteCode.ConstVal: message = Resources.InvalidRemoteCodeErrorMsg; found = true; break; } if (found) { Console.WriteLine(message); } else { throw; } } } if (failed) { Console.WriteLine(Resources.OfferFunctionalNotFound); } } } try { conn.Logout(); } catch (ServiceFailure e) { Console.WriteLine(Resources.BusServiceFailureErrorMsg); Console.WriteLine(e); } catch (TRANSIENT) { Console.WriteLine(Resources.BusTransientErrorMsg); } catch (COMM_FAILURE) { Console.WriteLine(Resources.BusCommFailureErrorMsg); } if (!failed) { Console.WriteLine(Resources.ClientOK); } Console.ReadKey(); }
public void SayHello() { Assert.AreEqual("Hello World!", Hello.SayHello()); }
/// <summary> /// Send the ZreMsgOriginal to the socket. /// </summary> public void Send(IOutgoingSocket output) { if (output is RouterSocket) { output.SendMoreFrame(RoutingId); } int frameSize = 2 + 1; // Signature and message ID switch (Id) { case MessageId.Hello: frameSize += Hello.GetFrameSize(); break; case MessageId.Whisper: frameSize += Whisper.GetFrameSize(); break; case MessageId.Shout: frameSize += Shout.GetFrameSize(); break; case MessageId.Join: frameSize += Join.GetFrameSize(); break; case MessageId.Leave: frameSize += Leave.GetFrameSize(); break; case MessageId.Ping: frameSize += Ping.GetFrameSize(); break; case MessageId.PingOk: frameSize += PingOk.GetFrameSize(); break; } // Now serialize message into the buffer Msg msg = new Msg(); msg.InitPool(frameSize); try { m_offset = 0; m_buffer = msg.Data; // put signature PutNumber2(0xAAA0 | 1); // put message id PutNumber1((byte)Id); switch (Id) { case MessageId.Hello: Hello.Write(this); break; case MessageId.Whisper: Whisper.Write(this); break; case MessageId.Shout: Shout.Write(this); break; case MessageId.Join: Join.Write(this); break; case MessageId.Leave: Leave.Write(this); break; case MessageId.Ping: Ping.Write(this); break; case MessageId.PingOk: PingOk.Write(this); break; } // Send the data frame output.Send(ref msg, false); } finally { m_buffer = null; msg.Close(); } }
public void TestEnumOutRef() { var hello = new Hello(); Enum e; hello.EnumOutRef((int)Enum.C, out e); Assert.That(e, Is.EqualTo(Enum.C)); }
public object Any(Hello req) { return(new HelloResponse { Result = "Hello, " + req.Name }); }
public object Any(Hello request) { return(new HelloResponse { Result = $"Hello, {request.Name}!" }); }
public object Any(Hello request) => new HelloResponse { Result = $"Hello, {request.Name}!" };
public void Greet() { var result = Hello.Greet("Kail"); Assert.StartsWith("Hello Kail, it is", result); }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Hello obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
public IHttpActionResult SaveHello([MapFromBody(typeof(HelloDto))] Hello hello) { return(Ok()); }
public void TestPrimitiveInOutRefParameters() { var hello = new Hello(); int i = 10; Assert.That(hello.TestPrimitiveInOutRef(ref i), Is.True); Assert.That(i, Is.EqualTo(20)); }
public void TestTradesReceive() { var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); var helloMsg = new Hello() { apikey = System.Guid.Parse(config["TestApiKey"]), subscribe_data_type = new string[] { "trade", "quote" }, subscribe_filter_exchange_id = new string[] { "COINBASE" } }; using (var wsClient = new CoinApiWsClient(true)) { var mre_bs = new ManualResetEvent(false); var mre_cb = new ManualResetEvent(false); wsClient.TradeEvent += (s, i) => { if (i.symbol_id.StartsWith("GEMINI")) { mre_cb.Set(); } else if (i.symbol_id.StartsWith("COINBASE")) { mre_bs.Set(); } }; wsClient.QuoteEvent += (s, i) => { if (i.symbol_id.StartsWith("GEMINI")) { mre_cb.Set(); } else if (i.symbol_id.StartsWith("COINBASE")) { mre_bs.Set(); } }; // BITSTAMP wsClient.SendHelloMessage(helloMsg); if (!wsClient.ConnectedEvent.WaitOne(TimeSpan.FromSeconds(10))) { Assert.Fail("should connect"); } if (!mre_bs.WaitOne(TimeSpan.FromSeconds(10))) { Assert.Fail("bistamp should be"); } if (mre_cb.WaitOne(TimeSpan.FromSeconds(10))) { Assert.Fail("coinbase should not"); } // coinbase hello helloMsg = new Hello() { apikey = System.Guid.Parse(config["TestApiKey"]), subscribe_data_type = new string[] { "trade", "quote" }, subscribe_filter_exchange_id = new string[] { "GEMINI" } }; wsClient.SendHelloMessage(helloMsg); // received for coinbase - change of hello mre_cb.Reset(); if (!mre_cb.WaitOne(TimeSpan.FromSeconds(10))) { Assert.Fail("dont received for coinbase"); } mre_bs.Reset(); if (mre_bs.WaitOne(TimeSpan.FromSeconds(10))) { Assert.Fail("received for bitstapm after coinbase"); } } }
public void Can_receive_and_process_standard_request_reply_combo() { mqHost = CreateMqHost(); string messageReceived = null; mqHost.RegisterHandler<Hello>(m => new HelloResponse { Result = "Hello, " + m.GetBody().Name }); mqHost.RegisterHandler<HelloResponse>(m => { messageReceived = m.GetBody().Result; return null; }); mqHost.Start(); var mqClient = mqHost.CreateMessageQueueClient(); var dto = new Hello { Name = "ServiceStack" }; mqClient.Publish(dto); Thread.Sleep(2000); mqHost.Dispose(); Assert.That(messageReceived, Is.EqualTo("Hello, ServiceStack")); }
/// <param name='name'> /// </param> /// <param name='title'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HelloResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <HelloResponse> > PostWithHttpMessagesAsync(string name = default(string), string title = default(string), Hello body = default(Hello), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("name", name); tracingParameters.Add("title", title); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "hello").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.Accept != null) { if (_httpRequest.Headers.Contains("Accept")) { _httpRequest.Headers.Remove("Accept"); } _httpRequest.Headers.TryAddWithoutValidation("Accept", Client.Accept); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (body != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new HelloResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); HelloResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <HelloResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <HelloResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <HelloResponse>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public object Any(Hello request) { return new HelloResponse { Result = request.Name }; }
private void WriteHello(string name) { //welcomeLabel.Text = "Hello, " + (String.IsNullOrEmpty(nameEntry.Text) ? "not authorized user" : nameEntry.Text) + "!"; welcomeLabel.Text = Hello.TimeHello(name); }
public string SayHello() { Hello myHello = new Hello(); return(myHello.SayHello()); }
public object Any(Hello request) { return(request); }
public void DefaultMessage() { Assert.True( Hello.SayHello().Contains(Hello.defaultUser) ); }
public void Greet() { var result = Hello.Greet("wesh"); Assert.StartsWith("Salut BG wesh, il est", result); }
public void GreetUpper() { var result = Hello.GreetUpper("Kail"); Assert.StartsWith("Hello KAIL, it is", result); }
public void GreetUpper() { var result = Hello.GreetUpper("KALL"); Assert.StartsWith("Salut BG KALL, il est", result); }
public async Task HandleHandshakeMessage(HandshakeType handshakeMessageType, ReadableBuffer buffer, ref WritableBuffer outBuffer) { switch (State) { case StateType.WaitServerHello: if (handshakeMessageType == HandshakeType.server_hello) { Hello.ReadServerHello(buffer, this); GenerateHandshakeKeys(); State = StateType.WaitEncryptedExtensions; return; } break; case StateType.WaitEncryptedExtensions: if (handshakeMessageType == HandshakeType.encrypted_extensions) { HandshakeContext(buffer); State = StateType.WaitServerVerification; return; } break; case StateType.WaitServerVerification: if (handshakeMessageType == HandshakeType.certificate) { Handshake.Certificates.ReadCertificates(buffer, Listener); HandshakeContext(buffer); return; } if (handshakeMessageType == HandshakeType.certificate_verify) { HandshakeContext(buffer); State = StateType.WaitServerFinished; return; } break; case StateType.WaitServerFinished: if (handshakeMessageType == HandshakeType.finished) { HandshakeContext(buffer); var hash = new byte[HandshakeHash.HashSize]; HandshakeHash.InterimHash(hash); var writer = pipe.Alloc(); ServerHandshakeTls13.ServerFinished(ref writer, this, KeySchedule.GenerateClientFinishedKey()); _dataForCurrentScheduleSent.Reset(); await writer.FlushAsync(); await _dataForCurrentScheduleSent; GenerateApplicationKeys(hash); KeySchedule.GenerateResumptionSecret(); HandshakeHash.Dispose(); HandshakeHash = null; State = StateType.HandshakeComplete; return; } break; case StateType.HandshakeComplete: if (handshakeMessageType == HandshakeType.new_session_ticket) { Listener.ResumptionProvider.RegisterSessionTicket(buffer); return; } break; } Alerts.AlertException.ThrowAlert(Alerts.AlertLevel.Fatal, Alerts.AlertDescription.unexpected_message, ""); }
public static Ice.DispatchStatus shutdown___(Hello obj__, IceInternal.Incoming inS__, Ice.Current current__) { Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode); inS__.readEmptyParams(); obj__.shutdown(current__); inS__.writeEmptyParams__(); return Ice.DispatchStatus.DispatchOK; }
static void Main(string [] args) { Hello x = new Hello(); System.Console.WriteLine("Hello, world."); }
protected void Test (Hello hello) { hello (); }
public virtual void Run() { Hello.SayHello(); }
public void TestEnumInOutRef() { var hello = new Hello(); var e = Enum.E; hello.EnumInOut(ref e); Assert.That(e, Is.EqualTo(Enum.F)); }
public static void Main() { Hello.Hi(); Hello.Bye(); }
public void TestNullRef() { var hello = new Hello (); Assert.That(hello.RetNull(), Is.Null); }
public object Any(Hello request) { return(new HelloResponse { Result = "Hello, {0}!".Fmt(request.Name) }); }
public void TestPrimitiveOutRefParameters() { var hello = new Hello(); float f; Assert.That(hello.TestPrimitiveOutRef(out f), Is.True); Assert.That(f, Is.EqualTo(10.0f)); }
public void TestNullRef() { var hello = new Hello(); Assert.That(hello.RetNull(), Is.Null); }
static void Main () { IFoo f = new Hello (); int i = f.GetHashCode (); bool b = f.Equals (f); }
async public Task Hello(Hello info) { Console.WriteLine("Hello! My name: " + info.name.ToString()); return; }
public object Any(Hello request) { return new HelloResponse { Result = "Hello, {0}!".Fmt(request.Name) }; }
public HelloDecorator() { this.hello = new Hello(); this.hello.setMessage("Hello World"); }