Exemple #1
0
        public System.Threading.Tasks.Task <HelloWorldResponse> HelloWorldAsync()
        {
            HelloWorldRequest inValue = new HelloWorldRequest();

            inValue.Body = new HelloWorldRequestBody();
            return(((AddNumbersSoap)(this)).HelloWorldAsync(inValue));
        }
        public void DotnetWscCallJavaWspTest()
        {
            // Ensure that the WSP is up and running.
            Thread.Sleep(30000);

            var succeeded = false;

            // Retrieve token
            IStsTokenService stsTokenService =
                new StsTokenServiceCache(
                    TokenServiceConfigurationFactory.CreateConfiguration()
                    );
            var securityToken = stsTokenService.GetToken();

            // Call WSP with token
            var client = new HelloWorldPortTypeClient();

            var channelWithIssuedToken =
                client.ChannelFactory.CreateChannelWithIssuedToken(
                    securityToken
                    );

            var helloWorldRequestJohn = new HelloWorldRequest("John");

            succeeded =
                channelWithIssuedToken
                .HelloWorld(helloWorldRequestJohn)
                .response.Equals("Hello John");

            Assert.IsTrue(succeeded);
        }
    public System.Threading.Tasks.Task <HelloWorldResponse> HelloWorldAsync()
    {
        HelloWorldRequest inValue = new HelloWorldRequest();

        inValue.Body = new HelloWorldRequestBody();
        return(((WebServiceCIMPMessageGenerationSoap)(this)).HelloWorldAsync(inValue));
    }
        public async Task <HelloWorldResponse> GetMessage([FromBody] HelloWorldRequest request)
        {
            var response = new HelloWorldResponse();

            if (!ModelState.IsValid)
            {
                response.Message = "Invalid request";

                return(response);
            }

            //implement logic here to get the message from the database once the database becomes available
            //similar to the below
            //var helloWorld = await _context.HelloWorld
            //                    .AsNoTracking()
            //                    .Where(x => x.Message == request.Message)
            //                    .FirstOrDefaultAsync();

            //since the database is not available at this time to return the data into the HelloWorld model,
            //I'm assigning it the value of HelloWorldRequest
            var helloWorld = new HelloWorld();

            helloWorld.Message = request.Message;

            response = HelloWorldMapper.MapFromEntity(helloWorld);

            return(response);
        }
Exemple #5
0
        private static void HandleResponse(Task <HelloWorldResponse> task, HelloWorldRequest request, IMetricsRoot metrics)
        {
            metrics.Measure.Counter.Increment(SentRequestsCount);

            if (task.IsFaulted)
            {
                metrics.Measure.Counter.Increment(FailedRequestsCount);

                if (task.Exception != null)
                {
                    Logger.Log(LogLevel.Error, task.Exception.Message, task.Exception);
                }
            }
            else if (task.IsCompletedSuccessfully)
            {
                metrics.Measure.Counter.Increment(SuccessfulRequestsCount);

                var response = task.Result;

                if (response == null)
                {
                    metrics.Measure.Counter.Increment(ApplicationErrorCount, "null-response");
                }
                else if (string.IsNullOrEmpty(response.Message))
                {
                    metrics.Measure.Counter.Increment(ApplicationErrorCount, "empty-message");
                }
                else if (response.Message.Equals(request.Message) == false)
                {
                    metrics.Measure.Counter.Increment(ApplicationErrorCount, "non-matching-message");
                }
            }
        }
        public async Task <HelloWorldResponse> Post(HelloWorldRequest request)
        {
            var response = new HelloWorldResponse();

            try
            {
                if (ModelState.IsValid)
                {
                    var entityToStore = HelloWorldMapper.MapToEntity(request);

                    _context.HelloWorld.Add(entityToStore);

                    //uncomment this once the database is actually set up
                    await _context.SaveChangesAsync();

                    response.Message = "Message successfully saved to the database";
                }
            }
            catch (DbUpdateException ex)
            {
                response.Message = string.Format("There was an error when updating database: {0}", ex.InnerException);
            }

            return(response);
        }
Exemple #7
0
 public override Task <HelloWorldResponse> SayHelloWorld(HelloWorldRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloWorldResponse
     {
         Message = $"Hello World from GRPC! Hostname: {Environment.MachineName}"
     }));
 }
Exemple #8
0
 public override Task <HelloWorldResponse> HelloWorld(HelloWorldRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloWorldResponse()
     {
         Message = "Hello World! " + request.Name
     }));
 }
Exemple #9
0
 public override Task <HttpBody> HelloWorld(HelloWorldRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HttpBody
     {
         ContentType = "application/xml",
         Data = ByteString.CopyFrom(Encoding.UTF8.GetBytes(@"<message>Hello world</message>"))
     }));
 }
        public static HelloWorld MapToEntity(HelloWorldRequest request)
        {
            var helloWorld = new HelloWorld();

            helloWorld.Message = request.Message;

            return(helloWorld);
        }
Exemple #11
0
        static void Main(string[] args)
        {
            // Setup Log4Net configuration by loading it from configuration file.
            // log4net is not necessary and is only being used for demonstration.
            XmlConfigurator.Configure();

            // To ensure that the WSP is up and running.
            Thread.Sleep(1000);

            // Retrieve token
            IStsTokenService stsTokenService =
                new StsTokenServiceCache(
                    TokenServiceConfigurationFactory.CreateConfiguration()
                    );
            var securityToken = stsTokenService.GetToken();

            // Call WSP with token
            var client = new HelloWorldPortTypeClient();

            var channelWithIssuedToken =
                client.ChannelFactory.CreateChannelWithIssuedToken(
                    securityToken
                    );

            var helloWorldRequestJohn = new HelloWorldRequest("John");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJohn).response
                );

            var helloWorldRequestJane = new HelloWorldRequest("Jane");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJane).response
                );

            try
            {
                // third call will trigger a SOAPFault
                var helloWorldRequest = new HelloWorldRequest("");
                Console.WriteLine(
                    channelWithIssuedToken.HelloWorld(helloWorldRequest).response
                    );
            }
            catch (Exception ex)
            {
                Console.WriteLine("Expected SOAPFault caught: " + ex.Message);
            }

            // Encrypted calls fails client side. However, encryption at message
            // level is not required and no further investigation has been
            // putted into this issue yet.
            //
            // Console.WriteLine(channelWithIssuedToken.HelloEncryptAndSign("Schultz"));

            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
Exemple #12
0
        public IApiObjectResponse <string> PostModelStateManualValidation([FromBody] HelloWorldRequest request)
        {
            if (!ModelState.IsValid)
            {
                throw new BadRequestResponseException(ModelState);
            }

            return(new Ok.Object <string>(data: $"Hello {request.Name} {request.Surname}"));
        }
    public string HelloWorld()
    {
        HelloWorldRequest inValue = new HelloWorldRequest();

        inValue.Body = new HelloWorldRequestBody();
        HelloWorldResponse retVal = ((WebServiceCIMPMessageGenerationSoap)(this)).HelloWorld(inValue);

        return(retVal.Body.HelloWorldResult);
    }
Exemple #14
0
        public string HelloWorld()
        {
            HelloWorldRequest inValue = new HelloWorldRequest();

            inValue.Body = new HelloWorldRequestBody();
            HelloWorldResponse retVal = ((AddNumbersSoap)(this)).HelloWorld(inValue);

            return(retVal.Body.HelloWorldResult);
        }
Exemple #15
0
 public override Task <HelloWorldResponse> HelloWorld(HelloWorldRequest request, ServerCallContext context)
 {
     return(Task.FromResult(new HelloWorldResponse
     {
         Hello = new HelloWorld
         {
             Greeting = "Hello",
             Name = request.Name,
         }
     }));
 }
        public async void GetPassingTest()
        {
            var request = new HelloWorldRequest();

            request.Message = "Hello World!";

            var helloWorldApiCall = new HelloWorldApiCall("http://localhost:53252/api/HelloWorld/GetMessage");

            var response = await helloWorldApiCall.Get(request);

            Assert.Equal(response.Message, request.Message);
        }
        public async void GetFalingTest()
        {
            var request = new HelloWorldRequest();

            request.Message = "Hello World";

            var controller = new HelloWorldController();

            var response = await controller.GetMessage(request);

            Assert.NotEqual("Hi there", response.Message);
        }
Exemple #18
0
        static async Task MainAsync(string[] args)
        {
            RuntimeTypeModel.Default.Add(typeof(Envelope <HelloWorldRequest>), true);
            RuntimeTypeModel.Default.Add(typeof(HelloWorldRequest), true);
            RuntimeTypeModel.Default.Add(typeof(HelloWorldResponse), true);
            RuntimeTypeModel.Default.CompileInPlace();
            var totalTime = 0L;
            var requests  = 100000;

            var client = ClientFactory.Create <HelloWorldRequest, HelloWorldResponse>(c =>
            {
                c.ConnectTo()
                .Using(new JsonSerializer())
                .ForOperation("SampleServer", "HelloWorld")
                .SetPoolingSize(10, 10)
                .SetMaximumTimeout(TimeSpan.FromSeconds(5));
            });

            using (client)
            {
                var cts   = new CancellationTokenSource();
                var tasks = new List <Task <DateTime> >();
                var sw    = new Stopwatch();
                sw.Start();

                for (var i = 0; i < requests; i++)
                {
                    var request = new HelloWorldRequest
                    {
                        Message = Guid.NewGuid().ToString()
                    };

                    var task = client
                               .RequestAsync(request, cts.Token)
                               .ContinueWith(r => DateTime.UtcNow, cts.Token);

                    tasks.Add(task);
                }

                var dateTimeList = Task.WhenAll(tasks).GetAwaiter().GetResult();
                sw.Stop();
                totalTime = sw.ElapsedMilliseconds;
                Console.WriteLine($"Avg response time: {totalTime / (decimal)requests}ms");
                var aggregate = dateTimeList
                                .GroupBy(x => x.ToString("ddMMyyyyHHmmss"));
                foreach (var second in aggregate)
                {
                    Console.WriteLine($"{second.Count()}req/s");
                }
                Console.ReadLine();
            }
        }
Exemple #19
0
        static void Main(string[] args)
        {
            var request = new HelloWorldRequest();

            request.Message = "Hello World!";

            var response          = new HelloWorldResponse();
            var helloWorldApiCall = new HelloWorldApiCall("http://localhost:53252/api/HelloWorld/GetMessage");

            Task.Run(async() =>
                     response = await helloWorldApiCall.Get(request)
                     ).Wait();

            Console.WriteLine(response.Message);

            System.Threading.Thread.Sleep(10000);
        }
Exemple #20
0
        /// <summary>
        /// HelloWorld 请求方法
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <ApiResponse <string> > Get(HelloWorldRequest request)
        {
            ApiResponse <string> apiResponse = ApiResponse <string> .GetInstance();

            if (null == request || string.IsNullOrEmpty(request.SayHi))
            {
                return(await Task.FromResult(apiResponse.Error()));
            }

            try
            {
                string sayHi = $"消息内容为--{request.SayHi}";
                apiResponse.Success(sayHi);
            }
            catch (Exception)
            {
                throw;
            }

            return(await Task.FromResult(apiResponse));
        }
Exemple #21
0
        static Task Main(string[] args)
        {
            RuntimeTypeModel.Default.Add(typeof(Envelope <HelloWorldRequest>), true);
            RuntimeTypeModel.Default.Add(typeof(HelloWorldRequest), true);
            RuntimeTypeModel.Default.Add(typeof(HelloWorldResponse), true);
            RuntimeTypeModel.Default.CompileInPlace();

            var requests = 100000;

            var client = ClientFactory.Create <HelloWorldRequest, HelloWorldResponse>(c =>
            {
                c.ConnectTo()
                .Using(new JsonSerializer())
                .Using(Logger)
                .ForOperation("SampleServer", "HelloWorld")
                .SetPoolingSize(10, 10)
                .SetRetries(3)
                .SetMaximumTimeout(TimeSpan.FromMilliseconds(50));
            });

            var metrics = new MetricsBuilder()
                          .Report.ToConsole(o =>
            {
                o.FlushInterval          = TimeSpan.FromSeconds(2);
                o.MetricsOutputFormatter = new MetricsJsonOutputFormatter();
            })
                          .Build();

            using (client)
            {
                var cts             = new CancellationTokenSource();
                var parallelOptions = new ParallelOptions
                {
                    CancellationToken      = cts.Token,
                    MaxDegreeOfParallelism = 30
                };

                Parallel.For(0, requests, parallelOptions, index =>
                {
                    var request = new HelloWorldRequest
                    {
                        Message = Guid.NewGuid().ToString()
                    };

                    using (metrics.Measure.Timer.Time(RequestTimer))
                    {
                        client
                        .RequestAsync(request, cts.Token, Priority.Normal, m =>
                        {
                            m.AddHeader("test", "123")
                            .AddHeader("test2", 123);
                        })
                        .ContinueWith(r => HandleResponse(r, request, metrics), cts.Token)
                        .ConfigureAwait(false)
                        .GetAwaiter()
                        .GetResult();
                    }
                });
            }

            Task.WaitAll(metrics.ReportRunner.RunAllAsync().ToArray());

            return(Task.CompletedTask);
        }
Exemple #22
0
 public Task <HelloWorldResponse> Get(HelloWorldRequest request)
 {
     return(Task.FromResult(new HelloWorldResponse()));
 }
 System.Threading.Tasks.Task <HelloWorldResponse> WebServiceCIMPMessageGenerationSoap.HelloWorldAsync(HelloWorldRequest request)
 {
     return(base.Channel.HelloWorldAsync(request));
 }
Exemple #24
0
 HelloWorldResponse QuerySoap.HelloWorld(HelloWorldRequest request)
 {
     return(base.Channel.HelloWorld(request));
 }
Exemple #25
0
 public IApiObjectResponse <string> ModelStateAutoValidation([FromBody] HelloWorldRequest request)
 {
     return(new Ok.Object <string>(data: $"Hello {request.Name} {request.Surname}"));
 }
Exemple #26
0
        static void Main(string[] args)
        {
            // Setup Log4Net configuration by loading it from configuration file
            // log4net is not necessary and is only being used for demonstration
            XmlConfigurator.Configure();

            // To ensure that the WSP is up and running.
            Thread.Sleep(1000);

            // Retrieve token
            IStsTokenService stsTokenService =
                new StsTokenServiceCache(
                    TokenServiceConfigurationFactory.CreateConfiguration()
                    );
            var securityToken = stsTokenService.GetToken();

            // Call WSP with token
            var hostname        = "https://localhost:8443/HelloWorld/services/helloworld";
            var customBinding   = new Channels.CustomBinding();
            var endpointAddress = new System.ServiceModel.EndpointAddress(
                new Uri(hostname),
                System.ServiceModel.EndpointIdentity.CreateDnsIdentity(
                    //"wsp.oioidws-net.dk TEST (funktionscertifikat)"
                    "eID JAVA test (funktionscertifikat)"
                    ),
                new Channels.AddressHeader[] { }
                );

            var asymmetric =
                new Channels.AsymmetricSecurityBindingElement
                (
                    new SecurityTokens.X509SecurityTokenParameters(
                        SecurityTokens.X509KeyIdentifierClauseType.Any,
                        SecurityTokens.SecurityTokenInclusionMode.AlwaysToInitiator
                        ),
                    new Soap.StrCustomization.CustomizedIssuedSecurityTokenParameters(
                        "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
                        )
            {
                UseStrTransform = true
            }
                )
            {
                AllowSerializedSigningTokenOnReply = true,
                ProtectTokens = true
            };

            asymmetric.SetKeyDerivation(false);
            var messageEncoding =
                new Channels.TextMessageEncodingBindingElement
            {
                MessageVersion =
                    Channels.MessageVersion.Soap12WSAddressing10
            };
            var transport =
                (hostname.ToLower().StartsWith("https://"))
                    ? new Channels.HttpsTransportBindingElement()
                    : new Channels.HttpTransportBindingElement();

            customBinding.Elements.Add(asymmetric);
            customBinding.Elements.Add(messageEncoding);
            customBinding.Elements.Add(transport);

            System.ServiceModel.ChannelFactory <HelloWorldPortType> factory =
                new System.ServiceModel.ChannelFactory <HelloWorldPortType>(
                    customBinding, endpointAddress
                    );
            factory.Credentials.UseIdentityConfiguration = true;
            factory.Credentials.ServiceCertificate.SetScopedCertificate(
                X509Certificates.StoreLocation.LocalMachine,
                X509Certificates.StoreName.My,
                X509Certificates.X509FindType.FindByThumbprint,
                //"1F0830937C74B0567D6B05C07B6155059D9B10C7",
                "85398FCF737FB76F554C6F2422CC39D3A35EC26F",
                new Uri(hostname)
                );
            factory.Endpoint.Behaviors.Add(
                new Soap.Behaviors.SoapClientBehavior()
                );

            var channelWithIssuedToken =
                factory.CreateChannelWithIssuedToken(securityToken);

            var helloWorldRequestJohn = new HelloWorldRequest("John");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJohn).response
                );

            var helloWorldRequestJane = new HelloWorldRequest("Jane");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJane).response
                );

            try
            {
                // third call will trigger a SOAPFault
                var helloWorldRequest = new HelloWorldRequest("");
                Console.WriteLine(
                    channelWithIssuedToken.HelloWorld(helloWorldRequest).response
                    );
            }
            catch (Exception ex)
            {
                Console.WriteLine("Expected SOAPFault caught: " + ex.Message);
            }

            // Encrypted calls fails client side. However, encryption at message
            // level is not required and no further investigation has been
            // putted into this issue yet.
            //
            // Console.WriteLine(channelWithIssuedToken.HelloEncryptAndSign("Schultz"));

            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
Exemple #27
0
 HelloWorldResponse AddNumbersSoap.HelloWorld(HelloWorldRequest request)
 {
     return(base.Channel.HelloWorld(request));
 }
 HelloWorldResponse WebServiceCIMPMessageGenerationSoap.HelloWorld(HelloWorldRequest request)
 {
     return(base.Channel.HelloWorld(request));
 }
 public HelloWorld HelloWorld(HelloWorldRequest request)
 {
     return(new HelloWorld {
         Message = string.IsNullOrWhiteSpace(request.Message) ?  "Hello, World!" : request.Message
     });
 }
 public HelloWorld HelloWorld(HelloWorldRequest request)
 {
     return new HelloWorld { Message = string.IsNullOrWhiteSpace(request.Message) ?  "Hello, World!" : request.Message };
 }
Exemple #31
0
 System.Threading.Tasks.Task <HelloWorldResponse> AddNumbersSoap.HelloWorldAsync(HelloWorldRequest request)
 {
     return(base.Channel.HelloWorldAsync(request));
 }