public static IGatewayServiceManagement CreateGatewayManagementChannel(Binding binding, Uri remoteUri, X509Certificate2 cert)
 {
     WebChannelFactory<IGatewayServiceManagement> factory = new WebChannelFactory<IGatewayServiceManagement>(binding, remoteUri);
     factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
     factory.Credentials.ClientCertificate.Certificate = cert;
     return factory.CreateChannel();
 }
Beispiel #2
0
        public static void Snippet6()
        {
            // <Snippet6>
            Uri            baseAddress = new Uri("http://localhost:8000");
            WebServiceHost host        = new WebServiceHost(typeof(Service), baseAddress);

            try
            {
                host.Open();

                // The endpoint name passed to the constructor must match an endpoint element
                // in the application configuration file
                WebChannelFactory <IService> cf = new WebChannelFactory <IService>("MyEndpoint", new Uri("http://localhost:8000"));
                IService channel = cf.CreateChannel();
                string   s;

                Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
                s = channel.EchoWithGet("Hello, world");
                Console.WriteLine("   Output: {0}", s);
            }
            catch (CommunicationException ex)
            {
                Console.WriteLine("An exception occurred: " + ex.Message);
            }
            // </Snippet6>
        }
Beispiel #3
0
        public string CreateSession(string sessionId)
        {
            using (new ApplicationContextScope(new ApplicationContext()))
            {
                ApplicationContext.Current.Items["SessionId"] = sessionId;
                try
                {
                    var channelFactory =
                        new WebChannelFactory<ISessionServiceRest>(Configuration.SessionServiceConfigurationName);
                    ISessionServiceRest channel = channelFactory.CreateChannel();

                    if (channel is IContextChannel)
                        using (new OperationContextScope(channel as IContextChannel))
                        {
                            WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "CreateSession");
                            return channel.CreateSession(sessionId);
                        }
                }
                catch (Exception exception)
                {
                    Logger.LogException(exception, Source, "AddRequestSessionData", Severity.Major);
                }
            }
            return null;
        }
Beispiel #4
0
    public static void Test()
    {
        string         baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host        = new WebServiceHost(typeof(Service), new Uri(baseAddress));

        host.Open();
        Console.WriteLine("Host opened");
        WebChannelFactory <ITest> factory = new WebChannelFactory <ITest>(new Uri(baseAddress));
        ITest proxy = factory.CreateChannel();

        using (new OperationContextScope((IContextChannel)proxy))
        {
            WebOperationContext.Current.OutgoingRequest.ContentType = "text/xml";
            Console.WriteLine(proxy.Process());
        }
        using (new OperationContextScope((IContextChannel)proxy))
        {
            WebOperationContext.Current.OutgoingRequest.ContentType = "application/xml";
            Console.WriteLine(proxy.Process());
        }
        ((IClientChannel)proxy).Close();
        factory.Close();
        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
        public void Stop(string requestId, StopReason reason)
        {
            try
            {
                string serviceUrl = Settings.GetAsString("ServiceURL", "");

                if (requestProperties == null || !requestProperties.ContainsKey(requestId) || !requestProperties[requestId].ContainsKey("RequestToken"))
                {
                    return;
                }

                string requestToken = requestProperties[requestId]["RequestToken"];

                using (var factory = new WebChannelFactory <IModelProcessorRestService>(new Uri(serviceUrl)))
                {
                    var channel = factory.CreateChannel();
                    //channel.Stop(requestId, (Lpp.Dns.DataMart.Model.Rest.StopReason)Enum.ToObject(typeof(StopReason), (int) reason));
                    channel.Stop(requestToken, (Lpp.Dns.DataMart.Model.Rest.StopReason)Enum.ToObject(typeof(StopReason), (int)reason));
                }
            }
            catch (Exception ex)
            {
                log.Debug(ex);
                throw new ModelProcessorError(ex.Message, ex);
            }
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            var factory=new WebChannelFactory<IMachine>(new Uri("http://localhost:8080/wcf"));
            IMachine machine = factory.CreateChannel();

               while (true)
            {
                Console.WriteLine("To submit press 1 \nTo get all machines press 2 \nTo get specific machine name press 3 ");
                string readLine = Console.ReadLine();

                if (readLine == "1")
                {
                    Console.WriteLine("please enter machine name :\n");
                    string machineName = Console.ReadLine();
                    machine.submitMachine(machineName);
                }
                else if (readLine == "2")
                {
                    string allMachines = machine.getAllMachines();

                    Console.WriteLine(allMachines);
                }
                else if (readLine == "3")
                {
                    Console.WriteLine("please enter the machine Id \n");
                    string machineId = Console.ReadLine();
                    string machineName = machine.getMachineName(machineId);
                    Console.WriteLine(machineName);
                }
                else
                {
                    break;
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// </summary>
        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Gathering files");
                var files = new List<FileDescriptor>();
                if (args != null)
                {
                    files.AddRange(
                        args
                        .Where(File.Exists)
                        .Select(a => new FileDescriptor { Name = a, Contents = File.ReadAllBytes(a) }));
                }

                Console.WriteLine("Send files");
                using (var f = new WebChannelFactory<IFileTracker>(new Uri("http://localhost/samplewcf/Call.svc/FileTracker")))
                {
                    var c = f.CreateChannel();
                    var i = c.Track(files.ToArray());
                    Console.WriteLine("Server said:");
                    Console.Write(i);
                }
                Console.WriteLine("Done");
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ResetColor();
            }
        }
 public static ISqlDatabaseManagement CreateSqlDatabaseManagementChannel(Binding binding, Uri remoteUri, X509Certificate2 cert, string requestSessionId)
 {
     WebChannelFactory<ISqlDatabaseManagement> factory = new WebChannelFactory<ISqlDatabaseManagement>(binding, remoteUri);
     factory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector(requestSessionId));
     factory.Credentials.ClientCertificate.Certificate = cert;
     return factory.CreateChannel();
 }
Beispiel #9
0
        public decimal GetVoucherAmount(string sessionId, string voucherCode)
        {
            using (new ApplicationContextScope(new ApplicationContext()))
            {
                ApplicationContext.Current.Items["SessionId"] = sessionId;
                try
                {
                    var channelFactory =
                        new WebChannelFactory<IPaymentServiceRest>(Configuration.PaymentServiceConfigurationName);
                    IPaymentServiceRest channel = channelFactory.CreateChannel();

                    if (channel is IContextChannel)
                        using (new OperationContextScope(channel as IContextChannel))
                        {
                            WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "GetVoucherAmount");
                            var response = channel.GetVoucherAmount(sessionId, voucherCode);
                            return response;
                        }
                }
                catch(Exception ex)
                {
                    Logger.LogException(ex, Source, "GetVoucherAmount", Severity.Critical);
                }
            }
            return 0M;
        }
Beispiel #10
0
        public ChangeMobileResponse ChangeMobile(string sessionId, string authenticationId, string mobile)
        {
            using (new ApplicationContextScope(new ApplicationContext()))
            {
                ApplicationContext.SetSessionId(sessionId);
                try
                {
                    var channelFactory =
                        new WebChannelFactory<ILoginServiceRest>(Configuration.LoginServiceConfigurationName);
                    ILoginServiceRest channel = channelFactory.CreateChannel();

                    if (channel is IContextChannel)
                        using (new OperationContextScope(channel as IContextChannel))
                        {
                            WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "ChangeMobile");
                            return channel.ChangeMobile(sessionId, authenticationId, mobile);
                        }
                }
                catch (Exception exception)
                {
                    Logger.LogException(exception, Source, "ChangeMobile", Severity.Major);
                }
            }
            return null;
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            Console.ReadLine();
             //var client = new EvalServiceClient("BasicHttpBinding_IEvalService");

             WebChannelFactory<IEvalService> cf =
            new WebChannelFactory<IEvalService>(new Uri("http://localhost:8080/evalservice"));

             IEvalService client = cf.CreateChannel();

             client.SubmitEval(new Eval
             {
            Comments = "This came from code",
            Submitter = "Sean",
            TimeSubmitted = DateTime.Now
             });
             Console.WriteLine("Save success");
             Console.WriteLine("Load Evals");
             var evals = client.GetEvals();
             foreach (var eval in evals)
             {
            Console.WriteLine(eval.Comments);
             }
             Console.WriteLine("End load Evals");
             Console.Read();
        }
Beispiel #12
0
 public Blip(string user, string password)
 {
     this.user = user;
     this.password = password;
     channelFactory = new WebChannelFactory<IBlipApi>(GetBinding(), new Uri(BlipApiUrl));
     api = channelFactory.CreateChannel();
 }
        public ReservationListingResponse GetReservationListing(string sessionId, RequestParams requestParams)
        {
            using (new ApplicationContextScope(new ApplicationContext()))
            {
                ApplicationContext.SetSessionId(sessionId);
                try
                {
                    var channelFactory =
                        new WebChannelFactory<IAirlinesAdminServiceRest>(
                            Configuration.AirlinesAdminServiceConfigurationName);
                    IAirlinesAdminServiceRest channel = channelFactory.CreateChannel();

                    if (channel is IContextChannel)
                        using (new OperationContextScope(channel as IContextChannel))
                        {
                            WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName",
                                                                                    "GetReservationListing");
                            ReservationListingResponse response = channel.GetReservationListing(sessionId, requestParams);
                            if (response != null && response.IsSuccess)
                            {
                                return response;
                            }
                        }
                }
                catch (Exception exception)
                {
                    Logger.LogException(exception, Source, "GetReservationListing", Severity.Major);
                }
            }
            return new ReservationListingResponse
                       {
                           IsSuccess = false,
                           ErrorMessage = "Failed to get Reservation Listing. Please try again after some time"
                       };
        }
Beispiel #14
0
        public GetTokenResponse GetToken(string sessionId, string tokenId)
        {
            using (new ApplicationContextScope(new ApplicationContext()))
            {
                ApplicationContext.Current.Items["SessionId"] = sessionId;
                try
                {
                    var channelFactory =
                        new WebChannelFactory<ITokenServiceRest>(Configuration.TokenServiceConfigurationName);
                    ITokenServiceRest channel = channelFactory.CreateChannel();

                    if (channel is IContextChannel)
                        using (new OperationContextScope(channel as IContextChannel))
                        {
                            WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "GenerateToken");
                            GetTokenResponse response = channel.GetToken(tokenId);
                            return response;
                        }
                }
                catch (Exception exception)
                {
                    Logger.LogException(exception, Source, "GenerateToken", Severity.Major);
                }
            }
            return null;
        }
        public static T CreateServiceManagementChannel <T>(Uri remoteUri, string username, string password, params IEndpointBehavior[] behaviors)
            where T : class
        {
            WebChannelFactory <T> factory = new WebChannelFactory <T>(remoteUri);

            factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
            foreach (IEndpointBehavior behavior in behaviors)
            {
                factory.Endpoint.Behaviors.Add(behavior);
            }
            WebHttpBinding wb = factory.Endpoint.Binding as WebHttpBinding;

            wb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            wb.Security.Mode = WebHttpSecurityMode.Transport;

            if (!string.IsNullOrEmpty(username))
            {
                factory.Credentials.UserName.UserName = username;
            }
            if (!string.IsNullOrEmpty(password))
            {
                factory.Credentials.UserName.Password = password;
            }

            return(factory.CreateChannel());
        }
Beispiel #16
0
        public static void Snippet5()
        {
            // <Snippet5>
            Uri            baseAddress = new Uri("http://localhost:8000");
            WebServiceHost host        = new WebServiceHost(typeof(Service), baseAddress);

            try
            {
                host.Open();

                WebHttpBinding binding          = new WebHttpBinding();
                WebChannelFactory <IService> cf = new WebChannelFactory <IService>(binding, new Uri("http://localhost:8000"));
                IService channel = cf.CreateChannel();
                string   s;

                Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
                s = channel.EchoWithGet("Hello, world");
                Console.WriteLine("   Output: {0}", s);
            }
            catch (CommunicationException ex)
            {
                Console.WriteLine("An exception occurred: " + ex.Message);
            }
            // </Snippet5>
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Pressione <ENTER> para executar o ws.client...");
            Console.ReadLine();

            // http://localhost:2893/ (URI)

            WebChannelFactory<IProposta> client =
                new WebChannelFactory<IProposta>(
                    new Uri("http://localhost:2893/Proposta.svc"));

            IProposta clientProposta = client.CreateChannel();

            Proposta proposta = new Proposta()
            {
                DescricaoProposta = "Essa proposta foi inserida a partir do console.",
                NomeCliente = "João",
                DataHoraEnviada = DateTime.Now
            };

            Proposta proposta1 = new Proposta()
            {
                DescricaoProposta = "Essa proposta foi inserida a partir do console.",
                NomeCliente = "Maria",
                DataHoraEnviada = DateTime.Now
            };

            clientProposta.EnviarProposta(proposta);
            clientProposta.EnviarProposta(proposta1);

            Console.WriteLine("Chamada Finalizada...");
            Console.ReadLine();
        }
Beispiel #18
0
        public string GetServerVersion(string serverUrl)
        {
            WebChannelFactory <ICIFactoryServer> webChannelFactory = getWebChannelFactory(serverUrl);
            ICIFactoryServer commChannel   = webChannelFactory.CreateChannel();
            string           serverVersion = commChannel.GetVersion();

            return(serverVersion);
        }
Beispiel #19
0
        public static IGatewayServiceManagement CreateGatewayManagementChannel(Binding binding, Uri remoteUri, X509Certificate2 cert)
        {
            WebChannelFactory <IGatewayServiceManagement> factory = new WebChannelFactory <IGatewayServiceManagement>(binding, remoteUri);

            factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
            factory.Credentials.ClientCertificate.Certificate = cert;
            return(factory.CreateChannel());
        }
Beispiel #20
0
        public ProjectStatus GetProjectStatusLite(string serverUrl, string projectName)
        {
            WebChannelFactory <ICIFactoryServer> webChannelFactory = getWebChannelFactory(serverUrl);
            ICIFactoryServer commChannel   = webChannelFactory.CreateChannel();
            ProjectStatus    projectStatus = commChannel.GetProjectStatusLite(projectName);

            return(projectStatus);
        }
Beispiel #21
0
		public void CanCallRestfulHostedService()
		{
			using (var factory = new WebChannelFactory<IAmUsingWindsor>(
				new Uri("http://localhost:27197/UsingWindsorRest.svc")))
			{
				Assert.AreEqual(126, factory.CreateChannel().MultiplyValueFromWindsorConfig(3));
			}
		}
Beispiel #22
0
        public static ISqlDatabaseManagement CreateSqlDatabaseManagementChannel(Binding binding, Uri remoteUri, X509Certificate2 cert, string requestSessionId)
        {
            WebChannelFactory <ISqlDatabaseManagement> factory = new WebChannelFactory <ISqlDatabaseManagement>(binding, remoteUri);

            factory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector(requestSessionId));
            factory.Credentials.ClientCertificate.Certificate = cert;
            return(factory.CreateChannel());
        }
Beispiel #23
0
        public bool ForceBuild(string serverUrl, string projectName, string serializedClientInfo)
        {
            WebChannelFactory <ICIFactoryServer> webChannelFactory = getWebChannelFactory(serverUrl);
            ICIFactoryServer commChannel = webChannelFactory.CreateChannel();
            bool             result      = commChannel.ForceBuild(projectName, serializedClientInfo);

            return(result);
        }
Beispiel #24
0
 public void CanCallRestfulHostedService()
 {
     using (var factory = new WebChannelFactory <IAmUsingWindsor>(
                new Uri("http://localhost:27197/UsingWindsorRest.svc")))
     {
         Assert.AreEqual(126, factory.CreateChannel().MultiplyValueFromWindsorConfig(3));
     }
 }
Beispiel #25
0
        public string GetProject(string serverUrl, string projectName)
        {
            WebChannelFactory <ICIFactoryServer> webChannelFactory = getWebChannelFactory(serverUrl);
            ICIFactoryServer commChannel = webChannelFactory.CreateChannel();
            string           project     = commChannel.GetProject(projectName);

            return(project);
        }
		public static IServiceManagement CreateServiceManagementChannel(string endpointConfigurationName, Uri remoteUri, X509Certificate2 cert)
		{
			WebChannelFactory<IServiceManagement> webChannelFactory = new WebChannelFactory<IServiceManagement>(endpointConfigurationName, remoteUri);
			webChannelFactory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector());
			webChannelFactory.Credentials.ClientCertificate.Certificate = cert;
			IServiceManagement serviceManagement = webChannelFactory.CreateChannel();
			return serviceManagement;
		}
		public static IServiceManagement CreateServiceManagementChannel(Type channelType, X509Certificate2 cert)
		{
			WebChannelFactory<IServiceManagement> webChannelFactory = new WebChannelFactory<IServiceManagement>(channelType);
			webChannelFactory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector());
			webChannelFactory.Credentials.ClientCertificate.Certificate = cert;
			IServiceManagement serviceManagement = webChannelFactory.CreateChannel();
			return serviceManagement;
		}
Beispiel #28
0
        public static void TestRESTUsingWebChannelFactory()
        {
            //1) consuming the REST based service
            WebChannelFactory <ISOAPRESTDemo> cf = new WebChannelFactory <ISOAPRESTDemo>(new Uri(serviceUrlREST));
            ISOAPRESTDemo client = cf.CreateChannel();

            PrintSuccessMessage(client.EchoWithGet(message), client.EchoWithPost(message));
        }
Beispiel #29
0
        protected void SetState(string state, int sessionId = -1)
        {
            string username = GetUsername(sessionId);


            ServiceState pState = new ServiceState(state, username);

            if (EventLog.SourceExists(EVENTS_SOURCE))
            {
                string[] insertStrings = { new JavaScriptSerializer().Serialize(pState) };
                byte[]   binaryData    = {};
                m_EventLog.WriteEvent(myInfoEvent, binaryData, insertStrings);
            }

            if (!MODE.ToLower().Contains("active"))
            {
                EventLog.WriteEntry("SetState standby mode, no network sending");
                return;
            }

            ReadApiPath();

            if (!string.IsNullOrEmpty(API_PATH))
            {
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52323/api");
                //request.Method = "POST";
                //request.ContentType = "application/x-www-form-urlencoded";
                //request.AllowAutoRedirect = false;

                ////Put the post data into the request
                //byte[] data = (new ASCIIEncoding()).GetBytes("workstation=efjcnwmc&User=voemk&Event=cfhwb&time=1-1-2030");
                //request.ContentLength = data.Length;
                //Stream reqStream = request.GetRequestStream();
                //reqStream.Write(data, 0, data.Length);
                //reqStream.Close();

                using (WebChannelFactory <IWorkstationServiceLog> myChannelFactory =
                           new WebChannelFactory <IWorkstationServiceLog>(
                               new Uri(Properties.Settings.Default.ASPDataCenter)))
                {
                    IWorkstationServiceLog client = null;

                    try
                    {
                        client = myChannelFactory.CreateChannel();
                        client.WorkstationServiceLog(pState.MachineName, pState.UserName, pState.State, pState.timestamp);
                    }
                    catch (Exception ex)
                    {
                        SaveError("SetState", ex.Message);
                        if (client != null)
                        {
                            ((ICommunicationObject)client).Abort();
                        }
                    }
                }
            }
        }
Beispiel #30
0
        public HelperService()
        {
            host = new WebServiceHost(typeof(AsdepWcf), baseAddress);
            host.Open();

            WebChannelFactory <IAsdepWcf> cf = new WebChannelFactory <IAsdepWcf>(baseAddress);

            channel = cf.CreateChannel();
        }
        /// <summary>
        /// Gets a control manager.  The control manager is disposed with the runtime, so it should not
        /// be wrapped elsewhere.
        /// </summary>
        /// <returns></returns>
        private IControlManager GetControlManager()
        {
            if (_controlManagerWrapper == null)
            {
                _controlManagerWrapper = new ChannelWrapper <IControlManager>(_webChannelFactory.CreateChannel());
            }

            return(_controlManagerWrapper.Channel);
        }
        public void CanCallMethods()
        {
            var channelFactory = new WebChannelFactory <IPtController>(typeof(IPtController).FullName);

            var client = channelFactory.CreateChannel();

            //	var page = client.LoadPage("Page1");
            client.SendCommand("Scroll", "2");
        }
Beispiel #33
0
 static void CallByFactoryChannel()
 {
     using (var client = new WebChannelFactory <ITime>("TimeClient"))
     {
         var proxy  = client.CreateChannel();
         var result = proxy.GetCurrentTime();
         Console.WriteLine(result);
     }
 }
        public static IServiceManagement CreateServiceManagementChannel(X509Certificate2 cert)
        {
            WebChannelFactory<IServiceManagement> factory = new WebChannelFactory<IServiceManagement>();
            factory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector());
            factory.Credentials.ClientCertificate.Certificate = cert;

            var channel = factory.CreateChannel();
            return channel;
        }
Beispiel #35
0
        public ProjectStatus[] GetProjectsStatus(string serverUrl)
        {
            WebChannelFactory <ICIFactoryServer> webChannelFactory = getWebChannelFactory(serverUrl);
            ICIFactoryServer commChannel = webChannelFactory.CreateChannel();

            ProjectStatus[] projectsStatus = commChannel.GetProjectsStatus();

            return(projectsStatus);
        }
        public virtual List <TvShow> FindShowsByName(string name)
        {
            ITvSeries bierdopje = channelFactory.CreateChannel();

            using (Stream responseStream = bierdopje.FindShowByName(name))
            {
                string responseString = CreateStringFromStream(responseStream);
                CloseChannel(bierdopje);
                return(responseParser.GetTvShows(responseString));
            }
        }
        static void Main(string[] args)
        {
            ServiceHost sh = new ServiceHost(typeof(Service), new Uri("http://localhost:8000/"));

            sh.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "Soap");
            ServiceEndpoint endpoint = sh.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "Web");

            endpoint.Behaviors.Add(new WebHttpBehavior());

            //endpoint.EndpointBehaviors.Add(new WebHttpBehavior());

            foreach (IEndpointBehavior behavior in endpoint.Behaviors)
            {
                Console.WriteLine("Behavior: {0}", behavior.ToString());
            }
            sh.Open();
            using (WebChannelFactory <IService> wcf = new WebChannelFactory <IService>(new Uri("http://localhost:8000/web")))
            {
                IService channel = wcf.CreateChannel();
                string   s;

                Console.WriteLine("Calling EchoWithGet by HTTP GET: ");
                s = channel.EchoWithGet("Hello, world");
                Console.WriteLine("   Output: {0}", s);

                Console.WriteLine("");
                Console.WriteLine("This can also be accomplished by navigating to");
                Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!");
                Console.WriteLine("in a web browser while this sample is running.");

                Console.WriteLine("");

                Console.WriteLine("Calling EchoWithPost by HTTP POST: ");
                s = channel.EchoWithPost("Hello, world");
                Console.WriteLine("   Output: {0}", s);
                Console.WriteLine();
            }
            using (ChannelFactory <IService> wcf = new ChannelFactory <IService>(new BasicHttpBinding(), "http://localhost:8000/Soap"))
            {
                IService channel = wcf.CreateChannel();
                string   s;

                Console.WriteLine("Calling EchoWithGet on SOAP endpoint: ");
                s = channel.EchoWithGet("Hello, world");
                Console.WriteLine("   Output: {0}", s);

                Console.WriteLine("");

                Console.WriteLine("Calling EchoWithPost on SOAP endpoint: ");
                s = channel.EchoWithPost("Hello, world");
                Console.WriteLine("   Output: {0}", s);
                Console.WriteLine();
                Console.ReadLine();
            }
            sh.Close();
        }
Beispiel #38
0
        static void Main()
        {
            Uri baseAddress = new Uri("http://localhost:8000/");

            using (WebServiceHost host = new WebServiceHost(typeof(ServerSideProfileService), baseAddress))
            {
                // Open the service host, service is now listening
                host.Open();

                Console.WriteLine("Service listening at {0}.", baseAddress);
                Console.WriteLine("To view its JSON output, point your web browser to {0}GetMemberProfile.", baseAddress);
                Console.WriteLine();


                using (WebChannelFactory <IClientSideProfileService> cf = new WebChannelFactory <IClientSideProfileService>(baseAddress))
                {
                    // Create client side proxy
                    IClientSideProfileService channel = cf.CreateChannel();

                    // Make a request to the service and get the Json response
                    XmlDictionaryReader reader = channel.GetMemberProfile().GetReaderAtBodyContents();

                    // Go through the Json as though it's a dictionary. There is no need to map it to a CLR type.
                    JsonObject json = new JsonObject(reader);


                    string name         = json["root"]["personal"]["name"];
                    int    age          = json["root"]["personal"]["age"];
                    double height       = json["root"]["personal"]["height"];
                    bool   isSingle     = json["root"]["personal"]["isSingle"];
                    int[]  luckyNumbers =
                    {
                        json["root"]["personal"]["luckyNumbers"][0],
                        json["root"]["personal"]["luckyNumbers"][1],
                        json["root"]["personal"]["luckyNumbers"][2]
                    };
                    string[] favoriteBands =
                    {
                        json["root"]["favoriteBands"][0],
                        json["root"]["favoriteBands"][1]
                    };

                    Console.WriteLine("This is {0}'s page. I am {1} years old and I am {2} meters tall.",
                                      name, age, height);
                    Console.WriteLine("I am {0}single.", (isSingle) ? "" : "not ");
                    Console.WriteLine("My lucky numbers are {0}, {1}, and {2}.",
                                      luckyNumbers[0], luckyNumbers[1], luckyNumbers[2]);
                    Console.WriteLine("My favorite bands are {0} and {1}.",
                                      favoriteBands[0], favoriteBands[1]);
                }

                Console.WriteLine();
                Console.WriteLine("Press Enter to terminate...");
                Console.ReadLine();
            }
        }
        static void Main(string[] args)
        {
            ServiceHost sh = new ServiceHost(typeof(Service),new Uri("http://localhost:8000/"));
            sh.AddServiceEndpoint(typeof(IService),new BasicHttpBinding(),"Soap");
            ServiceEndpoint endpoint = sh.AddServiceEndpoint(typeof(IService),new WebHttpBinding(),"Web");

            endpoint.Behaviors.Add(new WebHttpBehavior());

            //endpoint.EndpointBehaviors.Add(new WebHttpBehavior());

            foreach (IEndpointBehavior behavior in endpoint.Behaviors)
            {
                Console.WriteLine("Behavior: {0}", behavior.ToString());
            }
            sh.Open();
            using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8000/web")))
            {

                IService channel = wcf.CreateChannel();
                string s;

                Console.WriteLine("Calling EchoWithGet by HTTP GET: ");
                s = channel.EchoWithGet("Hello, world");
                Console.WriteLine("   Output: {0}", s);

                Console.WriteLine("");
                Console.WriteLine("This can also be accomplished by navigating to");
                Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!");
                Console.WriteLine("in a web browser while this sample is running.");

                Console.WriteLine("");

                Console.WriteLine("Calling EchoWithPost by HTTP POST: ");
                s = channel.EchoWithPost("Hello, world");
                Console.WriteLine("   Output: {0}", s);
                Console.WriteLine();
            }
            using (ChannelFactory<IService> wcf = new ChannelFactory<IService>(new BasicHttpBinding(), "http://localhost:8000/Soap"))
            {
                IService channel = wcf.CreateChannel();
                string s;

                Console.WriteLine("Calling EchoWithGet on SOAP endpoint: ");
                s = channel.EchoWithGet("Hello, world");
                Console.WriteLine("   Output: {0}", s);

                Console.WriteLine("");

                Console.WriteLine("Calling EchoWithPost on SOAP endpoint: ");
                s = channel.EchoWithPost("Hello, world");
                Console.WriteLine("   Output: {0}", s);
                Console.WriteLine();
                Console.ReadLine();
            }
            sh.Close();
        }
Beispiel #40
0
        public LoginForm()
        {
            InitializeComponent();

            WebChannelFactory <ICloudStoreService> factory = new WebChannelFactory <ICloudStoreService>(new Uri("http://localhost:56082/MyCloudStore/CloudStoreService.svc"));

            proxy = factory.CreateChannel();

            userController = new UserController(proxy, this);
        }
Beispiel #41
0
        public static IServiceManagement CreateServiceManagementChannel(string endpointConfigurationName, Uri remoteUri, X509Certificate2 cert)
        {
            WebChannelFactory <IServiceManagement> webChannelFactory = new WebChannelFactory <IServiceManagement>(endpointConfigurationName, remoteUri);

            webChannelFactory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector());
            webChannelFactory.Credentials.ClientCertificate.Certificate = cert;
            IServiceManagement serviceManagement = webChannelFactory.CreateChannel();

            return(serviceManagement);
        }
        public void RejectTwoParametersWhenNotWrapped()
        {
            var factory = new WebChannelFactory <IBogusService1> (new WebHttpBinding(), new Uri("http://localhost:37564"));

#if MOBILE
            factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
#endif

            Assert.Throws <InvalidOperationException> (() => factory.CreateChannel());
        }
Beispiel #43
0
        private static void CallRestService()
        {
            //Connect to api/RestService

            Uri baseAddress = new Uri("http://localhost:58788/api/RestService");
            //WebChannelFactory  WebHttpBehavior,  WebHttpBinding
            WebChannelFactory<IRestService> cf = new WebChannelFactory<IRestService>(baseAddress);
            IRestService service = cf.CreateChannel();
            Person person = service.GetPerson("1");
        }
Beispiel #44
0
        public static IServiceManagement CreateServiceManagementChannel(Type channelType, X509Certificate2 cert)
        {
            WebChannelFactory <IServiceManagement> webChannelFactory = new WebChannelFactory <IServiceManagement>(channelType);

            webChannelFactory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector());
            webChannelFactory.Credentials.ClientCertificate.Certificate = cert;
            IServiceManagement serviceManagement = webChannelFactory.CreateChannel();

            return(serviceManagement);
        }
Beispiel #45
0
 public static ISaaSService GetSaaSService()
 {
     try {
         Uri address = new Uri (SaaSService);
         var factory = new WebChannelFactory<ISaaSService> (new WebHttpBinding { AllowCookies = true }, address);
         return factory.CreateChannel ();
     } catch (Exception ex) {
         logger.Error (ex, "Ошибка создания подключения к SaaS сервису");
         return null;
     }
 }
Beispiel #46
0
        static void Main()
        {
            Uri baseAddress = new Uri("http://localhost:8000/");

            using (WebServiceHost host = new WebServiceHost(typeof(ServerSideProfileService), baseAddress))
            {
                // Open the service host, service is now listening
                host.Open();

                Console.WriteLine("Service listening at {0}.", baseAddress);
                Console.WriteLine("To view its JSON output, point your web browser to {0}GetMemberProfile.", baseAddress);
                Console.WriteLine();


                using (WebChannelFactory<IClientSideProfileService> cf = new WebChannelFactory<IClientSideProfileService>(baseAddress))
                {
                    // Create client side proxy
                    IClientSideProfileService channel = cf.CreateChannel();

                    // Make a request to the service and get the Json response
                    XmlDictionaryReader reader = channel.GetMemberProfile().GetReaderAtBodyContents();

                    // Go through the Json as though it's a dictionary. There is no need to map it to a CLR type.
                    JsonObject json = new JsonObject(reader);


                    string name = json["root"]["personal"]["name"];
                    int age = json["root"]["personal"]["age"];
                    double height = json["root"]["personal"]["height"];
                    bool isSingle = json["root"]["personal"]["isSingle"];
                    int[] luckyNumbers = {
                                             json["root"]["personal"]["luckyNumbers"][0],
                                             json["root"]["personal"]["luckyNumbers"][1],
                                             json["root"]["personal"]["luckyNumbers"][2] 
                                         };
                    string[] favoriteBands = {
                                                 json["root"]["favoriteBands"][0],
                                                 json["root"]["favoriteBands"][1]
                                             };

                    Console.WriteLine("This is {0}'s page. I am {1} years old and I am {2} meters tall.", 
                        name, age, height);
                    Console.WriteLine("I am {0}single.",(isSingle) ? "" : "not ");
                    Console.WriteLine("My lucky numbers are {0}, {1}, and {2}.",
                        luckyNumbers[0], luckyNumbers[1], luckyNumbers[2]);
                    Console.WriteLine("My favorite bands are {0} and {1}.", 
                        favoriteBands[0], favoriteBands[1]);
                }

                Console.WriteLine();
                Console.WriteLine("Press Enter to terminate...");
                Console.ReadLine();
            }
        }
        static void Main(string[] args)
        {
            var serviceFactory = new WebChannelFactory<IRetailer>("RetailService");
            var retailService = serviceFactory.CreateChannel();

            var findResults = retailService.FindItems(ItemCategory.Toys, "minecraft lego set");

            foreach (var item in findResults) {
                Console.WriteLine(item.Title);
            }
        }
        public static IServiceManagement CreateServiceManagementChannel(Uri remoteUri, X509Certificate2 cert)
        {
            WebChannelFactory <IServiceManagement> factory = new WebChannelFactory <IServiceManagement>(remoteUri);

            factory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector());
            factory.Credentials.ClientCertificate.Certificate = cert;

            var channel = factory.CreateChannel();

            return(channel);
        }
        public static T GetRestProxy <T>(string url) where T : class
        {
            var binding = new BasicHttpBinding();

            binding.SendTimeout    = TimeSpan.FromSeconds(15);
            binding.ReceiveTimeout = TimeSpan.FromDays(14);

            var factory = new WebChannelFactory <T>(new Uri(url));

            return(factory.CreateChannel());
        }
Beispiel #50
0
        public AddRequestResponse AddRequest(string sessionId, string authenticationId)
        {
            using (new ApplicationContextScope(new ApplicationContext()))
            {
                ApplicationContext.Current.Items["SessionId"] = sessionId;
                try
                {
                    var sessionChannelFactory =
                        new WebChannelFactory<ISessionServiceRest>(Configuration.SessionServiceConfigurationName);
                    ISessionServiceRest sessionChannel = sessionChannelFactory.CreateChannel();
                    SessionDataResponse sessionDataResponse = null;
                    if (sessionChannel is IContextChannel)
                        using (new OperationContextScope(sessionChannel as IContextChannel))
                        {
                            WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "GetSessionData");
                            sessionDataResponse = sessionChannel.GetSessionData(authenticationId, sessionId);
                        }

                    if (sessionDataResponse != null && sessionDataResponse.SessionData != null)
                    {
                        var loginChannelFactory =
                            new WebChannelFactory<ILoginServiceRest>(Configuration.LoginServiceConfigurationName);
                        ILoginServiceRest loginChannel = loginChannelFactory.CreateChannel();

                        if (loginChannel is IContextChannel)
                            using (new OperationContextScope(loginChannel as IContextChannel))
                            {
                                WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "GetAccount");
                                GetAccountResponse account = loginChannel.GetAccount(sessionId, authenticationId);
                                if (account != null && account.UserAccount != null)
                                    sessionDataResponse.SessionData.Request.AccountId = account.UserAccount.AccountId;
                            }

                        var channelFactory =
                            new WebChannelFactory<ITravelServiceRest>(Configuration.TravelServiceConfigurationName);
                        ITravelServiceRest channel = channelFactory.CreateChannel();

                        if (channel is IContextChannel)
                            using (new OperationContextScope(channel as IContextChannel))
                            {
                                WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "AddRequest");
                                return channel.AddRequest(sessionId,
                                                          sessionDataResponse.SessionData.Request);
                            }
                    }
                }
                catch (Exception exception)
                {
                    Logger.LogException(exception, Source, "AddRequest", Severity.Major);
                }
            }
            return null;
        }
Beispiel #51
0
        public static T CreateServiceManagementChannel <T>(string endpointConfigurationName, Uri remoteUri, X509Certificate2 cert)
            where T : class
        {
            WebChannelFactory <T> factory = new WebChannelFactory <T>(endpointConfigurationName, remoteUri);

            factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
            factory.Credentials.ClientCertificate.Certificate = cert;

            var channel = factory.CreateChannel();

            return(channel);
        }
Beispiel #52
0
        public static T CreateServiceManagementChannel <T>(Type channelType, X509Certificate2 cert)
            where T : class
        {
            WebChannelFactory <T> factory = new WebChannelFactory <T>(channelType);

            factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
            factory.Credentials.ClientCertificate.Certificate = cert;

            var channel = factory.CreateChannel();

            return(channel);
        }
Beispiel #53
0
 public static IServiceManagement Get(X509Certificate2 authCert, out ClientOutputMessageInspector messageInspector)
 {
     messageInspector = new ClientOutputMessageInspector();
     WebChannelFactory<IServiceManagement> factory = new WebChannelFactory<IServiceManagement>
         (
             ConfigurationConstants.WebHttpBinding(0),
             new Uri(Utils.ServiceManagementEndpoint)
         );
     factory.Endpoint.Behaviors.Add(messageInspector);
     factory.Credentials.ClientCertificate.Certificate = authCert;
     return factory.CreateChannel();
 }
Beispiel #54
0
        /// <summary>
        /// Perform a ITodoApi AddTodos request.
        /// </summary>
        private void AddTodos(string name, DateTime expirationDate)
        {
            using (var client = new WebChannelFactory<ITodoApi>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                client.Open();
                var channel = client.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    channel.CreateTodo(new TodoType() { Name = name, ExpirationDate = expirationDate });
                }
            }
        }
Beispiel #55
0
        public void CreateComplexObject()
        {
            using (var client = new WebChannelFactory<IDataTest>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                client.Open();
                var channel = client.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    channel.CreateComplexObject(GetComplexObject());
                    ValidateHttpStatusResponse(HttpStatusCode.OK);
                }
            }
        }
Beispiel #56
0
        public static IGraphDSREST_Service ConnectToAdministrationServiceHost(String ServiceURL)
        {
            var _WebHttpBinding = new WebHttpBinding { ReceiveTimeout = TimeSpan.MaxValue };

            //binding.PortSharingEnabled = false;
            //binding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue;
            //binding.Security.Mode = SecurityMode.TransportWithMessageCredential;

            // WebChannelFactory! to fix "Manual addressing is enabled on this factory" error
            var _WebChannelFactory = new WebChannelFactory<IGraphDSREST_Service>(_WebHttpBinding, new Uri(ServiceURL));
            //factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByIssuerName, "SONES GmbH - Mail CA");

            return _WebChannelFactory.CreateChannel(); //  (new EndpointAddress(ServiceURL));
        }
Beispiel #57
0
        public string GetPostData(string authenticationId, string sessionId, Address contactAddress)
        {
            ISessionService sessionService = new SessionService();

            var sessionDataResponse = sessionService.GetSessionData(authenticationId, sessionId);
            if (sessionDataResponse == null || string.IsNullOrEmpty(sessionDataResponse.ErrorMessage) == false || sessionDataResponse.SessionData == null)
                return string.Empty;

            var loginService = new LoginService();
            GetAccountResponse getAccountResponse = loginService.GetAccount(sessionId, authenticationId);
            if (getAccountResponse == null || getAccountResponse.UserAccount == null)
                return string.Empty;

            var userAccount = getAccountResponse.UserAccount;

            using (new ApplicationContextScope(new ApplicationContext()))
            {
                ApplicationContext.Current.Items["SessionId"] = sessionId;
                try
                {
                    var channelFactory =
                        new WebChannelFactory<IPaymentServiceRest>(Configuration.PaymentServiceConfigurationName);
                    IPaymentServiceRest channel = channelFactory.CreateChannel();

                    if (channel is IContextChannel)
                        using (new OperationContextScope(channel as IContextChannel))
                        {
                            var referenceNumber = Guid.NewGuid().ToString().Substring(10);
                            var voucherCode = string.Empty;
                            if (sessionDataResponse.SessionData.PaymentTransaction != null)
                            {
                                referenceNumber =
                                    sessionDataResponse.SessionData.PaymentTransaction.InternalReferenceNumber;
                            }
                            voucherCode = sessionDataResponse.SessionData.VoucherCode;

                            WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MethodName", "GetPostData");
                            return channel.GetPostData(referenceNumber,
                                                       sessionDataResponse.SessionData.ToPayAmount.ToString(),
                                                       "Air", sessionId, userAccount, contactAddress, voucherCode);
                        }
                }
                catch (Exception exception)
                {
                    Logger.LogException(exception, Source, "GetPostData", Severity.Critical);
                }
            }
            return null;
        }
 static void Main(string[] args)
 {
     #region web http service
     using (ChannelFactory<IRestService> cf = new ChannelFactory<IRestService>(new WebHttpBinding(), "http://localhost:8080/"))
     {
         cf.Endpoint.EndpointBehaviors.Add(new WebHttpBehavior());
         cf.Endpoint.EndpointBehaviors.Add(new CustomEndpointBehavior());
         IRestService channel = cf.CreateChannel();
         string s;
         Console.WriteLine("call WithGet");
         s = channel.WithGet("hello get");
         Console.WriteLine(s);
         Console.WriteLine("call WithPost");
         s = channel.WithPost("hello post");
         Console.WriteLine(s);
         Student student = new Student { FirstName = "Tom", LastName = "Jim" };
         s = channel.CreateStudent(student);
         Console.WriteLine(s);
         Console.ReadLine();
     }
     #endregion
     #region web http service and soap service
     using (WebChannelFactory<IRestService> wcf = new WebChannelFactory<IRestService>(new Uri("http://localhost:8090/web/")))
     {
         IRestService channel = wcf.CreateChannel();
         string s;
         Console.WriteLine("web http service call WithGet");
         s = channel.WithGet("web http service hello get");
         Console.WriteLine(s);
         Console.WriteLine("web http service call WithPost");
         s = channel.WithPost("web http service hello post");
         Console.WriteLine(s);
         Console.ReadLine();
     }
     using (ChannelFactory<IRestService> wcf = new ChannelFactory<IRestService>(new BasicHttpBinding(), "http://localhost:8090/soap/"))
     {
         IRestService channel = wcf.CreateChannel();
         string s;
         Console.WriteLine("soap service call WithGet");
         s = channel.WithGet("soap service hello get");
         Console.WriteLine(s);
         Console.WriteLine("soap service call WithPost");
         s = channel.WithPost("soap service hello post");
         Console.WriteLine(s);
         Console.ReadLine();
     }
     #endregion
 }
Beispiel #59
0
        public void GetTodos()
        {
            using (var client = new WebChannelFactory<ITodoApi>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                client.Open();
                var channel = client.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    var todos = channel.GetTodos();
                    ValidateHttpStatusResponse(HttpStatusCode.OK);

                    Assert.AreEqual(3, todos.Todo.Length);
                }
            }
        }
Beispiel #60
0
        public void CreateInts()
        {
            using (var server = new WebServiceHost(new DataService(), new Uri(_hostAddress)))
            using (var client = new WebChannelFactory<IDataTest>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                server.Open();
                client.Open();
                var channel = client.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    channel.CreateInts( new []{24,42});
                    ValidateHttpStatusResponse(HttpStatusCode.OK);
                }
            }
        }