コード例 #1
0
 /// <summary>
 /// Configures WS HTTP Binding message size
 /// </summary>
 /// <param name="messageSize">Message size to configure the binding for</param>
 /// <param name="binding">BasicHttpBinding to configure</param>
 public static void ConfigureMessageSizeOnWsHttpBinding(MessageSize messageSize, WSHttpBinding binding)
 {
     if (messageSize == MessageSize.Medium)
     {
         binding.MaxBufferPoolSize                   = 1024 * 1024 * 10; // 10MB
         binding.MaxReceivedMessageSize              = binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxArrayLength         = (int)binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxStringContentLength = (int)binding.MaxBufferPoolSize;
     }
     else if (messageSize == MessageSize.Large)
     {
         binding.MaxBufferPoolSize                   = 1024 * 1024 * 100; // 100MB
         binding.MaxReceivedMessageSize              = binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxArrayLength         = (int)binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxStringContentLength = (int)binding.MaxBufferPoolSize;
     }
     else if (messageSize == MessageSize.VeryLarge)
     {
         binding.MaxBufferPoolSize                   = 1024 * 1024 * 1024; // 1GB
         binding.MaxReceivedMessageSize              = binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxArrayLength         = (int)binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxStringContentLength = (int)binding.MaxBufferPoolSize;
     }
     else if (messageSize == MessageSize.Max)
     {
         binding.MaxBufferPoolSize                   = int.MaxValue;
         binding.MaxReceivedMessageSize              = binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxArrayLength         = (int)binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxStringContentLength = (int)binding.MaxBufferPoolSize;
     }
 }
コード例 #2
0
        /// <summary>
        ///     Decodes a raw buffer into a ready to use <see cref="Message" />.
        /// </summary>
        /// <param name="size">The 2 bytes masked message size from the raw buffer.</param>
        /// <param name="buffer">The remaining message raw buffer.</param>
        /// <returns>The decoded ready to use <see cref="Message" />.</returns>
        /// <exception cref="InvalidOperationException">The message was interrupted or injected (checksum failed).</exception>
        internal Message Decode(MessageSize size, Span <byte> buffer)
        {
            if (size.Encrypted && this.Option.HasFlag(MessageProtocolOption.Encryption))
            {
                this.Blowfish.Decrypt(buffer);
            }

            var msg = new Message(size, buffer);

            this.Validate(msg);

            return(msg);
        }
コード例 #3
0
 /// <summary>
 /// Configures WS HTTP Binding message size
 /// </summary>
 /// <param name="messageSize">Message size to configure the binding for</param>
 /// <param name="binding">BasicHttpBinding to configure</param>
 public static void ConfigureMessageSizeOnWsHttpBinding(MessageSize messageSize, WSHttpBinding binding)
 {
     if (messageSize == MessageSize.Medium)
     {
         binding.MaxBufferPoolSize = 1024 * 1024 * 10; // 10MB
         binding.MaxReceivedMessageSize = binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxArrayLength = (int)binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxStringContentLength = (int)binding.MaxBufferPoolSize;
     }
     else if (messageSize == MessageSize.Large)
     {
         binding.MaxBufferPoolSize = 1024 * 1024 * 100; // 100MB
         binding.MaxReceivedMessageSize = binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxArrayLength = (int)binding.MaxBufferPoolSize;
         binding.ReaderQuotas.MaxStringContentLength = (int)binding.MaxBufferPoolSize;
     }
 }
コード例 #4
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 public void AddServiceHostBasicHttp(Type serviceType, MessageSize messageSize)
 {
     AddServiceHostBasicHttp(serviceType, null, null, messageSize);
 }
コード例 #5
0
 /// <summary>Adds a new REST service using JSON data format</summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="contractType">Type of the contract.</param>
 /// <param name="serviceId">The service id.</param>
 /// <param name="messageSize">Size of the message.</param>
 /// <param name="baseAddress">The base address.</param>
 /// <param name="basePath">The base path.</param>
 /// <param name="extension">The extension.</param>
 /// <param name="useHttps">Indicates whether HTTPS should be used</param>
 public void AddServiceHostRestJson(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined, string baseAddress = null, string basePath = null, string extension = null, bool useHttps = false)
 {
     Execute(
         () => ServiceGarden.AddServiceHostRestJson(serviceType, contractType, serviceId, messageSize, baseAddress, basePath, extension, useHttps),
         url => AddServiceInfo(serviceType, contractType, url, "REST HTTP (JSON)", ServiceGarden.GetHostByEndpointAddress(url))
         );
 }
コード例 #6
0
        /// <summary>
        /// Adds another service to the list of hosted services
        /// </summary>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="messageSize">Size of the message.</param>
        /// <param name="exposeWsdl">if set to <c>true</c> [expose WSDL].</param>
        public void AddServiceHostWsHttp(Type serviceType, MessageSize messageSize, bool exposeWsdl)
        {
            var contractType = serviceType.GetInterfaces()[0];

            AddServiceHostWsHttp(serviceType, contractType, contractType.Name, messageSize, exposeWsdl);
        }
コード例 #7
0
 /// <summary>Hosts a Basic HTTP service</summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="contractType">Type of the contract.</param>
 /// <param name="serviceId">The service id.</param>
 /// <param name="messageSize">Size of the message.</param>
 /// <param name="exposeWsdl">if set to <c>true</c> a WSDL endpoint is exposed.</param>
 /// <param name="baseAddress">The base address.</param>
 /// <param name="basePath">The base path.</param>
 /// <param name="extension">The extension.</param>
 /// <param name="useHttps">Indicates whether HTTPS should be used</param>
 public void AddServiceHostBasicHttp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined, bool exposeWsdl = false, string baseAddress = null, string basePath = null, string extension = null, bool useHttps = false)
 {
     Execute(
         () => ServiceGarden.AddServiceHostBasicHttp(serviceType, contractType, serviceId, messageSize, exposeWsdl, baseAddress, basePath, extension, useHttps),
         url => AddServiceInfo(serviceType, contractType, url, "Basic HTTP", ServiceGarden.GetHostByEndpointAddress(url))
         );
 }
コード例 #8
0
        public static string AddServiceHostBasicHttp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined, bool exposeWsdl = false, string baseAddress = null, string basePath = null, string extension = null, bool useHttps = false)
        {
            // Before we do anything else, we start looking for optional parameters and setting appropriate defaults
            if (contractType == null) contractType = GetContractTypeFromServiceType(serviceType);
            if (baseAddress == null)
            {
                baseAddress = BaseUrl;
                if (string.IsNullOrEmpty(baseAddress)) throw new Core.Exceptions.NullReferenceException("Static BaseUrl property must be set on the ServiceGarden class before the garden can be populated.");
            }
            if (basePath == null)
            {
                basePath = BasePath;
                if (!string.IsNullOrEmpty(basePath) && !basePath.EndsWith("/")) basePath += "/";
            }
            if (extension == null)
            {
                extension = GetSetting("ServiceBasicHTTPExtension", contractType.Name, "basic");
                if (!string.IsNullOrEmpty(extension) && !extension.StartsWith("/")) extension = "/" + extension;
            }
            if (serviceId == null) serviceId = contractType.Name;
            if (messageSize == MessageSize.Undefined) messageSize = GetMessageSize(contractType.Name);

            // Starting our regular method
            if (!string.IsNullOrEmpty(basePath) && !basePath.EndsWith("/")) basePath += "/";
            if (!string.IsNullOrEmpty(extension) && !extension.StartsWith("/")) extension = "/" + extension;
            var protocol = useHttps ? "https://" : "http://";
            var serviceFullAddress = protocol + baseAddress + "/" + basePath + serviceId + extension;
            var serviceNamespace = GetServiceNamespace(serviceType, contractType);

            var addresses = new[] { new Uri(serviceFullAddress) };
            var host = CreateServiceHost(serviceType, contractType, addresses);

            // Binding needed
            var securityMode = useHttps ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None;
            var binding = new BasicHttpBinding(securityMode) {SendTimeout = new TimeSpan(0, 10, 0)};
            if (!string.IsNullOrEmpty(serviceNamespace)) binding.Namespace = serviceNamespace;
            ServiceHelper.ConfigureMessageSizeOnBasicHttpBinding(messageSize, binding);

            // Endpoint configuration
            if (BeforeEndpointAdded != null)
            {
                var endpointAddedArgs = new EndpointAddedEventArgs { Binding = binding, ContractType = contractType, ServiceFullAddress = serviceFullAddress };
                BeforeEndpointAdded(null, endpointAddedArgs);
                serviceFullAddress = endpointAddedArgs.ServiceFullAddress;
            }
            var endpoint = host.AddServiceEndpoint(contractType, binding, serviceFullAddress);
            if (!string.IsNullOrEmpty(serviceNamespace) && endpoint.Contract != null && endpoint.Contract.Namespace != serviceNamespace) endpoint.Contract.Namespace = serviceNamespace;
            if (HttpCrossDomainCallsAllowed) endpoint.Behaviors.Add(new CrossDomainScriptBehavior());

            // Maybe we expose a WSDL endpoint too
            if (exposeWsdl)
            {
                var wsdlFullPath = serviceFullAddress + "/wsdl";
                var smb = new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = new Uri(wsdlFullPath) };
                host.Description.Behaviors.Add(smb);
                var mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();
                host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, wsdlFullPath);
            }

            var serviceKey = serviceFullAddress;
            if (Hosts.ContainsKey(serviceKey))
            {
                if (Hosts[serviceKey].Host.State == CommunicationState.Opened)
                {
                    try
                    {
                        Hosts[serviceKey].Host.Close();
                    }
                    catch { } // Nothing we can do
                }
                Hosts.Remove(serviceKey);
            }

            // If needed, we fire the static event, so people can tie into this to programmatically manipulate the host or binding if need be
            if (BeforeHostAdded != null) BeforeHostAdded(null, new HostAddedEventArgs
                                                       {
                                                           Host = host,
                                                           ServiceFullAddress = serviceFullAddress,
                                                           Binding = binding,
                                                           ContractType = contractType,
                                                           MessageSize = messageSize,
                                                           ServiceId = serviceId,
                                                           ServiceType = serviceType
                                                       });

            lock (Hosts)
                Hosts.Add(serviceKey, new HostWrapper(host, serviceFullAddress));

            return StartService(serviceKey);
        }
コード例 #9
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 /// <param name="exposeWsdl">if set to <c>true</c> [expose WSDL].</param>
 public void AddServiceHostBasicHttp(Type serviceType, MessageSize messageSize, bool exposeWsdl)
 {
     AddServiceHostBasicHttp(serviceType, null, null, messageSize, exposeWsdl);
 }
コード例 #10
0
 /// <summary>Adds a TCP/IP (net.tcp) service host</summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="contractType">Type of the contract.</param>
 /// <param name="serviceId">The service id.</param>
 /// <param name="messageSize">Size of the message.</param>
 public void AddServiceHostNetTcp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined)
 {
     var port = _basePort;
     _basePort++;
     Execute(
         () => ServiceGarden.AddServiceHostNetTcp(serviceType, contractType, serviceId, messageSize, port),
         url => AddServiceInfo(serviceType, contractType, url, "Net.Tcp", ServiceGarden.GetHostByEndpointAddress(url))
         );
 }
コード例 #11
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 public void AddServiceHostBasicHttp(Type serviceType, MessageSize messageSize)
 {
     AddServiceHostBasicHttp(serviceType, null, null, messageSize);
 }
コード例 #12
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 public void AddServiceHostNetTcp(Type serviceType, MessageSize messageSize)
 {
     var contractType = serviceType.GetInterfaces()[0];
     AddServiceHostNetTcp(serviceType, contractType, contractType.Name, messageSize);
 }
コード例 #13
0
 /// <summary>Adds a new REST service using JSON data format</summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="contractType">Type of the contract.</param>
 /// <param name="serviceId">The service id.</param>
 /// <param name="messageSize">Size of the message.</param>
 /// <param name="baseAddress">The base address.</param>
 /// <param name="basePath">The base path.</param>
 /// <param name="extension">The extension.</param>
 /// <param name="useHttps">Indicates whether HTTPS should be used</param>
 public void AddServiceHostRestJson(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined, string baseAddress = null, string basePath = null, string extension = null, bool useHttps = false)
 {
     Execute(
         () => ServiceGarden.AddServiceHostRestJson(serviceType, contractType, serviceId, messageSize, baseAddress, basePath, extension, useHttps),
         url => AddServiceInfo(serviceType, contractType, url, "REST HTTP (JSON)", ServiceGarden.GetHostByEndpointAddress(url))
         );
 }
コード例 #14
0
        /// <summary>Adds a TCP/IP (net.tcp) service host</summary>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="contractType">Type of the contract.</param>
        /// <param name="serviceId">The service id.</param>
        /// <param name="messageSize">Size of the message.</param>
        public void AddServiceHostNetTcp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined)
        {
            var port = _basePort;

            _basePort++;
            Execute(
                () => ServiceGarden.AddServiceHostNetTcp(serviceType, contractType, serviceId, messageSize, port),
                url => AddServiceInfo(serviceType, contractType, url, "Net.Tcp", ServiceGarden.GetHostByEndpointAddress(url))
                );
        }
コード例 #15
0
 public override string ToString()
 {
     return("[P2Pv1Header]\r\n" +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "SessionId     : {1:x} ({0})\r\n", SessionId.ToString(System.Globalization.CultureInfo.InvariantCulture), SessionId) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "Identifier    : {1:x} ({0})\r\n", Identifier.ToString(System.Globalization.CultureInfo.InvariantCulture), Identifier) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "Offset        : {1:x} ({0})\r\n", Offset.ToString(System.Globalization.CultureInfo.InvariantCulture), Offset) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "TotalSize     : {1:x} ({0})\r\n", TotalSize.ToString(System.Globalization.CultureInfo.InvariantCulture), TotalSize) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "MessageSize   : {1:x} ({0})\r\n", MessageSize.ToString(System.Globalization.CultureInfo.InvariantCulture), MessageSize) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "Flags         : {1:x} ({0})\r\n", (uint)Flags, Convert.ToString(Flags)) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "AckSessionId  : {1:x} ({0})\r\n", AckSessionId.ToString(System.Globalization.CultureInfo.InvariantCulture), AckSessionId) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "AckIdentifier : {1:x} ({0})\r\n", AckIdentifier.ToString(System.Globalization.CultureInfo.InvariantCulture), AckIdentifier) +
            String.Format(System.Globalization.CultureInfo.InvariantCulture, "AckTotalSize  : {1:x} ({0})\r\n", AckTotalSize.ToString(System.Globalization.CultureInfo.InvariantCulture), AckTotalSize));
 }
コード例 #16
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 public void AddServiceHostRestJson(Type serviceType, MessageSize messageSize)
 {
     AddServiceHostRestJson(serviceType, null, null, messageSize);
 }
コード例 #17
0
        public override string ToString()
        {
            StringBuilder headerTLVBuilder = new StringBuilder();

            headerTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Header TLVs  ({0})    : ", headerTLVs.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)));
            if (headerTLVs.Count > 0)
            {
                foreach (KeyValuePair <byte, byte[]> keyvalue in headerTLVs)
                {
                    headerTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{1:x}({0}),", keyvalue.Key.ToString(System.Globalization.CultureInfo.InvariantCulture), keyvalue.Key));
                    headerTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{1:x}({0}),( ", keyvalue.Value.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), keyvalue.Value.Length));
                    foreach (byte b in keyvalue.Value)
                    {
                        headerTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "0x{0:x2} ", b));
                    }
                    headerTLVBuilder.Append("); ");
                }
            }
            headerTLVBuilder.Append("\r\n");

            StringBuilder bodyTLVBuilder = new StringBuilder();

            bodyTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, " DataPacket TLVs ({0}): ", dataPacketTLVs.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)));
            if (dataPacketTLVs.Count > 0)
            {
                foreach (KeyValuePair <byte, byte[]> keyvalue in dataPacketTLVs)
                {
                    bodyTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{1:x}({0}),", keyvalue.Key.ToString(System.Globalization.CultureInfo.InvariantCulture), keyvalue.Key));
                    bodyTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{1:x}({0}),( ", keyvalue.Value.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), keyvalue.Value.Length));
                    foreach (byte b in keyvalue.Value)
                    {
                        bodyTLVBuilder.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "0x{0:x2} ", b));
                    }
                    bodyTLVBuilder.Append("); ");
                }
            }
            bodyTLVBuilder.Append("\r\n");

            int dataHeaderLen = DataPacketHeaderLength;

            return("[P2Pv2Header]\r\n" +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, "HeaderLength        : {1:x} ({0})\r\n", HeaderLength.ToString(System.Globalization.CultureInfo.InvariantCulture), HeaderLength) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, "OperationCode       : {1:x} ({0})\r\n", (byte)OperationCode, Convert.ToString(OperationCode)) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, "MessageSize         : {1:x} ({0})\r\n", MessageSize.ToString(System.Globalization.CultureInfo.InvariantCulture), MessageSize) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, "Identifier          : {1:x} ({0})\r\n", Identifier.ToString(System.Globalization.CultureInfo.InvariantCulture), Identifier) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, "AckIdentifier       : {1:x} ({0})\r\n", AckIdentifier.ToString(System.Globalization.CultureInfo.InvariantCulture), AckIdentifier) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, "NakIdentifier       : {1:x} ({0})\r\n", NakIdentifier.ToString(System.Globalization.CultureInfo.InvariantCulture), NakIdentifier) +
                   headerTLVBuilder.ToString() +

                   String.Format(System.Globalization.CultureInfo.InvariantCulture, " Data HeaderLength  : {1:x} ({0})\r\n", dataHeaderLen.ToString(System.Globalization.CultureInfo.InvariantCulture), dataHeaderLen) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, " TFCombination      : {1:x} ({0})\r\n", (byte)TFCombination, Convert.ToString(TFCombination)) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, " PackageNumber      : {1:x} ({0})\r\n", PackageNumber.ToString(System.Globalization.CultureInfo.InvariantCulture), PackageNumber) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, " SessionId          : {1:x} ({0})\r\n", SessionId.ToString(System.Globalization.CultureInfo.InvariantCulture), SessionId) +
                   String.Format(System.Globalization.CultureInfo.InvariantCulture, " DataRemaining      : {1:x} ({0})\r\n", DataRemaining.ToString(System.Globalization.CultureInfo.InvariantCulture), DataRemaining) +
                   bodyTLVBuilder.ToString());
        }
コード例 #18
0
 public static string TryAddServiceHostBasicHttp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined, bool exposeWsdl = false, string baseAddress = null, string basePath = null, string extension = null, bool useHttps = false)
 {
     try
     {
         var url = AddServiceHostBasicHttp(serviceType, contractType, serviceId, messageSize, exposeWsdl, baseAddress, basePath, extension, useHttps);
         if (contractType == null) contractType = GetContractTypeFromServiceType(serviceType);
         if (!string.IsNullOrEmpty(url))
         {
             var logText = "Successfully started Basic HTTP Service '" + serviceType + "' (contract: '" + contractType + "').\r\n\r\nFull URL: " + url;
             logText += "\r\nExpose WSDL: " + (exposeWsdl ? "Yes" : "No");
             logText += "\r\nMessage Size: " + messageSize;
             LoggingMediator.Log(logText);
         }
         else
             LoggingMediator.Log("Error starting Basic HTTP Service '" + serviceType + "' (contract: '" + contractType + "').", LogEventType.Error);
         return url;
     }
     catch (Exception ex)
     {
         if (contractType == null) contractType = GetContractTypeFromServiceType(serviceType);
         LoggingMediator.Log("Error starting Basic HTTP Service '" + serviceType + "' (contract: '" + contractType + "').", ex, LogEventType.Error);
         return string.Empty;
     }
 }
コード例 #19
0
 /// <summary>
 /// Creates the service host.
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Potential size of the message. (Should be large if the payload could potentially be more than an MB).</param>
 /// <param name="exposeWsdl">if set to <c>true</c> [expose WSDL].</param>
 /// <param name="baseAddress">Base service address (such as www.domain.com)</param>
 /// <param name="basePath">Base path (such as "MyService" to create www.domain.com/MyService/ws)</param>
 /// <returns>
 /// Service URL if successful. Empty string otherwise.
 /// </returns>
 public static string AddServiceHostWsHttp(Type serviceType, MessageSize messageSize, bool exposeWsdl, string baseAddress, string basePath)
 {
     return AddServiceHostWsHttp(serviceType, null, null, messageSize, exposeWsdl, baseAddress, basePath);
 }
コード例 #20
0
        protected override ITransport InitializeTransport(IEasyGelfLogger logger)
        {
            var remoteIpAddress = Dns.GetHostAddresses(RemoteAddress)
                                  .Shuffle()
                                  .FirstOrDefault() ?? IPAddress.Loopback;
            var encoder       = new CompositeEncoder(new GZipEncoder(), new ChunkingEncoder(new MessageBasedIdGenerator(), MessageSize.UdpMessageSize()));
            var configuration = new UdpTransportConfiguration
            {
                Host = new IPEndPoint(remoteIpAddress, RemotePort),
            };

            return(new UdpTransport(configuration, encoder, new GelfMessageSerializer()));
        }
コード例 #21
0
 /// <summary>
 /// Tries to create the service host.
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Potential size of the message. (Should be large if the payload could potentially be more than an MB).</param>
 /// <param name="baseAddress">Base service address (such as www.domain.com)</param>
 /// <param name="basePath">Base path (such as "MyService" to create www.domain.com/MyService/ws)</param>
 /// <returns>
 /// Service URL if successful. Empty string otherwise.
 /// </returns>
 /// <remarks>Uses the LoggingMediator class to log information. Configure LoggingMediator accordingly.</remarks>
 public static string TryAddServiceHostRestXml(Type serviceType, MessageSize messageSize, string baseAddress, string basePath)
 {
     return TryAddServiceHostRestXml(serviceType, null, null, messageSize, baseAddress, basePath);
 }
コード例 #22
0
        protected override ITransport InitializeTransport(IEasyGelfLogger logger)
        {
            var encoder       = new CompositeEncoder(new GZipEncoder(), new ChunkingEncoder(new MessageBasedIdGenerator(), MessageSize.UdpMessageSize()));
            var configuration = new UdpTransportConfiguration
            {
                RemoteAddress = RemoteAddress,
                RemotePort    = RemotePort
            };

            return(new UdpTransport(configuration, encoder, new GelfMessageSerializer(logger)));
        }
コード例 #23
0
 /// <summary>
 /// Creates the service host.
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Potential size of the message. (Should be large if the payload could potentially be more than an MB).</param>
 /// <param name="baseAddress">Base service address (such as www.domain.com)</param>
 /// <param name="basePath">Base path (such as "MyService" to create www.domain.com/MyService/ws)</param>
 /// <returns>
 /// Service URL if successful. Empty string otherwise.
 /// </returns>
 public static string AddServiceHostRestJson(Type serviceType, MessageSize messageSize, string baseAddress, string basePath)
 {
     return AddServiceHostRestJson(serviceType, null, null, messageSize, baseAddress, basePath);
 }
コード例 #24
0
        private void OnTimingFrame(MessageFrame frame)
        {
            var data = Encoding.ASCII.GetString(frame.PayloadBuffer.Array, frame.PayloadBuffer.Offset,
                                                frame.PayloadBuffer.Count);

            var parts = data.Split(';');

            if (data == "completed")
            {
                var clockSyncAndNetworkDelay = TimeSpan.FromMilliseconds(_timings.Average());
                var elapsedTime = DateTime.UtcNow.Subtract(Started).Subtract(clockSyncAndNetworkDelay);
                var mbits       = (MessageCount * MessageSize * 8L / elapsedTime.TotalSeconds) / 1000000;
                Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " completed.");
                Console.WriteLine("Duration:      {0} ms", elapsedTime.TotalMilliseconds);
                Console.WriteLine("Message Size:  {0} bytes", MessageSize.ToString("N0"));
                Console.WriteLine("Message Count: {0}", MessageCount.ToString("N0"));
                Console.WriteLine("Total size:    {0} bytes", (MessageSize * MessageCount).ToString("N0"));
                Console.WriteLine("Msgs/sec:      {0}", (MessageCount / elapsedTime.TotalSeconds).ToString("N0"));
                Console.WriteLine("Throughput:    {0} Mbit/s", mbits.ToString("N1"));

                if (!File.Exists("result.csv"))
                {
                    File.AppendAllText("result.csv", "sep=,\r\n");
                    File.AppendAllText("result.csv", @"""Message size (bytes)"",""Message count"",""Transfer size (bytes)"",""Msgs/Ack"",""Duration (ms)"",""Msgs/sec"",""Troughput (Mbit/s)""" + "\r\n");
                }

                File.AppendAllText(@"result.csv",
                                   string.Format("{0},{1},{2},{3},{4},{5},{6}\r\n",
                                                 MessageSize.ToString(CultureInfo.InvariantCulture),
                                                 MessageCount.ToString(CultureInfo.InvariantCulture),
                                                 (MessageSize * MessageCount).ToString(CultureInfo.InvariantCulture),
                                                 MessagesPerAck,
                                                 ((long)elapsedTime.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
                                                 ((long)(MessageCount / elapsedTime.TotalSeconds)).ToString(CultureInfo.InvariantCulture),
                                                 mbits.ToString(CultureInfo.InvariantCulture)));
                _completedEvent.Set();

                return;
            }

            var timing = int.Parse(parts[0]);

            _timings.Add(timing);
            var date       = DateTime.Parse(parts[1], CultureInfo.InvariantCulture);
            var difference = DateTime.UtcNow.Subtract(date).TotalMilliseconds;

            _timings.Add((int)difference);

            if (_timings.Count == 10)
            {
                var buffer = Encoding.ASCII.GetBytes(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.ffff") + ";end");
                _client.Send(new MessageFrame(buffer));
            }
            else if (_timings.Count == 12)
            {
                Started = DateTime.UtcNow;
                Benchmark(_client);
            }
            else
            {
                var buffer = Encoding.ASCII.GetBytes(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                _client.Send(new MessageFrame(buffer));
            }
        }
コード例 #25
0
 /// <summary>
 /// Tries to create the service host.
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="contractType">Type of the contract.</param>
 /// <param name="messageSize">Potential size of the message. (Should be large if the payload could potentially be more than an MB).</param>
 /// <param name="baseAddress">Base service address (such as www.domain.com)</param>
 /// <param name="basePath">Base path (such as "MyService" to create www.domain.com/MyService/ws)</param>
 /// <returns>
 /// Service URL if successful. Empty string otherwise.
 /// </returns>
 /// <remarks>Uses the LoggingMediator class to log information. Configure LoggingMediator accordingly.</remarks>
 public static string TryAddServiceHostRestJson(Type serviceType, Type contractType, MessageSize messageSize, string baseAddress, string basePath)
 {
     return TryAddServiceHostRestJson(serviceType, contractType, null, messageSize, baseAddress, basePath);
 }
コード例 #26
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 public void AddServiceHostRestJson(Type serviceType, MessageSize messageSize)
 {
     AddServiceHostRestJson(serviceType, null, null, messageSize);
 }
コード例 #27
0
        public static string AddServiceHostNetTcp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined, int port = -1)
        {
            // Before we do anything else, we start looking for optional parameters and setting appropriate defaults
            if (contractType == null) contractType = GetContractTypeFromServiceType(serviceType);
            if (serviceId == null) serviceId = contractType.Name;
            if (messageSize == MessageSize.Undefined) messageSize = GetMessageSize(contractType.Name);

            // Starting our regular method
            var baseAddress = BaseUrl;
            if (string.IsNullOrEmpty(baseAddress)) throw new Core.Exceptions.NullReferenceException("Static BaseUrl property must be set on the ServiceGarden class before the garden can be populated.");
            if (BasePort == -1) throw new Core.Exceptions.NullReferenceException("Static BasePort property must be set on the ServiceGarden class before the garden can be populated.");
            if (port == -1)
            {
                port = BasePort;
                port += _portOffset;
                _portOffset++;
            }
            var path = BasePath;
            if (!string.IsNullOrEmpty(path) && !path.EndsWith("/")) path += "/";
            var serviceFullAddress = "net.tcp://" + baseAddress + ":" + port + "/" + path + serviceId;
            var serviceNamespace = GetServiceNamespace(serviceType, contractType);

            var addresses = new[] { new Uri(serviceFullAddress) };
            var host = CreateServiceHost(serviceType, contractType, addresses);

            // Binding needed
            var binding = new NetTcpBinding(SecurityMode.None) { SendTimeout = new TimeSpan(0, 10, 0) };
            if (!string.IsNullOrEmpty(serviceNamespace)) binding.Namespace = serviceNamespace;
            ServiceHelper.ConfigureMessageSizeOnNetTcpBinding(messageSize, binding);

            // Endpoint configuration
            if (BeforeEndpointAdded != null)
            {
                var endpointAddedArgs = new EndpointAddedEventArgs {Binding = binding, ContractType = contractType, ServiceFullAddress = serviceFullAddress};
                BeforeEndpointAdded(null, endpointAddedArgs);
                serviceFullAddress = endpointAddedArgs.ServiceFullAddress;
            }
            var endpoint = host.AddServiceEndpoint(contractType, binding, serviceFullAddress);
            if (!string.IsNullOrEmpty(serviceNamespace) && endpoint.Contract != null && endpoint.Contract.Namespace != serviceNamespace) endpoint.Contract.Namespace = serviceNamespace;

            var serviceKey = serviceFullAddress;
            if (Hosts.ContainsKey(serviceKey))
            {
                if (Hosts[serviceKey].Host.State == CommunicationState.Opened)
                {
                    try
                    {
                        Hosts[serviceKey].Host.Close();
                    }
                    catch { } // Nothing we can do
                }
                Hosts.Remove(serviceKey);
            }

            // We check whether the service we host has a custom service behavior attribute. If not, we make it a per-call service
            var customAttributes = serviceType.GetCustomAttributes(typeof(ServiceBehaviorAttribute), true);
            if (customAttributes.Length == 0) // No explicitly set behavior attribute found
            {
                var serviceBehaviorFound = false;
                foreach (var behavior in host.Description.Behaviors)
                {
                    var serviceBehavior = behavior as ServiceBehaviorAttribute;
                    if (serviceBehavior != null)
                    {
                        serviceBehavior.InstanceContextMode = InstanceContextMode.PerCall;
                        serviceBehaviorFound = true;
                        break;
                    }
                }
                if (!serviceBehaviorFound)
                    host.Description.Behaviors.Add(new ServiceBehaviorAttribute { InstanceContextMode = InstanceContextMode.PerCall });
            }

            // If needed, we fire the static event, so people can tie into this to programmatically manipulate the host or binding if need be);
            if (BeforeHostAdded != null) BeforeHostAdded(null, new HostAddedEventArgs
                                                       {
                                                           Host = host,
                                                           ServiceFullAddress = serviceFullAddress,
                                                           Binding = binding,
                                                           ContractType = contractType,
                                                           MessageSize = messageSize,
                                                           ServiceId = serviceId,
                                                           ServiceType = serviceType
                                                       });

            lock (Hosts)
                Hosts.Add(serviceKey, new HostWrapper(host, serviceFullAddress));

            return StartService(serviceKey);
        }
コード例 #28
0
        /// <summary>
        /// Adds another service to the list of hosted services
        /// </summary>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="messageSize">Size of the message.</param>
        public void AddServiceHostNetTcp(Type serviceType, MessageSize messageSize)
        {
            var contractType = serviceType.GetInterfaces()[0];

            AddServiceHostNetTcp(serviceType, contractType, contractType.Name, messageSize);
        }
コード例 #29
0
 public static string TryAddServiceHostNetTcp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined)
 {
     try
     {
         var url = AddServiceHostNetTcp(serviceType, contractType, serviceId, messageSize);
         if (contractType == null) contractType = GetContractTypeFromServiceType(serviceType);
         if (!string.IsNullOrEmpty(url))
         {
             var logText = "Successfully started Net.Tcp Service '" + serviceType + "' (contract: '" + contractType + "').\r\n\r\nFull URL: " + url;
             logText += "\r\nMessage Size: " + messageSize;
             LoggingMediator.Log(logText);
             
         }
         else
             LoggingMediator.Log("Error starting Net.Tcp Service '" + serviceType + "' (contract: '" + contractType + "').", LogEventType.Error);
         return url;
     }
     catch (Exception ex)
     {
         if (contractType == null) contractType = GetContractTypeFromServiceType(serviceType);
         LoggingMediator.Log("Error starting Net.Tcp Service '" + serviceType + "' (contract: '" + contractType + "').", ex, LogEventType.Error);
         return string.Empty;
     }
 }
コード例 #30
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 /// <param name="exposeWsdl">if set to <c>true</c> [expose WSDL].</param>
 public void AddServiceHostBasicHttp(Type serviceType, MessageSize messageSize, bool exposeWsdl)
 {
     AddServiceHostBasicHttp(serviceType, null, null, messageSize, exposeWsdl);
 }
コード例 #31
0
 public static string TryAddServiceHostBasicHttp(Type serviceType, Type contractType, MessageSize messageSize, bool exposeWsdl, string baseAddress, string basePath)
 {
     return TryAddServiceHostBasicHttp(serviceType, contractType, null, messageSize, exposeWsdl, baseAddress, basePath);
 }
コード例 #32
0
 /// <summary>Hosts a Basic HTTP service</summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="contractType">Type of the contract.</param>
 /// <param name="serviceId">The service id.</param>
 /// <param name="messageSize">Size of the message.</param>
 /// <param name="exposeWsdl">if set to <c>true</c> a WSDL endpoint is exposed.</param>
 /// <param name="baseAddress">The base address.</param>
 /// <param name="basePath">The base path.</param>
 /// <param name="extension">The extension.</param>
 /// <param name="useHttps">Indicates whether HTTPS should be used</param>
 public void AddServiceHostBasicHttp(Type serviceType, Type contractType = null, string serviceId = null, MessageSize messageSize = MessageSize.Undefined, bool exposeWsdl = false, string baseAddress = null, string basePath = null, string extension = null, bool useHttps = false)
 {
     Execute(
         () => ServiceGarden.AddServiceHostBasicHttp(serviceType, contractType, serviceId, messageSize, exposeWsdl, baseAddress, basePath, extension, useHttps),
         url => AddServiceInfo(serviceType, contractType, url, "Basic HTTP", ServiceGarden.GetHostByEndpointAddress(url))
         );
 }
コード例 #33
0
 /// <summary>
 /// Adds another service to the list of hosted services
 /// </summary>
 /// <param name="serviceType">Type of the service.</param>
 /// <param name="messageSize">Size of the message.</param>
 /// <param name="exposeWsdl">if set to <c>true</c> [expose WSDL].</param>
 public void AddServiceHostWsHttp(Type serviceType, MessageSize messageSize, bool exposeWsdl)
 {
     var contractType = serviceType.GetInterfaces()[0];
     AddServiceHostWsHttp(serviceType, contractType, contractType.Name, messageSize, exposeWsdl);
 }