Inheritance: Binding:Binding, IBindingRuntimePreferences
        public TestDataService(string baseUrl, Type serviceType)
        {
            for (var i = 0; i < 100; i++)
            {
                var hostId = Interlocked.Increment(ref _lastHostId);
                this._serviceUri = new Uri(baseUrl + hostId);
                this._host = new DataServiceHost(serviceType, new Uri[] { this._serviceUri });


                var binding = new WebHttpBinding { MaxReceivedMessageSize = Int32.MaxValue };
                _host.AddServiceEndpoint(typeof(System.Data.Services.IRequestHandler), binding, _serviceUri);
                
                //var endpoing = new ServiceEndPoint
                //this._host.Description.Endpoints[0].Binding
                //this._host.AddServiceEndpoint(serviceType, binding, this._serviceUri);
                try
                {
                    this._host.Open();
                    break;
                }
                catch (Exception)
                {
                    this._host.Abort();
                    this._host = null;
                }
            }

            if (this._host == null)
            {
                throw new InvalidOperationException("Could not open a service even after 100 tries.");
            }
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Инициализация...");
            var properties = ConnectionSettings.Default;
            var baseUrl = new Uri(properties.host);

            var contractType = typeof (IRestBridgeContract);
            var binding = new WebHttpBinding(WebHttpSecurityMode.None);
            binding.ContentTypeMapper = new JsonContentTypeMapper();

            var server = new ServiceHost(typeof (CastDriverBridgeEmulatorImpl));
            var endPoint = server.AddServiceEndpoint(contractType, binding, baseUrl);

            var behavior = new WebHttpBehavior();
            behavior.FaultExceptionEnabled = false;
            behavior.HelpEnabled = true;
            behavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
            behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;

            endPoint.Behaviors.Add(behavior);

            Console.WriteLine("Инициализация завершена.");

            Console.WriteLine("Запуск сервера...");
            server.Open();
            Console.WriteLine("Сервер запущен. Адрес сервера: {0}\nДля остановки нажмите Enter.", properties.host);

            Console.ReadLine();
            Console.WriteLine("Остановка сервера...");
            server.Close();
            Console.WriteLine("Сервер остановлен.");
            Console.ReadLine();
        }
Exemplo n.º 3
0
	public static void Main ()
	{
		var url = "http://localhost:8080";
		var host = new MyHostFactory ().CreateServiceHost (typeof (HogeService));
		var binding = new WebHttpBinding ();
		host.AddServiceEndpoint (typeof (IHogeService), binding, url);
		host.Open ();
		//Console.WriteLine ("js:");
		//Console.WriteLine (new WebClient ()
		//	.DownloadString (url + "/js"));
		Console.WriteLine ("jsdebug:");
		Console.WriteLine (new WebClient ()
			.DownloadString (url + "/jsdebug"));
		Console.WriteLine (new WebClient ()
			.DownloadString (url + "/Join?s1=foo&s2=bar"));
		Console.WriteLine (new WebClient ()
			.DownloadString (url + "/ToComplex?real=3&unreal=4"));
		foreach (ChannelDispatcher cd in host.ChannelDispatchers) {
			Console.WriteLine ("BindingName: " + cd.BindingName);
			Console.WriteLine (cd.Listener.Uri);
			foreach (var o in cd.Endpoints [0].DispatchRuntime.Operations)
				Console.WriteLine ("OP: {0} {1}", o.Name, o.Action);
		}
		Console.WriteLine ("Type [CR] to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8000/");
            ServiceHost selfHost = new WebServiceHost(typeof(MonitorService), baseAddress);

            try
            {
                // Step 3 Add a service endpoint.
                var t = new WebHttpBinding();

                selfHost.AddServiceEndpoint(typeof(IMonitorService), t, "test");
                WebHttpBehavior whb = new WebHttpBehavior();

                // Step 4 Enable metadata exchange.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;

                selfHost.Description.Behaviors.Add(smb);

                // Step 5 Start the service.
                selfHost.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

                // Close the ServiceHostBase to shutdown the service.
                selfHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occurred: {0}", ce.Message);
                selfHost.Abort();
            }
        }
Exemplo n.º 5
0
        public static ServiceHost CreateServiceHost()
        {
            /*var uri = new Uri("http://localhost:8686/hello");
            var host = new ServiceHost(typeof(HelloService), uri);

            var binding = new BasicHttpBinding();
            host.AddServiceEndpoint(typeof(IHelloService), binding, uri);

            var metadata = new ServiceMetadataBehavior();
            metadata.HttpGetEnabled = true;
            metadata.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(metadata);

            return host;*/

            var baseAddress = new Uri("http://localhost:8686/blog");

            //			var baseAddress = new UriBuilder(Uri.UriSchemeHttp, Environment.MachineName, -1, "/blogdemo/").Uri;
            var serviceHost = new ServiceHost(typeof(BloggerAPI), baseAddress);

            var epXmlRpc = serviceHost.AddServiceEndpoint(typeof(IBloggerAPI), new WebHttpBinding(WebHttpSecurityMode.None), baseAddress);
            epXmlRpc.Behaviors.Add(new XmlRpcEndpointBehavior());

            var webBinding = new WebHttpBinding(WebHttpSecurityMode.None);
            var epFeed = serviceHost.AddServiceEndpoint(typeof(IFeed), webBinding, new Uri(baseAddress, "./feed"));
            epFeed.Behaviors.Add(new WebHttpBehavior());

            return serviceHost;
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            ItemCounter counter = new ItemCounter();

            using (WebServiceHost host = new WebServiceHost(new StreamingFeedService(counter), new Uri("http://localhost:8000/Service")))
            {
                WebHttpBinding binding = new WebHttpBinding();

                binding.TransferMode = TransferMode.StreamedResponse;
                host.AddServiceEndpoint(typeof(IStreamingFeedService), binding, "Feeds");

                host.Open();

                XmlReader reader = XmlReader.Create("http://localhost:8000/Service/Feeds/StreamedFeed");
                StreamedAtom10FeedFormatter formatter = new StreamedAtom10FeedFormatter(counter);

                Console.WriteLine("Reading stream from server");

                formatter.ReadFrom(reader);
                SyndicationFeed feed = formatter.Feed;

                foreach (SyndicationItem item in feed.Items)
                {
                    //This sample is implemented such that the server will generate an infinite stream of items;
                    //it only stops after the client reads 10 items
                    counter.Increment();
                }

                Console.WriteLine("CLIENT: read total of {0} items", counter.GetCount());
                Console.WriteLine("Press any key to terminate");
                Console.ReadLine();
            }
        }
Exemplo n.º 7
0
        private static void RunProxy()
        {
            //string baseAddress = "http://" + Environment.MachineName + ":8000/Service.svc";
            string baseAddress = "http://localhost:52696/SalesService.svc";

            WebHttpBinding webBinding = new WebHttpBinding
            {
                ContentTypeMapper = new RawContentMapper(),
                MaxReceivedMessageSize = 4194304,
                MaxBufferSize = 4194304,
                SendTimeout = TimeSpan.FromMinutes(4)
            };

            EndpointAddress endpoint = new EndpointAddress(baseAddress + "/json");

            using (SalesService proxy = new SalesService(webBinding, endpoint))
            {
                proxy.Endpoint.Behaviors.Add(new WebHttpJsonNetBehavior());

                try
                {
                    var cons = proxy.GetSalesman(0, 5);
                    Console.WriteLine(cons);
                    Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadLine();
                }
            }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            WebServiceHost webServiceHost = new WebServiceHost(typeof(PartyService.Service));

            WebHttpBinding serviceBinding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
            serviceBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            ServiceEndpoint ep = webServiceHost.AddServiceEndpoint(
                typeof(PartyService.IService),
                serviceBinding,
                "http://localhost:8000/service");
            ep.Behaviors.Add(new PartyService.ProcessorBehaviour());

            WebHttpBinding staticBinding = new WebHttpBinding(WebHttpSecurityMode.None);
            ServiceEndpoint sep = webServiceHost.AddServiceEndpoint(
                typeof(PartyService.IStaticItemService),
                new WebHttpBinding(),
                "http://localhost:8000");

            webServiceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
            webServiceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new PartyService.Validator();
            webServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;

            webServiceHost.Open();
            Console.WriteLine("Service is running - press enter to quit");
            Console.ReadLine();
            webServiceHost.Close();
            Console.WriteLine("Service stopped");
        }
Exemplo n.º 9
0
        public void DifferentWriteEncodingsTest()
        {
            Encoding[] validEncodings = new Encoding[]
            {
                Encoding.UTF8,
                Encoding.Unicode,
                Encoding.BigEndianUnicode,
            };

            string[] charsetValues = new string[] { "utf-8", "utf-16LE", "utf-16BE" };

            for (int i = 0; i < validEncodings.Length; i++)
            {
                Encoding encoding = validEncodings[i];
                WebHttpBinding binding = new WebHttpBinding();
                binding.WriteEncoding = encoding;
                WebHttpBehavior3 behavior = new WebHttpBehavior3();
                string baseAddress = TestService.BaseAddress;

                using (ServiceHost host = new ServiceHost(typeof(TestService), new Uri(baseAddress)))
                {
                    host.AddServiceEndpoint(typeof(ITestService), binding, "").Behaviors.Add(behavior);
                    host.Open();
                    HttpWebRequest request = WebHttpBehavior3Test.CreateRequest("GET", baseAddress + "/EchoGet?a=1", null, null, null);
                    HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
                    Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode);
                    Assert.AreEqual("application/json; charset=" + charsetValues[i], resp.ContentType);
                    Stream respStream = resp.GetResponseStream();
                    string responseBody = new StreamReader(respStream, encoding).ReadToEnd();
                    Assert.AreEqual("{\"a\":\"1\"}", responseBody);
                }
            }
        }
Exemplo n.º 10
0
        public FilesWinService(ILog log, IConfig config, IFirewallService firewallService)
            : base(log, true)
        {
            this.config = config;
            this.firewallService = firewallService;

            Uri baseAddress = config.FilesServiceUri;

            var webHttpBinding = new WebHttpBinding();
            webHttpBinding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
            webHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

            var serviceHost =  new IocServiceHost(typeof(FilesService), baseAddress);
            base.serviceHost = serviceHost;

            ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(typeof(IFilesService), webHttpBinding, baseAddress);
            endpoint.Behaviors.Add(new WebHttpBehavior());
            ServiceCredential filesCredentials = config.FilesCredentials;
            #if DEBUG
            log.Debug("FilesWinService baseAddress: {0} credentials: {1}:{2}",
                baseAddress, filesCredentials.Username, filesCredentials.Password);
            #endif
            serviceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNamePasswordValidator(filesCredentials);
            serviceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
        }
        public void OnShare(object sender, EventArgs e)
        {
            bool putFileNameInUri = this.checkBoxPutFileNameInUrl.Checked;
            int hoursToShare = int.Parse(this.dropDownHoursToShare.SelectedValue);

            var listItem = GetListItem();
            if (listItem == null) return;
            try
            {
                var binding = new WebHttpBinding();
                var endpoint = new EndpointAddress(GetServiceUrl());
                var channelFactory = new ChannelFactory<Services.IAzureSharer>(binding, endpoint);
                channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
                var client = channelFactory.CreateChannel();
                var fileModel = new Services.FileModel()
                                    {
                                        FileName = HttpUtility.UrlEncode(listItem.File.Name),
                                        FileContent = listItem.File.OpenBinary(),
                                        HoursToShare = hoursToShare,
                                        PutFileNameInUrl = putFileNameInUri
                                    };
                var blobToken = client.ShareFile(fileModel);

                ((IClientChannel)client).Close();
                channelFactory.Close();

                this.textBoxGeneratedLink.Text = String.Format("{0}/{1}",GetServiceUrl(),blobToken);
            }
            catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(String.Format("Tried to upload {0} with {1} bytes, got error {2}", listItem.File.Name, listItem.File.OpenBinary().Length, ex.Message));
            }
        }
        /// <summary>
        /// Initializes and hosts all services.
        /// </summary>
        public void Initialize()
        {
            // Host the public web service
            if (_settingWSIsEnabled.Value)
            {
                string address = string.Format("http://localhost:{0}/AlarmWorkflow/AlarmWorkflowService", _settingWSPort.Value);
                Binding binding = new WebHttpBinding()
                {
                    HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.WeakWildcard,
                    MaxReceivedMessageSize = int.MaxValue,
                    ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                };

                HostService(address, binding, typeof(IAlarmWorkflowService), new AlarmWorkflowService(_parent));
            }

            // Host the service used for local-machine communication between service and clients (such as the Windows/Linux UI)
            {
                string address = "net.pipe://localhost/alarmworkflow/service";
                NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport)
                {
                    MaxReceivedMessageSize = int.MaxValue,
                    ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                };

                HostService(address, binding, typeof(IAlarmWorkflowServiceInternal), new AlarmWorkflowServiceInternal(_parent));
            }
        }
Exemplo n.º 13
0
        public void StartService()
        {
            StopService();
            Trace.WriteLine("create ServiceHost(typeof(Service1))");

            if (!__configureService)
                _serviceHost = new ServiceHost(typeof(Service1));
            else
            {
                _serviceHost = new ServiceHost(typeof(Service1), new Uri("http://localhost:8701/Test_wcf_service/"));

                WebHttpBinding webHttpBinding = new WebHttpBinding();
                webHttpBinding.CrossDomainScriptAccessEnabled = true;
                ServiceEndpoint serviceEndpoint = _serviceHost.AddServiceEndpoint(typeof(Service1), webHttpBinding, "service1");
                serviceEndpoint.Behaviors.Add(new WebHttpBehavior());
                //serviceEndpoint.Behaviors.Add(new CorsEnablingBehavior());

                ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();
                serviceMetadataBehavior.HttpGetEnabled = true;
                serviceMetadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                _serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);
            }

            if (__trace)
                TraceServiceDescription(_serviceHost.Description);

            Trace.WriteLine("open ServiceHost");
            _serviceHost.Open();
            Trace.WriteLine("service is started");
            Trace.WriteLine();
        }
Exemplo n.º 14
0
        /// <summary>
        /// OSA Plugin Interface - called on start up to allow plugin to do any tasks it needs
        /// </summary>
        /// <param name="pluginName">The name of the plugin from the system</param>
        public override void RunInterface(string pluginName)
        {
            pName = pluginName;

            try
            {
                this.Log.Info("Starting Rest Interface");

                bool showHelp = bool.Parse(OSAEObjectPropertyManager.GetObjectPropertyValue(pName, "Show Help").Value);

                serviceHost = new WebServiceHost(typeof(OSAERest.api), new Uri("http://localhost:8732/api"));
                WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.None);
                binding.CrossDomainScriptAccessEnabled = true;

                var endpoint = serviceHost.AddServiceEndpoint(typeof(IRestService), binding, "");

                ServiceDebugBehavior sdb = serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
                sdb.HttpHelpPageEnabled = false;

                if (showHelp)
                {
                    serviceHost.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true });
                }

                this.Log.Info("Starting Rest Interface");
                serviceHost.Open();
            }
            catch (Exception ex)
            {
                this.Log.Error("Error starting RESTful web service", ex);
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), "soap");
            WebHttpBinding webBinding = new WebHttpBinding();
            webBinding.ContentTypeMapper = new MyRawMapper();
            host.AddServiceEndpoint(typeof(ITestService), webBinding, "json").Behaviors.Add(new NewtonsoftJsonBehavior());
            Console.WriteLine("Opening the host");
            host.Open();

            ChannelFactory<ITestService> factory = new ChannelFactory<ITestService>(new BasicHttpBinding(), new EndpointAddress(baseAddress + "/soap"));
            ITestService proxy = factory.CreateChannel();
            Console.WriteLine(proxy.GetPerson());

            SendRequest(baseAddress + "/json/GetPerson", "GET", null, null);
            SendRequest(baseAddress + "/json/EchoPet", "POST", "application/json", "{\"Name\":\"Fido\",\"Color\":\"Black and white\",\"Markings\":\"None\",\"Id\":1}");
            SendRequest(baseAddress + "/json/Add", "POST", "application/json", "{\"x\":111,\"z\":null,\"w\":[1,2],\"v\":{\"a\":1},\"y\":222}");

            Console.WriteLine("Now using the client formatter");
            ChannelFactory<ITestService> newFactory = new ChannelFactory<ITestService>(webBinding, new EndpointAddress(baseAddress + "/json"));
            newFactory.Endpoint.Behaviors.Add(new NewtonsoftJsonBehavior());
            ITestService newProxy = newFactory.CreateChannel();
            Console.WriteLine(newProxy.Add(444, 555));
            Console.WriteLine(newProxy.EchoPet(new Pet { Color = "gold", Id = 2, Markings = "Collie", Name = "Lassie" }));
            Console.WriteLine(newProxy.GetPerson());

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();
            host.Close();
            Console.WriteLine("Host closed");
        }
Exemplo n.º 16
0
        public SafeServiceHost(VLogger logger, Type contractType, SafeServicePolicyDecider consumer, string webAddressSuffix, params string[] addresses)
        {
            object instance = consumer;
            this.policyDecider = consumer;
            this.logger = logger;
            List<Uri> addressList = new List<Uri>();
            foreach (String address in addresses)
            {
                addressList.Add(new Uri(address+webAddressSuffix));
            }

            serviceHost = new ServiceHost(instance, addressList.ToArray());
            serviceHost.Authentication.ServiceAuthenticationManager = new SafeServiceAuthenticationManager();
            serviceHost.Authorization.ServiceAuthorizationManager = new SafeServiceAuthorizationManager(consumer, this);
            
            foreach (string address in addresses)
            {
                var contract = ContractDescription.GetContract(contractType);
                var webBinding = new WebHttpBinding();
                var webEndPoint = new ServiceEndpoint(contract, webBinding, new EndpointAddress(address+webAddressSuffix));
                webEndPoint.EndpointBehaviors.Add(new WebHttpBehavior());
                serviceHost.AddServiceEndpoint(webEndPoint);
            }

        }
Exemplo n.º 17
0
        private void ClientInitialize()
        {
            try
            {
                if (!_initialized)
                {
                    _serverUri = new Uri(ItemServiceUrl);

                    Logger.Log("Initializing Client Service connection to {0}", _serverUri.AbsoluteUri);

                    WebHttpBinding webHttpBinding = new WebHttpBinding
                    {
                        OpenTimeout = TimeSpan.FromMilliseconds(5000),
                        SendTimeout = TimeSpan.FromMilliseconds(5000),
                        CloseTimeout = TimeSpan.FromMilliseconds(5000),
                    };

                    _httpFactory = new WebChannelFactory<IItemService>(webHttpBinding, _serverUri);
                    _httpProxy = _httpFactory.CreateChannel();

                    _initialized = true;
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Exception in ClientInitialize() {0}", ex);
            }
        }
Exemplo n.º 18
0
        public void TestMethod1()
        {
            var token = GetToken();

            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var binding = new WebHttpBinding
            {
                Security =
                {
                    Mode = WebHttpSecurityMode.Transport,
                    Transport = {ClientCredentialType = HttpClientCredentialType.None}
                }
            };

            using (var factory = new ChannelFactory<IThingsService>(binding, "https://localhost:1234/things"))
            {
                factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
                var channel = factory.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    WebOperationContext.Current.OutgoingRequest.Headers.Add("token", token);
                    var nodes = channel.GetNodes();
                }
            }
        }
Exemplo n.º 19
0
        public CM_FunctionalTests(string cMUrl, string uName, string uPassword)
        {
            WebHttpBinding bd = new WebHttpBinding();
            bd.SendTimeout = TimeSpan.FromMinutes(2);

            if (cMUrl.ToLower().Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
                bd.Security.Mode = WebHttpSecurityMode.Transport;
                bd.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                this.ServiceChannel = new ChannelFactory<IChassisManager>(bd, cMUrl);
            }
            else
            {
                bd.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
                bd.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                this.ServiceChannel = new ChannelFactory<IChassisManager>(bd, cMUrl);
            }

            this.ServiceChannel.Endpoint.Behaviors.Add(new WebHttpBehavior());

            // Check if user credentials are specified, if not use default
            if (!string.IsNullOrEmpty(uName))
            {
                // Set user credentials specified
                this.ServiceChannel.Credentials.Windows.ClientCredential =
                    new System.Net.NetworkCredential(uName, uPassword);
            }
            this.Channel = this.ServiceChannel.CreateChannel();
        }
Exemplo n.º 20
0
 public bool TryStart(string endpointAddress, out string errorMessage)
 {
     errorMessage = string.Empty;
     try
     {
         this.ShootDown();
         serviceHost = createServiceHost();
         WebHttpBinding restBinding = new WebHttpBinding()
         {
             TransferMode = TransferMode.Buffered,//TransferMode.StreamedResponse,
             MaxBufferSize = int.MaxValue,
             MaxReceivedMessageSize = int.MaxValue
         };
         ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(typeof(IWebService)
             , restBinding, endpointAddress);
         endpoint.Behaviors.Add(new WebHttpBehavior());
         serviceHost.Open();
     }
     catch (Exception e)
     {
         errorMessage = e.Message;
         return false;
     }
     return true;
 }
Exemplo n.º 21
0
		public void CreateBindingElements ()
		{
			WebHttpBinding b = new WebHttpBinding ();
			BindingElementCollection bc = b.CreateBindingElements ();
			Assert.AreEqual (2, bc.Count, "#1");
			Assert.AreEqual (typeof (WebMessageEncodingBindingElement), bc [0].GetType (), "#2");
			Assert.AreEqual (typeof (HttpTransportBindingElement), bc [1].GetType (), "#3");
		}
Exemplo n.º 22
0
        public void DefaultSchemeBasedOnSecurityMode ()
        {
            WebHttpBinding b = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
            Assert.AreEqual("http", b.Scheme, "#1");

            b = new WebHttpBinding(WebHttpSecurityMode.Transport);
            Assert.AreEqual("https", b.Scheme, "#2");
        }
Exemplo n.º 23
0
        protected void OnStart(string[] args)
        {
            try
            {
                KillProcesses();

                for (int s = 0; s < MapServerConfig.ServerCount; s++)
                {
                    MapServerConfig.ServerConfig serverConfig = MapServerConfig.Server(s);

                    if (_startInstances)
                    {
                        _running = true;
                        for (int i = 0; i < serverConfig.Instances.Length; i++)
                        {
                            MapServerConfig.ServerConfig.InstanceConfig instanceConfig = serverConfig.Instances[i];
                            if (instanceConfig == null || instanceConfig.Port <= 0)
                            {
                                continue;
                            }

                            Thread thread = new Thread(new ParameterizedThreadStart(ProcessMonitor));
                            thread.Start(instanceConfig.Port);
                        }
                    }

                    TaskerServiceType serviceType = new TaskerServiceType();
                    serviceType.Init(serverConfig.Port);
                    ServiceHost host = new ServiceHost(/*typeof(Service.TaskerServiceType)*/ serviceType, new Uri("http://localhost:" + serverConfig.Port));

                    try
                    {
                        if (host.Description.Endpoints.Count == 1 &&
                            host.Description.Endpoints[0].Binding is System.ServiceModel.WebHttpBinding)
                        {
                            System.ServiceModel.WebHttpBinding binding = (System.ServiceModel.WebHttpBinding)host.Description.Endpoints[0].Binding;
                            binding.MaxReceivedMessageSize = int.MaxValue;
                        }
                    }
                    catch { }

                    host.Open();

                    Console.WriteLine("Tasker is listening on port " + serverConfig.Port);

                    _hosts.Add(host);
                }
                DeleteImageThread del = new DeleteImageThread();
                _delThread = new Thread(new ThreadStart(del.Run));
                _delThread.Start();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Exception: " + ex.Message + "\n" + ex.StackTrace);
                Console.ResetColor();
            }
        }
Exemplo n.º 24
0
        public WebServiceHost CreateServiceHost()
        {
            var port = ConfigurationManager.AppSettings["SdShare.ServerPort"];
            var serviceHost = new WebServiceHost(new PublishingService(), new[] {   new Uri("http://localhost:" + port + "/sdshare") });
            var webBinding = new WebHttpBinding();
            serviceHost.AddServiceEndpoint(typeof(IPublishingService), webBinding, "rest");

            return serviceHost;
        }
Exemplo n.º 25
0
        protected override void InitializeRuntime()
        {
            WebHttpBinding binding = new WebHttpBinding();
            binding.CrossDomainScriptAccessEnabled = true;
            ServiceEndpoint endpoint = this.AddServiceEndpoint(typeof(IJsonpEnabledBasicService), binding, "");
            endpoint.Behaviors.Add(new WebHttpBehavior3());

            base.InitializeRuntime();
        }
Exemplo n.º 26
0
 /// <summary>
 /// Open the service host.
 /// </summary>
 /// <param name="binding">A specific biding instance.</param>
 public void OpenServiceHost(System.ServiceModel.WebHttpBinding binding)
 {
     if (base.CommunicationState == CommunicationState.Closed)
     {
         base.Initialise();
         base.ServiceHost.AddServiceEndpoint(typeof(TContract), binding, "");
         OpenConnection();
     }
 }
Exemplo n.º 27
0
 /// <summary>
 /// Open the service host.
 /// </summary>
 /// <param name="binding">A specific biding instance.</param>
 /// <param name="address">The endpoint address.</param>
 public void OpenServiceHost(System.ServiceModel.WebHttpBinding binding, string address)
 {
     if (base.CommunicationState == CommunicationState.Closed)
     {
         base.Initialise();
         base.ServiceHost.AddServiceEndpoint(base.ServiceType, binding, address);
         OpenConnection();
     }
 }
 /// <summary>
 /// 使用指定基址创建指定的 System.ServiceModel.Web.WebServiceHost 派生类的实例。
 /// </summary>
 /// <param name="serviceType">要创建的服务主机的类型</param>
 /// <param name="baseAddresses">该服务的基址的数组</param>
 /// <returns>System.ServiceModel.ServiceHost 派生类的实例</returns>
 protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
 {
     WebServiceHost host = new WebServiceHost(serviceType, baseAddresses);
     WebHttpBinding binding = new WebHttpBinding();
     binding.ReaderQuotas.MaxStringContentLength = 2147483647;
     ServiceEndpoint endpoint = host.AddServiceEndpoint(serviceType, binding, "");
     endpoint.Behaviors.Add(new CommonHttpBehavior());
     return host;
 }
Exemplo n.º 29
0
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            string serviceName = baseAddresses[0].LocalPath.Substring(baseAddresses[0].LocalPath.LastIndexOf('/')).Replace("/", string.Empty).Replace(".svc", string.Empty);
            string iServiceName = "I" + serviceName;

            Assembly assemblyInterfaces = Assembly.Load("CNDreams.ServiceInterface");
            Type interfaceType = assemblyInterfaces.GetTypes().FirstOrDefault(x => x.Name.Equals(iServiceName, StringComparison.OrdinalIgnoreCase));
            if (interfaceType == null)
                return null;

            Type[] allServerTypes = Assembly.GetExecutingAssembly().GetTypes();
            Type implementedType = allServerTypes.FirstOrDefault(x => x.GetInterface(interfaceType.Name) != null);
            if (implementedType == null)
                return null;

            ServiceHost host = new ServiceHost(implementedType, baseAddresses);

            /* wsHttpBinding 绑定节点
            ----------------------------------------------------------*/
            WSHttpBinding wsHttpBinding = new WSHttpBinding("wsHttpBinding-binding");
            host.AddServiceEndpoint(interfaceType, wsHttpBinding, "wsHttp");

            /* webHttpBinding 绑定节点
            ----------------------------------------------------------*/
            WebHttpBinding webHttpBinding = new WebHttpBinding("webHttpBinding-binding");
            ServiceEndpoint serviceEndpoint = host.AddServiceEndpoint(interfaceType, webHttpBinding, "webHttp");
            serviceEndpoint.Behaviors.Add(new WebHttpBehavior()
            {
                AutomaticFormatSelectionEnabled = true,
                HelpEnabled = true
            });

            ServiceMetadataBehavior metaDataBehavior = new ServiceMetadataBehavior();
            metaDataBehavior.HttpGetEnabled = true;
            host.Description.Behaviors.Add(metaDataBehavior);
            host.Description.Behaviors.Add(new NHibernateInceptor());
            ServiceDebugBehavior debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            //ServiceCredentials serviceCredential = new ServiceCredentials();
            //serviceCredential.UserNameAuthentication.UserNamePasswordValidationMode = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
            //serviceCredential.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
            //serviceCredential.ServiceCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=localhost");
            //host.Description.Behaviors.Add(serviceCredential);
            if (debug == null)
            {
                host.Description.Behaviors.Add(
                     new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
            }
            else
            {
                if (!debug.IncludeExceptionDetailInFaults)
                    debug.IncludeExceptionDetailInFaults = true;
            }
            host.AddServiceEndpoint(typeof(IMetadataExchange), wsHttpBinding, "MEX");

            return host;
        }
Exemplo n.º 30
0
		public static Binding WebHttpBinding()
		{
			WebHttpBinding webHttpBinding = new WebHttpBinding(WebHttpSecurityMode.Transport);
			webHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
			webHttpBinding.ReaderQuotas.MaxStringContentLength = 0x4000000;
			webHttpBinding.MaxBufferSize = 0x4c4b40;
			webHttpBinding.MaxReceivedMessageSize = (long)0x4c4b40;
			webHttpBinding.ReaderQuotas.MaxArrayLength = 0x4c4b40;
			return webHttpBinding;
		}
        public static Binding AnonymousWebHttpBinding(int maxStringContentLength = MaxStringContentLength)
        {
            var binding = new WebHttpBinding(WebHttpSecurityMode.None);
            binding.ReaderQuotas.MaxStringContentLength = maxStringContentLength;

            // Increasing MaxReceivedMessageSize to allow big deployments
            binding.MaxReceivedMessageSize = MaxReceivedMessageSize;

            return binding;
        }
Exemplo n.º 32
0
 private static Binding GetBinding()
 {
     var binding = new WebHttpBinding();
     binding.Security.Mode = WebHttpSecurityMode.None;//BasicHttpSecurityMode.None;
     binding.MaxReceivedMessageSize = 1000 * 1024 * 1024;
     binding.ReaderQuotas.MaxStringContentLength = 1000 * 1024 * 1024;//10 * 1024 * 1024
     binding.SendTimeout = new TimeSpan(0, 500, 0);//new TimeSpan(0, 5, 0);
     binding.ReceiveTimeout = new TimeSpan(0, 500, 0);//new TimeSpan(0, 5, 0);
     return binding;
 }
Exemplo n.º 33
0
 static void Main(string[] args)
 {
     WebService DemoServices = new WebService();
     WebHttpBinding binding = new WebHttpBinding();
     WebServiceHost serviceHost = new WebServiceHost(DemoServices, new Uri("http://localhost:8000/"));
     serviceHost.AddServiceEndpoint(typeof(IWebService), binding, "");
     serviceHost.Open();
     Console.ReadKey();
     serviceHost.Close();
 }
Exemplo n.º 34
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="endPointAddress">The specific end point address</param>
 /// <param name="binding">Contains the binding elements that specify the protocols,
 /// transports, and message encoders used for communication between clients and services.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(string endPointAddress, System.ServiceModel.WebHttpBinding binding,
               string username                                   = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(endPointAddress), binding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }
Exemplo n.º 35
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="binding">Contains the binding elements that specify the protocols,
 /// transports, and message encoders used for communication between clients and services.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(System.ServiceModel.WebHttpBinding binding, string username = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(Nequeo.Management.ServiceModel.Properties.Settings.Default.ServiceAddress),
         binding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }