Esempio n. 1
0
        void t_Elapsed(object sender, ElapsedEventArgs e)
        {
            var level = (LogEventLevel) new Random().Next(0, 5);

            switch (level)
            {
            case LogEventLevel.Verbose:
                Composable.GetExport <IXLogger>().Verbose("This is a Serilog.Sinks.XSockets test with level {0}", level);
                break;

            case LogEventLevel.Debug:
                Composable.GetExport <IXLogger>().Debug("This is a Serilog.Sinks.XSockets test with level {0}", level);
                break;

            case LogEventLevel.Information:
                Composable.GetExport <IXLogger>().Information("This is a Serilog.Sinks.XSockets test with level {0}", level);
                break;

            case LogEventLevel.Warning:
                Composable.GetExport <IXLogger>().Warning("This is a Serilog.Sinks.XSockets test with level {0}", level);
                break;

            case LogEventLevel.Error:
                Composable.GetExport <IXLogger>().Error("This is a Serilog.Sinks.XSockets test with level {0}", level);
                break;

            case LogEventLevel.Fatal:
                Composable.GetExport <IXLogger>().Fatal("This is a Serilog.Sinks.XSockets test with level {0}", level);
                break;
            }
        }
Esempio n. 2
0
        public override async Task HandShake(byte[] ar)
        {
            var rawHandshake = Encoding.UTF8.GetString(ar, 0, ar.Length);

            var identifiedProtocol = GetProtocolFromHandshake(ar);

            if (identifiedProtocol != null && identifiedProtocol is HyperTextTransferProtocol)
            {
                //Get the instance of the identified protocol
                var http = (HyperTextTransferProtocol)await identifiedProtocol.Resolve(ar, Transport, Configuration);

                var path = http.Handshake.Split(' ');

                if (path[0] == "GET" && path[1] == "/")
                {
                    Composable.GetExport <IXLogger>().Information("ProtocolHandshakeHandler - Handshake OK: {h}", rawHandshake);
                    var success = await Transport.Send(NOCONTENT);

                    await http.Disconnect(false);
                }
                else
                {
                    await base.HandShake(ar);
                }
                return;
            }
            else
            {
                await base.HandShake(ar);
            }
        }
Esempio n. 3
0
        public override async Task <byte[]> GetHostResponse()
        {
            try
            {
                var connectMessage = MqttHelpers.Parse((byte)MqttProtocolVersion.Version_3_1_1, this.RawHandshake);
                //var connectMessage = MqttMsgConnect.Parse((byte)MqttProtocolVersion.Version_3_1_1, this.RawHandshake);
                this.ConnectionContext.Environment = new Dictionary <string, object>();
                this.ConnectionContext.Environment.Add("mqttclient", connectMessage);
                ConnectionContext.User = _authenticationPipeline.GetPrincipal(this);

                Broker.MqttOpen(connectMessage);
                await Broker.Open();

                return(new byte[0]);
            }
            catch (Exception ex)
            {
                // 3.1.4.2 -  The Server MUST validate that the CONNECT Packet conforms to section 3.1
                // and close the Network Connection without sending a CONNACK if it does not conform
                Composable.GetExport <IXLogger>().Error(ex, "MQTT CONNECT FAILED");
                await Disconnect(false);

                return(new byte[0]);
            }
        }
Esempio n. 4
0
        public static void StartOnAzure(this IXSocketServerContainer container)
        {
            //Configurations
            var configs           = new List <IConfigurationSetting>();
            var uriStr            = RoleEnvironment.GetConfigurationSettingValue("uri");
            var origins           = new HashSet <string>(RoleEnvironment.GetConfigurationSettingValue("origin").Split(',').ToList());
            var instanceEndpoints =
                RoleEnvironment.CurrentRoleInstance.InstanceEndpoints.Values.Where(p => p.Protocol.Equals("tcp"));

            //Create endpoints
            foreach (var endpoint in instanceEndpoints)
            {
                var uri = new Uri(uriStr.Replace("port", endpoint.IPEndpoint.Port.ToString(CultureInfo.InvariantCulture)));
                configs.Add(new ConfigurationSetting(uri, origins)
                {
                    Endpoint = endpoint.IPEndpoint
                });
                Composable.GetExport <IXLogger>().Information("Endpoint {@endpoint}", endpoint);
            }

            if (!configs.Any())
            {
                Composable.GetExport <IXLogger>().Fatal("Could not find a TCP endpoint, check your configuration");
                return;
            }

            //Start server with endpoints
            container.Start(false, configurationSettings: configs);
        }
Esempio n. 5
0
 /// <inheritdoc />
 protected override Task ExecuteAsync(CancellationToken _)
 => Composable
 .Add(crawlEnginePhase.ExecuteAsync)
 .Add(normalizationEnginePhase.ExecuteAsync)
 .Add(indexingEnginePhase.ExecuteAsync)
 .Add(algorithmEnginePhase.ExecuteAsync)
 .Invoke(Unit.Instance);
Esempio n. 6
0
 static void Main(string[] args)
 {
     using (var container = Composable.GetExport <IXSocketServerContainer>())
     {
         container.Start();
         Console.ReadLine();
     }
 }
Esempio n. 7
0
 public override async Task OnMessage(IMessage message)
 {
     if (Debugger.IsAttached)
     {
         Composable.GetExport <IXLogger>().Verbose("MyController:OnMessage {@m}", message);
     }
     await this.InvokeToAll(message);
 }
Esempio n. 8
0
 public MqttProtocol()
 {
     Broker = new MqttController
     {
         ProtocolInstance = this,
     };
     ProtocolProxy           = new MqttProtocolProxy();
     _authenticationPipeline = Composable.GetExport <IXSocketAuthenticationPipeline>();
 }
Esempio n. 9
0
 static void Main(string[] args)
 {
     using (WebApp.Start <Startup>("http://localhost:12345"))
     {
         Composable.GetExport <IXLogger>().Information("All files under Sample/Web should have the property 'Copy to output directory' set to 'Copy always'");
         Console.WriteLine("Navigate to: http://localhost:12345/Sample/Web/Stockticker.html");
         Console.ReadLine();
     }
 }
Esempio n. 10
0
    public StorageObject(string partitiokKey, string rowKey, object o)
    {
        this.PartitionKey = partitiokKey;
        this.RowKey       = rowKey;
        var t = o.GetType();

        this.Type = string.Format("{0}, {1}", t.FullName, Assembly.GetAssembly(t).GetName().Name);
        this.JSON = Composable.GetExport <IXSocketJsonSerializer>().SerializeToString(o, o.GetType());
    }
Esempio n. 11
0
        /// <summary>
        /// The handshake should contain Sec-WebSocket-Version:\13
        /// The handshake should NOT contain any subprotocol
        /// </summary>
        /// <param name="handshake"></param>
        /// <returns></returns>
        public override async Task <bool> Match(IList <byte> handshake)
        {
            var s = Encoding.UTF8.GetString(handshake.ToArray());

            Composable.GetExport <IXLogger>().Information(s);
            return
                (Regex.Match(s, @"(^Sec-WebSocket-Version:\s13)", RegexOptions.Multiline).Success
                 &&
                 Regex.Match(s, @"(^Sec-WebSocket-Protocol:\sNative)", RegexOptions.Multiline).Success);
        }
Esempio n. 12
0
        public override bool OnStart()
        {
            bool result = base.OnStart();

            //Get the server container
            _container = Composable.GetExport <IXSocketServerContainer>();
            //Start in worker role
            _container.StartOnAzure();

            return(result);
        }
Esempio n. 13
0
 static void Main(string[] args)
 {
     using (var container = Composable.GetExport <IXSocketServerContainer>())
     {
         Composable.GetExport <IXSocketsScaleOut>().AddScaleOut("ws://127.0.0.1:4503");
         Composable.GetExport <IXSocketsScaleOut>().AddScaleOut("ws://127.0.0.1:4504");
         Composable.GetExport <IXSocketsScaleOut>().AddScaleOut("ws://127.0.0.1:4505");
         container.Start();
         Console.ReadLine();
     }
 }
Esempio n. 14
0
        protected void Application_Start()
        {
            // Start the MVC->XSockets bridge
            _container = Composable.GetExport <IXSocketsRelayContainer>();
            _container.Start();

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Esempio n. 15
0
        public override bool OnStart()
        {
            bool result = base.OnStart();

            // Use the XSockets.NET Plugin Framwork to get an IXSocketServerContainer
            _container = Composable.GetExport <IXSocketServerContainer>();

            //Start server by using extension (see ConfigurationHelper)
            _container.StartOnAzure();

            return(result);
        }
Esempio n. 16
0
 /// <summary>
 /// Convert the incoming data to an IMessage of with correct type (text/binary)
 /// </summary>
 /// <param name="payload"></param>
 /// <param name="messageType"></param>
 /// <returns></returns>
 public override IMessage OnIncomingFrame(IEnumerable <byte> payload, MessageType messageType)
 {
     Composable.GetExport <IXLogger>().Information("Native Websockets {p}", Encoding.UTF8.GetString(payload.ToArray()));
     if (messageType == MessageType.Binary)
     {
         return(new Message(payload, "bar", "foo"));
     }
     else
     {
         return(new Message(Encoding.UTF8.GetString(payload.ToArray()), "bar", "foo"));
     }
 }
Esempio n. 17
0
        public MqttManager()
        {
            // create managers (publisher, subscriber, session and UAC)
            this.subscriberManager = new MqttSubscriberManager();
            this.sessionManager    = new MqttSessionManager();
            this.publisherManager  = new MqttPublisherManager(this.subscriberManager, this.sessionManager);
            this.uacManager        = new MqttUacManager();

            this.clients = new MqttClientCollection();

            mqttBridge = Composable.GetExport <IMqttBridge>();
        }
Esempio n. 18
0
        /// <summary>
        /// When the controller is openend by the client it sends back information about all the connected sensors.
        /// </summary>
        public override async Task OnOpened()
        {
            //Send back containerId so see if we are on different servers when scaling
            await this.Invoke(Composable.GetExport <IXSocketServerContainer>().ContainerId, "containerid");

            //Default temp limit
            this.TempLimit = 10;
            //Find all sensors and get latest known value and name
            var sensors = this.FindOn <Sensor>().Select(p => p.SensorInfo);

            //Send back sensor information
            await this.Invoke(sensors, "sensors");
        }
Esempio n. 19
0
        /// <summary>
        /// Set Composable.
        /// </summary>
        public static void SetComposable(this IExtendable resource,
                                         Composable composableValue)
        {
            switch (resource)
            {
            case StructureDefinition sDef: break;

            case ElementDefinition eDef: break;

            default: throw new Exception($"Can only set composable on an element definition");
            }

            resource.AddExtension(ComposableExtensionUri, new FhirString(composableValue.ToString()));
        }
Esempio n. 20
0
        /// <summary>
        /// When a client connects create a new PeerConnection and send the information the the client
        /// </summary>
        public override async Task OnOpened()
        {
            var groupId = Guid.NewGuid();

            if (this.HasParameterKey("grouppeer"))
            {
                var p = this.GetParameter("grouppeer");
                groupId      = Guid.Parse(p);
                this.GroupId = groupId;
            }

            // Get the context from a parameter if it exists
            var context = Guid.NewGuid();

            if (this.HasParameterKey("ctx"))
            {
                var p = this.GetParameter("ctx");
                context        = Guid.Parse(p);
                this.ContextId = context;
            }

            IPresence user = new Presence {
                Online = true, UserName = "******", GroupId = groupId, Context = context, Id = this.PersistentId
            };

            //Update user
            if (XSockets.Core.Utility.Storage.Repository <Guid, IPresence> .ContainsKey(this.PersistentId))
            {
                user = XSockets.Core.Utility.Storage.Repository <Guid, IPresence> .GetById(user.Id);

                if (this.HasParameterKey("username"))
                {
                    user.UserName = this.GetParameter("username");
                }
            }
            SavePresence(user);
            var others = XSockets.Core.Utility.Storage.Repository <Guid, IPresence> .Find(p => p.Id != user.Id);

            Composable.GetExport <IXLogger>().Information("Others {@a}", others);
            await this.Invoke(others, "allusers");

            Peer = new PeerConnection
            {
                Context = context,
                PeerId  = ConnectionId,
                GroupId = groupId
            };

            await this.Invoke(Peer, Events.Context.Created);
        }
Esempio n. 21
0
 /// <summary>
 /// Log the incomming data and send it back to the caller only
 /// </summary>
 /// <param name="model"></param>
 public void LogTest(SomeModel model)
 {
     try
     {
         //Get the logger and write with level information
         Composable.GetExport <IXLogger>().Information("LogTest: {@model}", model);
         //And... throw...
         throw new Exception("Ohh crap!");
     }
     catch (Exception ex)
     {
         Composable.GetExport <IXLogger>().Error("LogTest: {@ex}", ex);
     }
 }
        /// <summary>
        /// When a client connects create a new PeerConnection and send the information the the client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="onClientConnectArgs"></param>
        private void _OnOpen(object sender, OnClientConnectArgs onClientConnectArgs)
        {
            IPresence user = new Presence {
                Online = true, UserName = "******", Id = this.PersistentId
            };

            //Update user
            if (Core.Utility.Storage.Repository <Guid, IPresence> .ContainsKey(this.PersistentId))
            {
                user = Core.Utility.Storage.Repository <Guid, IPresence> .GetById(user.Id);

                if (this.HasParameterKey("username"))
                {
                    user.UserName = this.GetParameter("username");
                }
            }
            SavePresence(user);
            var others = Core.Utility.Storage.Repository <Guid, IPresence> .Find(p => p.Id != user.Id);

            Composable.GetExport <IXLogger>().Information("Others {@a}", others);
            this.Invoke(others, "allusers");

            // Get the context from a parameter if it exists
            var context = Guid.NewGuid();

            if (this.HasParameterKey("ctx"))
            {
                var p = this.GetParameter("ctx");
                context = Guid.Parse(p);
            }

            Peer = new PeerConnection
            {
                Context = context,
                PeerId  = ConnectionId
            };

            this.Invoke(Peer, Events.Context.Created);
        }
Esempio n. 23
0
 public static bool TryParse(string text, out Validator result)
 {
     return(Composable.TryParse(text, out result));
 }
Esempio n. 24
0
 public StupidProtocolProxy()
 {
     JsonSerializer = Composable.GetExport <IXSocketJsonSerializer>();
 }
Esempio n. 25
0
 public static Validator Parse(string text)
 {
     return((Validator)Composable.Parse(typeof(Validator), text));
 }
Esempio n. 26
0
        protected void Application_Start()
        {
            Container container = new Container();

            IoC.Configure(container);
            //RouteTable.Routes.MapHubs();
            //assign instrumentation key to appinsights
            Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = System.Web.Configuration.WebConfigurationManager.AppSettings["iKey"];
            ControllerBuilder.Current.SetControllerFactory(typeof(SmarttouchControllerFactory));
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //ControllerBuilder.Current.SetControllerFactory(typeof(SmarttouchControllerFactory));
            InitializeAutoMapper.Initialize();
            //GlobalConfiguration.Configuration.EnsureInitialized();
            HttpContext.Current.Application["image_hostedpath"] = ConfigurationManager.AppSettings["IMAGE_HOSTING_SERVICE_URL"];
            HttpContext.Current.Application["webservice_url"]   = ConfigurationManager.AppSettings["WEBSERVICE_URL"];
            Logger.Current.CreateRollingFlatFileListener(EventLevel.Verbose, ConfigurationManager.AppSettings["WEBAPP_LOG_FILE_PATH"], 2048);
            ExceptionHandler.Current.AddDefaultLogAndRethrowPolicy();
            ExceptionHandler.Current.AddDefaultLogOnlyPolicy();
            i18n.LocalizedApplication.Current.DefaultLanguage = "en";
            i18n.UrlLocalizer.UrlLocalizationScheme           = i18n.UrlLocalizationScheme.Void;

            var defaultJsonFactory = ValueProviderFactories.Factories.OfType <JsonValueProviderFactory>().FirstOrDefault();
            var index = ValueProviderFactories.Factories.IndexOf(defaultJsonFactory);

            ValueProviderFactories.Factories.Remove(defaultJsonFactory);
            ValueProviderFactories.Factories.Insert(index, new SmartTouchJsonValueProviderFactory());

            bool   isHttpsMode = false;
            string httpsMode   = System.Configuration.ConfigurationManager.AppSettings["IsHttpsMode"];

            bool.TryParse(httpsMode, out isHttpsMode);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            var masterAccountDns = ConfigurationManager.AppSettings["MASTER_ACCOUNT_DNS"];

            if (masterAccountDns.Equals("localhost"))
            {
                using (var socketServerContainer = Composable.GetExport <IXSocketServerContainer>())
                {
                    socketServerContainer.StartServers();
                }
            }
            else
            {
                using (var socketServerContainer = Composable.GetExport <IXSocketServerContainer>())
                {
                    IList <IConfigurationSetting> configurationSettings = new List <IConfigurationSetting>();
                    //string uri = string.Empty;
                    IConfigurationSetting configSetting = null;
                    Uri uri = null;

                    if (isHttpsMode)
                    {
                        string sslKey = System.Configuration.ConfigurationManager.AppSettings["SSLSerialNumber"];

                        uri = new Uri("wss://" + ConfigurationManager.AppSettings["MASTER_ACCOUNT_DNS"]
                                      + ":" + ConfigurationManager.AppSettings["WEBSOCKET_PORT"]);

                        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                        store.Open(OpenFlags.ReadOnly);

                        var certificate = store.Certificates.Find(X509FindType.FindBySerialNumber, sslKey, false).OfType <X509Certificate2>().FirstOrDefault();
                        if (certificate != null)
                        {
                            Logger.Current.Informational("certificate found");
                            configSetting = new ConfigurationSetting
                            {
                                Port   = uri.Port,
                                Origin = new HashSet <string>()
                                {
                                    "*"
                                },
                                Uri         = uri,
                                Certificate = certificate
                            };
                            Logger.Current.Informational("Configured was mode for websockets.");
                        }
                        else
                        {
                            Logger.Current.Informational("certificate not found");
                            foreach (X509Certificate2 objCert in store.Certificates)
                            {
                                string serialNumber = objCert.SerialNumber.Trim().ToString().ToUpper();
                                Logger.Current.Verbose("Certificate name" + objCert.FriendlyName + " Store serial number:" + objCert.SerialNumber.Trim());
                                string orgSerialNumber = sslKey.Trim().ToString().ToUpper();
                                if (String.Equals(serialNumber, orgSerialNumber, StringComparison.InvariantCulture))
                                {
                                    certificate = objCert;
                                }
                            }
                            if (certificate != null)
                            {
                                Logger.Current.Informational("Certificate found.");
                                configSetting = new ConfigurationSetting
                                {
                                    Port   = uri.Port,
                                    Origin = new HashSet <string>()
                                    {
                                        "*"
                                    },
                                    Uri         = uri,
                                    Certificate = certificate
                                };
                                Logger.Current.Informational("Configured wss mode for websockets.");
                            }
                            else
                            {
                                Logger.Current.Informational("Certificate not found. Could not set wss for the application.");
                            }
                        }
                    }
                    else
                    {
                        uri = new Uri("ws://" + ConfigurationManager.AppSettings["MASTER_ACCOUNT_DNS"]
                                      + ":" + ConfigurationManager.AppSettings["WEBSOCKET_PORT"]);
                        configSetting = new ConfigurationSetting(uri);
                        Logger.Current.Informational("Configured ws mode for websockets.");
                    }

                    configurationSettings.Add(configSetting);
                    socketServerContainer.StartServers(withInterceptors: true, configurationSettings: configurationSettings);
                }
            }
        }
Esempio n. 27
0
 public override async Task <IMessage> OnOutgoingMessage(IXSocketController controller, IMessage e)
 {
     Composable.GetExport <IXLogger>().Information("Outgoing data: {@m}", e);
     return(await base.OnOutgoingMessage(controller, e));
 }
Esempio n. 28
0
 public override async Task OnIncomingMessage(IXSocketController controller, IMessage e)
 {
     Composable.GetExport <IXLogger>().Information("Incoming data: {@m}", e);
     await base.OnIncomingMessage(controller, e);
 }
Esempio n. 29
0
 public void MqttOpen(MqttMsgConnect msg)
 {
     MqttClient = new MqttClient(this.ProtocolInstance.Transport.Socket);
     ((MqttManager)Composable.GetExport <IXSocketController>(typeof(MqttManager))).RegisterClient(this.MqttClient, msg);
 }
Esempio n. 30
0
 public object Deserialize()
 {
     return(Composable.GetExport <IXSocketJsonSerializer>().DeserializeFromString(this.JSON, System.Type.GetType(Type)));
 }