Example #1
0
        public void GetTodosFiltered()
        {
            using (var server = new WebServiceHost(new TodoService(), new Uri(_hostAddress)))
            using (var client = new WebChannelFactory<ITodoApi>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                server.Open();
                client.Open();
                var channel = client.CreateChannel();

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

                    Assert.AreEqual(1, todos.Todo.Length);
                }

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

                    Assert.AreEqual(2, todos.Todo.Length);
                }
            }
        }
Example #2
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();
        }
 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();
 }
        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"
                       };
        }
Example #5
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 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();
 }
Example #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();
            }
        }
Example #8
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;
        }
        public static IGithubServiceManagement CreateServiceManagementChannel(Uri remoteUri, string username, string password)
        {
            WebChannelFactory<IGithubServiceManagement> factory;
            if (_factories.ContainsKey(remoteUri.ToString()))
            {
                factory = _factories[remoteUri.ToString()];
            }
            else
            {
                factory = new WebChannelFactory<IGithubServiceManagement>(remoteUri);
                factory.Endpoint.Behaviors.Add(new GithubAutHeaderInserter() {Username = username, Password = password});

                WebHttpBinding wb = factory.Endpoint.Binding as WebHttpBinding;
                wb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                wb.Security.Mode = WebHttpSecurityMode.Transport;
                wb.MaxReceivedMessageSize = 10000000;

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

                _factories[remoteUri.ToString()] = factory;
            }

            return factory.CreateChannel();
        }
Example #10
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;
        }
Example #11
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;
                }
            }
        }
Example #12
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();
        }
Example #13
0
 public Blip(string user, string password)
 {
     this.user = user;
     this.password = password;
     channelFactory = new WebChannelFactory<IBlipApi>(GetBinding(), new Uri(BlipApiUrl));
     api = channelFactory.CreateChannel();
 }
Example #14
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;
        }
        /// <summary>
        /// Creates a new instance of the <see cref="WorldGeocoder"/> class for the specified
        /// service configuration.
        /// </summary>
        /// <param name="serviceInfo">The instance of the geocoding service configuration
        /// specifying World geocoder service to create geocoder for.</param>
        /// <param name="exceptionHandler">Exception handler.</param>
        /// <returns>A new instance of the <see cref="WorldGeocoder"/> class.</returns>
        /// <exception cref="System.ArgumentNullException"><paramref name="serviceInfo"/> is a null
        /// reference.</exception>
        public static GeocoderBase CreateWorldGeocoder(GeocodingServiceInfo serviceInfo,
            IServiceExceptionHandler exceptionHandler)
        {
            CodeContract.RequiresNotNull("serviceInfo", serviceInfo);

            // Create binding for the geocoder REST service.
            var webBinding = ServiceHelper.CreateWebHttpBinding("WorldGeocoder");
            var binding = new CustomBinding(webBinding);
            var messageEncodingElement = binding.Elements.Find<WebMessageEncodingBindingElement>();
            messageEncodingElement.ContentTypeMapper = new ArcGisWebContentTypeMapper();

            // Create endpoint for the geocoder REST service.
            var contract = ContractDescription.GetContract(typeof(IGeocodingService));
            var serviceAddress = new EndpointAddress(serviceInfo.RestUrl);
            var endpoint = new WebHttpEndpoint(contract, serviceAddress);
            endpoint.Binding = binding;

            // Replace default endpoint behavior with a customized one.
            endpoint.Behaviors.Remove<WebHttpBehavior>();
            endpoint.Behaviors.Add(new GeocodingServiceWebHttpBehavior());

            // Create the geocoder instance.
            var channelFactory = new WebChannelFactory<IGeocodingService>(endpoint);
            var client = new GeocodingServiceClient(channelFactory, serviceInfo, exceptionHandler);

            return new WorldGeocoder(serviceInfo, client);
        }
Example #16
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;
		}
Example #17
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;
		}
Example #18
0
		public void CanCallRestfulHostedService()
		{
			using (var factory = new WebChannelFactory<IAmUsingWindsor>(
				new Uri("http://localhost:27197/UsingWindsorRest.svc")))
			{
				Assert.AreEqual(126, factory.CreateChannel().MultiplyValueFromWindsorConfig(3));
			}
		}
        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;
        }
Example #20
0
        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();
        }
Example #21
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");
        }
Example #22
0
        public static IServiceManagement CreateServiceManagementChannel(Type channelType, X509Certificate2 cert)
        {
            WebChannelFactory <IServiceManagement> factory = new WebChannelFactory <IServiceManagement>(channelType);

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

            var channel = factory.CreateChannel();

            return(channel);
        }
        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);
            }
        }
Example #24
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();
            }
        }
Example #25
0
        static void ThreadWorks(UpdaterFlags flags)
        {
            string checkVersion = String.Empty, checkResult = String.Empty;
            bool   showAnyway     = FlagsHelper.IsSet(flags, UpdaterFlags.ShowAnyway);
            bool   updateRequired = FlagsHelper.IsSet(flags, UpdaterFlags.UpdateRequired);
            bool   isMainThread   = !FlagsHelper.IsSet(flags, UpdaterFlags.StartInThread);
            Uri    address        = new Uri("http://saas.qsolution.ru:2048/Updater");

            try {
                logger.Info("Получаем данные от сервера");
                string parameters = String.Format("product.{0};edition.{1};serial.{2};major.{3};minor.{4};build.{5};revision.{6}",
                                                  MainSupport.ProjectVerion.Product,
                                                  MainSupport.ProjectVerion.Edition,
                                                  MainSupport.BaseParameters.SerialNumber,
                                                  MainSupport.ProjectVerion.Version.Major,
                                                  MainSupport.ProjectVerion.Version.Minor,
                                                  MainSupport.ProjectVerion.Version.Build,
                                                  MainSupport.ProjectVerion.Version.Revision);
                IUpdateService service = new WebChannelFactory <IUpdateService> (new WebHttpBinding {
                    AllowCookies = true
                }, address)
                                         .CreateChannel();
                updateResult = service.checkForUpdate(parameters);
                if (MachineConfig.ConfigSource.Configs ["Updater"] != null)
                {
                    checkVersion = MachineConfig.ConfigSource.Configs ["Updater"].Get("NewVersion", String.Empty);
                    checkResult  = MachineConfig.ConfigSource.Configs ["Updater"].Get("Check", String.Empty);
                }
                if (showAnyway || (updateResult.HasUpdate &&
                                   (checkResult == "True" || checkResult == String.Empty || checkVersion != updateResult.NewVersion)))
                {
                    if (isMainThread)
                    {
                        ShowDialog(updateRequired);
                    }
                    else
                    {
                        Application.Invoke(delegate {
                            ShowDialog(updateRequired);
                        });
                    }
                }
            } catch (Exception ex) {
                logger.Error(ex, "Ошибка доступа к серверу обновления.");
                if (showAnyway)
                {
                    ShowErrorDialog("Не удалось подключиться к серверу обновлений.\nПожалуйста, повторите попытку позже.");
                }
                if (updateRequired)
                {
                    Environment.Exit(1);
                }
            }
        }
        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());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CatalystRuntime"/> class.
 /// </summary>
 /// <param name="adapter">The catalyst adapter.</param>
 /// <param name="administrator">The administrator.</param>
 /// <param name="instanceDescriptor">The instance descriptor.</param>
 public CatalystRuntime(Catalyst adapter, CatalystAdministrator administrator, InstanceDescriptor instanceDescriptor)
 {
     _adapter            = adapter;
     _administrator      = administrator;
     _webChannelFactory  = adapter.WebChannelFactory;
     _instanceDescriptor = instanceDescriptor;
     _dataPublisher      = instanceDescriptor.DataPublicationEndpoints
                           .Where(endpoint => endpoint != null)
                           .Select(endpoint => adapter.DataPublisherFactory.CreatePublisher(endpoint))
                           .FirstOrDefault(publisherFactory => publisherFactory != null);
 }
        public static IServiceManagement CreateServiceManagementChannel(string endpointConfigurationName, Uri remoteUri, X509Certificate2 cert)
        {
            WebChannelFactory <IServiceManagement> factory = new WebChannelFactory <IServiceManagement>(endpointConfigurationName, remoteUri);

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

            var channel = factory.CreateChannel();

            return(channel);
        }
Example #29
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;
     }
 }
Example #30
0
        /// <summary>
        /// Initializes a new instance of the UTorrentClient class.
        /// </summary>
        /// <param name="webApiUri">The uri of the uTorrent web api</param>
        /// <param name="username">The username to use to log into uTorrent</param>
        /// <param name="password">The password to use</param>
        /// <param name="maxIncomingMessageSizeInBytes">The size of message to accept from uTorrent web</param>
        public UTorrentClient(Uri webApiUri, string username, string password, long maxIncomingMessageSizeInBytes = 524288)
        {
            CustomBinding clientCustomBinding = new CustomBinding(
                new WebMessageEncodingBindingElement() { ContentTypeMapper = new JsonContentTypeMapper() },
                new HttpTransportBindingElement { UseDefaultWebProxy = true, ManualAddressing = true, AuthenticationScheme = AuthenticationSchemes.Basic, Realm = "uTorrent", AllowCookies = true, MaxReceivedMessageSize = maxIncomingMessageSizeInBytes });

            this.channelFactory = new WebChannelFactory<IUTorrentProxy>(clientCustomBinding, webApiUri);
            this.channelFactory.Credentials.UserName.UserName = username;
            this.channelFactory.Credentials.UserName.Password = password;
            this.proxy = this.channelFactory.CreateChannel();
            this.Torrents = new TorrentCollection(this.proxy);
        }
        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);
            }
        }
Example #32
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();
 }
Example #33
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;
        }
Example #34
0
        public AnmatGenerationServiceClient(AnmatConfiguration configuration)
        {
            this.configuration = configuration;

            var binding = new WebHttpBinding();

            binding.SendTimeout = TimeSpan.FromMinutes(10);

            this.channelFactory = new WebChannelFactory <IAnmatDataService> (binding, new Uri(this.configuration.AnmatDataServiceUrl));

            this.channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
        }
Example #35
0
        public static T CreateServiceManagementChannel <T>(string endpointConfigurationName, X509Certificate2 cert)
            where T : class
        {
            WebChannelFactory <T> factory = new WebChannelFactory <T>(endpointConfigurationName);

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

            var channel = factory.CreateChannel();

            return(channel);
        }
Example #36
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);
     }
 }
Example #37
0
        /// <summary>
        /// Perform a ITodoApi GetTodos request.
        /// </summary>
        private TodosType GetTodos()
        {
            using (var client = new WebChannelFactory <ITodoApi>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                client.Open();
                var channel = client.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    return(channel.GetTodos());
                }
            }
        }
Example #38
0
        public WebClientChannelFactoryWithAuthorization(string listenAddress, string authorizationHeaderValue)
        {
            var binding = new WebHttpBinding {
                MaxReceivedMessageSize = Int32.MaxValue
            };

            _webChannelFactory = new WebChannelFactory <T>(binding, new Uri(listenAddress));
            if (!string.IsNullOrWhiteSpace(authorizationHeaderValue))
            {
                _webChannelFactory.Endpoint.Behaviors.Add(
                    new HttpAuthorizationInserterEndpointBehavior(authorizationHeaderValue));
            }
        }
Example #39
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());
        }
Example #40
0
		public void Dispose()
		{
			lock (_sync)
			{
				if (_factory == null)
				{
					return;
				}

				_factory.Close();
				_factory = null;
			}
		}
Example #41
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 });
                }
            }
        }
Example #42
0
 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
 }
Example #43
0
        /// <summary>
        /// Cleans up this instance and closes the underlying
        /// channel and channel factory.
        /// </summary>
        public void Dispose()
        {
            if (this.proxy != null)
            {
                ((IClientChannel)this.proxy).Close();
                this.proxy = null;
            }

            if (this.channelFactory != null)
            {
                this.channelFactory.Close();
                this.channelFactory = null;
            }
        }
Example #44
0
        public void CreateComplexObjects()
        {
            using (var client = new WebChannelFactory <IDataTest>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                client.Open();
                var channel = client.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    channel.CreateComplexObjects(GetComplexObjects());
                    ValidateHttpStatusResponse(HttpStatusCode.OK);
                }
            }
        }
Example #45
0
	// It is not working with mono!
	public static void Main ()
	{
		string url = "http://localhost:8080";
		//WebHttpBinding b = new WebHttpBinding ();
		CustomBinding b = new CustomBinding (
			new WebMessageEncodingBindingElement (),
			new InterceptorBindingElement (),
			new HttpTransportBindingElement () { ManualAddressing = true });
		var f = new WebChannelFactory<IMyService> (b, new Uri (url));
		// this causes NRE (even if the endpointaddress is specified at CreateChannel()).
		// var f = new WebChannelFactory<IMyService> (b); 
		IMyService s = f.CreateChannel ();
		Console.WriteLine (s.Greet ("hogehoge"));
	}
Example #46
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));
        }
Example #47
0
        static void Main(string[] args)
        {
            WebChannelFactory <IEvalService> cf = new WebChannelFactory <IEvalService>(new Uri("http://localhost:8089/evalservice"));

            IEvalService client = cf.CreateChannel();



            string input = "";

            while (input != "exit")
            {
                Console.Clear();
                Console.WriteLine("exit: quit app");
                Console.WriteLine("submit: submit eval");
                Console.WriteLine("get: get eval");
                Console.WriteLine("list: list evals");
                Console.WriteLine("remove: remove eval");
                Console.WriteLine();
                Console.Write("> ");
                input = Console.ReadLine();


                switch (input.ToLower())
                {
                case "exit":
                    return;

                case "submit":
                    SubmitEval(client);
                    break;

                case "get":
                    GetEval(client);
                    break;

                case "list":
                    ListEval(client);
                    break;

                case "remove":
                    RemoveEval(client);
                    break;

                default:
                    break;
                }
            }
        }
Example #48
0
 public IReadServiceWeb GetReadServiceWeb()
 {
     try
     {
         WebHttpBinding objWebHttpBinding       = GetWebHttpBinding();
         WebChannelFactory <IReadServiceWeb> cf = new WebChannelFactory <IReadServiceWeb>(objWebHttpBinding, new Uri(string.Format(URI_DRIVERWeb2, IP_ADDRESS, PORTWeb, "Driver")));
         IReadServiceWeb client = cf.CreateChannel();
         return(client);
     }
     catch (Exception ex)
     {
         EventscadaException?.Invoke(GetType().Name, ex.Message);
     }
     return(null);
 }
Example #49
0
        } // OnStart()

        //---------------------------------------------------------------------------------------------
        protected override void OnStop()
        {
            try
            {
                Logger.Log("Closing service");
            }
            finally
            {
                // Free the resources
                baseAddress = null;
                host.Close();
                host = null;
                cf   = null;
            }
        }
Example #50
0
        public static T CreateServiceManagementChannel <T>(Binding binding, Uri remoteUri, params IEndpointBehavior[] behaviors)
            where T : class
        {
            WebChannelFactory <T> factory = new WebChannelFactory <T>(binding, remoteUri);

            factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
            foreach (IEndpointBehavior behavior in behaviors)
            {
                factory.Endpoint.Behaviors.Add(behavior);
            }

            var channel = factory.CreateChannel();

            return(channel);
        }
Example #51
0
        public static T CreateChannel <T>(Binding binding, Uri remoteUri, X509Certificate2 cert, params IEndpointBehavior[] behaviors)
            where T : class
        {
            WebChannelFactory <T> factory = new WebChannelFactory <T>(binding, remoteUri);

            factory.Credentials.ClientCertificate.Certificate = cert;
            foreach (IEndpointBehavior behavior in behaviors)
            {
                factory.Endpoint.Behaviors.Add(behavior);
            }

            var channel = factory.CreateChannel();

            return(channel);
        }
Example #52
0
        static void Main(string[] args)
        {
            Console.WriteLine("WCF REST Service Client Application");
            WebChannelFactory <IEmployeeData> factory = new WebChannelFactory <IEmployeeData>(new Uri("http://localhost:8765/WcfRestService"));
            var client   = factory.CreateChannel();
            var response = string.Empty;

            Console.WriteLine("Enter a command (x to exit): ");
            response = Console.ReadLine();
            while (response != "x")
            {
                switch (response)
                {
                case "submit":
                    var eval = new Employee();
                    Console.WriteLine("Enter your name:");
                    eval.Submitter = Console.ReadLine();
                    Console.WriteLine("Enter your comments:");
                    eval.Comments = Console.ReadLine();
                    client.SubmitEmployee(eval);
                    Console.WriteLine("Employee information submitted");
                    break;

                case "get":
                    Console.WriteLine("Enter submitter name: ");
                    var submitter = Console.ReadLine();
                    var employees = client.GetEmployeesBySubmitter(submitter);
                    employees.ForEach(emp =>
                                      Console.WriteLine("{0} said {1} (Id {2})", emp.Submitter, emp.Comments, emp.Id)
                                      );
                    Console.WriteLine();
                    break;

                case "remove":
                    Console.WriteLine("Enter id of employee to remove: ");
                    var id = Console.ReadLine();
                    client.RemoveEmployee(id);
                    Console.WriteLine("Employee successfully removed");
                    break;

                default:
                    Console.WriteLine("Unsupported command");
                    break;
                }
                Console.WriteLine("Enter a command (x to exit): ");
                response = Console.ReadLine();
            }
        }
Example #53
0
        /// <summary>
        /// Method for performing a WCF call.
        /// </summary>
        private static void sendWcfServiceCall(IAction tracingAction)
        {
            using (var webChannelFactory = new WebChannelFactory <IService>(new Uri(WebServiceBaseAddress)))
            {
                // Hint: Add an instance of TraceServiceCallBehavior to the client's endpoint behaviors
                // If the following line is omitted, no automatic tracing is performed.
                webChannelFactory.Endpoint.EndpointBehaviors.Add(new TraceServiceCallBehavior(tracingAction));

                var channel = webChannelFactory.CreateChannel();


                Console.WriteLine("Calling ServiceMethod by HTTP GET: ");
                var response = channel.ServiceMethod("Hello, world!");
                Console.WriteLine($"   Output: {response}");
            }
        }
Example #54
0
        public void UpdateComplexObjects()
        {
            using (var client = new WebChannelFactory <IDataTest>(new WebHttpBinding(), new Uri(_hostAddress)))
            {
                client.Open();
                var channel = client.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    var input  = GetComplexObjects();
                    var result = channel.UpdateComplexObjects(input);
                    ValidateHttpStatusResponse(HttpStatusCode.OK);
                    MyAssert.AreEqual(input, result);
                }
            }
        }
Example #55
0
        public void CreateSimpleObject()
        {
            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.CreateSimpleObject(GetSimpleObject());
                        ValidateHttpStatusResponse(HttpStatusCode.OK);
                    }
                }
        }
Example #56
0
        /// <summary>
        /// CANNOT WORK
        /// 不能工作
        /// http://blogs.msdn.com/b/carlosfigueira/archive/2012/03/26/mixing-add-service-reference-and-wcf-web-http-a-k-a-rest-endpoint-does-not-work.aspx
        /// </summary>
        static void CallByRef()
        {
            try
            {
                var serviceUrl = "http://localhost:64669/Time.svc";

                using (var factory = new WebChannelFactory <TimeServices.ITime>(new Uri(serviceUrl)))
                {
                    var proxy  = factory.CreateChannel();
                    var result = proxy.GetCurrentTime();

                    Console.WriteLine(result);
                }
            }
            catch { }
        }
Example #57
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
                    });
                }
            }
        }
Example #58
0
        public void Current()
        {
            Assert.IsNull(WebOperationContext.Current, "#1");
            var binding = new WebHttpBinding();
            var address = new EndpointAddress("http://localhost:37564");
            var ch      = (IContextChannel)WebChannelFactory <IHogeService> .CreateChannel(binding, address);

            using (var ocs = new OperationContextScope(ch)) {
                Assert.IsNotNull(WebOperationContext.Current, "#2");
                Assert.IsNotNull(WebOperationContext.Current.OutgoingRequest, "#3");
                Assert.IsNotNull(WebOperationContext.Current.IncomingRequest, "#4");
                Assert.IsNotNull(WebOperationContext.Current.IncomingResponse, "#5");
                Assert.IsNotNull(WebOperationContext.Current.OutgoingResponse, "#6");                  // pointless though.
            }
            ch.Close();
        }
Example #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);
                }
            }
        }
Example #60
0
    public static void Main()
    {
        var ch = new WebChannelFactory <IHogeClient> (
            //new CustomBinding (new WebMessageEncodingBindingElement (), new HttpTransportBindingElement () { ManualAddressing = true }),
            new WebHttpBinding(),
            new Uri("http://localhost:8080"))
                 .CreateChannel();

        //new OperationContextScope ((IContextChannel) ch);
        //WebOperationContext.Current.OutgoingRequest.Method = "GET";
        //OperationContext.Current.OutgoingMessageHeaders.To =
        //	new Uri ("http://localhost:8080/Join?s1=foo");

        Console.WriteLine(ch.Echo("really?"));
        Console.WriteLine(ch.Join("foo", "bar"));
    }