void Awake(){
		instance = this;
		if (!PhotonNetwork.connected)
			PhotonNetwork.ConnectUsingSettings("v1.0"); // version of the game/demo. used to separate older clients from newer ones (e.g. if incompatible)
		
		//PhotonNetwork.playerName = PlayerPrefs.GetString("playerName", "Guest" + Random.Range(1, 9999));
	}
        public void Initialize(ConnectionManager connectionManager, IServiceProvider serviceProvider)
        {
            this._connectionManager = connectionManager;
            this._serviceProvider = serviceProvider;

            ConfigureControlsFromConnectionManager();
        }
示例#3
0
        private static async Task RunClientAsync(Uri address, CancellationToken token)
        {
            ClientEventSource eventSource = ClientEventSource.Instance;

            NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
            binding.OpenTimeout = TimeSpan.FromSeconds(1.0d);
            binding.SendTimeout = TimeSpan.FromSeconds(1.0d);
            binding.ReceiveTimeout = TimeSpan.FromSeconds(1.0d);
            binding.CloseTimeout = TimeSpan.FromSeconds(1.0d);

            CalculatorChannelFactory factory = new CalculatorChannelFactory(binding, new EndpointAddress(address), eventSource);
            await factory.OpenAsync();

            ConnectionManager<ICalculatorClientAsync> connectionManager = new ConnectionManager<ICalculatorClientAsync>(factory);

            using (ProxyInvoker<ICalculatorClientAsync> proxy = new ProxyInvoker<ICalculatorClientAsync>(connectionManager))
            {
                Random random = new Random();

                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        await proxy.InvokeAsync(c => InvokeRandomAsync(random, c));
                    }
                    catch (Exception)
                    {
                    }

                    await Task.Delay(TimeSpan.FromMilliseconds(250.0d));
                }
            }

            await factory.CloseAsync();
        }
示例#4
0
        public RouterActor(bool useDefault = true)
        {
            ConnectionMode connectionMode = ConnectionMode.ConnectionModeRemoteConnectionless;
            IConnectionManager connectionManager = new ConnectionManager();
            FalconConnection falconConnection = default(FalconConnection);
                            if (useDefault)
                                falconConnection = connectionManager.GetDefaultConnection();
                            else
                                falconConnection = connectionManager.GetConnection("", 1);

            _connection = ConnectionObjectFactory.CreateUnlicensedConnectionObject(null);
            _auto = new AutoDisposeConnectionObject(_connection);
            _connection.Mode = connectionMode;

            if (falconConnection.guidEdi == Guid.Empty)
                throw new Exception("Operation was aborted");
                        DeviceOpenError err = _connection.Open2("{" + falconConnection.guidEdi.ToString() + "}",
                                    falconConnection.Parameters);
            if (err != DeviceOpenError.DeviceOpenErrorNoError)
            {
                throw new InvalidOperationException(string.Format("Could not open connection: {0}", err.ToString()));
            }

            beginConfirmedGroupDataChannel();
        }
 private void newConnectionRequest(ConnectionManager.ConnectionInformation connection)
 {
     ConnectionHandeler handeler = new ConnectionHandeler(connection);
     handeler.Disconnection += serverDisconnected;
     AddConnection(handeler);
     handeler.Start();
 }
            public ConnectionItem(ConnectionManager connectionManager)
            {
                ArgumentVerifier.CheckObjectArgument(connectionManager, "connectionManager");

                this.name = connectionManager.Name;
                this.connectionManager = connectionManager;
            }
示例#7
0
        public WinSCPWrapper(ConnectionManager cm, object txn)
        {
            this.cm = cm;
            this.txn = txn;

            this.StartSession();
        }
 /// <summary>
 /// Create an instance of <see cref="IBatcher"/> according to the configuration 
 /// and the capabilities of the driver
 /// </summary>
 /// <remarks>
 /// By default, .Net doesn't have any batching capabilities, drivers that does have
 /// batching support need to override this method and return their own batcher.
 /// </remarks>
 public override IBatcher CreateBatcher(ConnectionManager connectionManager)
 {
     if (connectionManager.Factory.IsBatchUpdateEnabled)
         return new OracleDataClientBatchingBatcher(connectionManager);
     else
         return new NonBatchingBatcher(connectionManager);
 }
        public ContactRepository(ConnectionManager connectionManager)
        {
            connMgr = connectionManager;

            //Create the Contact table if it doesn't exist
            connMgr.Database.CreateEntityTable<Contact>();
        }
示例#10
0
文件: Socket.cs 项目: BjkGkh/R106
        internal static void SetupListener(int Port)
        {
            SessionManagement.Init();
			manager = new ConnectionManager(Port, 5, new HeartbeatParser(), false);

			manager.connectionEvent += manager_connectionEvent;
        }
示例#11
0
 public void CreateFileConnection(Package p)
 {
     ConMgr = p.Connections.Add("File");
     ConMgr.ConnectionString = @"\\<yourserver>\<yourfolder>\books.xml";
     ConMgr.Name = "SSIS Connection Manager for Files";
     ConMgr.Description = "Flat File connection";
 }
示例#12
0
        public override IDTSComponentMetaData100 AddDestAdapter(IDTSPipeline100 pipeline, ConnectionManager destConnMgr, out IDTSDesigntimeComponent100 destDesignTimeComp)
        {
            if (String.IsNullOrEmpty(quotedTableName))
            {
                throw new ArgumentException("Destination table name is empty");
            }
            IDTSComponentMetaData100 destComp = pipeline.ComponentMetaDataCollection.New();
            destComp.ComponentClassID = OLEDB_DEST_GUID;
            destComp.ValidateExternalMetadata = true;
            destDesignTimeComp = destComp.Instantiate();
            destDesignTimeComp.ProvideComponentProperties();
            destComp.Name = "OleDB Destination - Sql Server";
            destDesignTimeComp.SetComponentProperty("AccessMode", 0);
            destDesignTimeComp.SetComponentProperty("OpenRowset", quotedTableName);

            // set connection
            destComp.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(destConnMgr);
            destComp.RuntimeConnectionCollection[0].ConnectionManagerID = destConnMgr.ID;

            // get metadata
            destDesignTimeComp.AcquireConnections(null);
            destDesignTimeComp.ReinitializeMetaData();
            destDesignTimeComp.ReleaseConnections();

            extCols = destComp.InputCollection[0].ExternalMetadataColumnCollection;

            return destComp;
        }
示例#13
0
    public void connect(string args)
    {
        string[] javascriptArgs = JsonHelper.Deserialize<string[]>(args);
        string macAddress = javascriptArgs[0];
        connectionCallbackId = javascriptArgs[1];

        connectionManager = new ConnectionManager();
        connectionManager.Initialize(); // TODO can't we put this in the constructor?
        connectionManager.ByteReceived += connectionManager_ByteReceived;

        connectionManager.ConnectionSuccess += connectionManager_ConnectionSuccess;
        connectionManager.ConnectionFailure += connectionManager_ConnectionFailure;

        try
        {
            HostName deviceHostName = new HostName(macAddress);
            connectionManager.Connect(deviceHostName);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            connectionManager_ConnectionFailure("Invalid Hostname");
        }

    }
        /// <summary>
        /// Constructor. Inicializa instancias de la clase ConnectionManagerTester
        /// </summary>
        public ConnectionManagerTester()
        {
            /*
             * Primero se crea el CommandManager. Este gestiona los comandos de
             * sistema como alive, busy, ready, etc. Ahorra trabajo.
             * Adicionalmente se suscriben los eventos (apuntador a funcion)
             * para manejar las notificaciones de la clase
            */
            commandManager = new CommandManager();
            commandManager.Started += new CommandManagerStatusChangedEventHandler(commandManager_Started);
            commandManager.Stopped += new CommandManagerStatusChangedEventHandler(commandManager_Stopped);
            commandManager.CommandReceived += new CommandReceivedEventHandler(commandManager_CommandReceived);
            commandManager.ResponseReceived += new ResponseReceivedEventHandler(commandManager_ResponseReceived);

            /*
             * Ahora se inicializa el ConnectionManager. Bajo el esquema actual
             * todas las aplicaciones son servidores y es el blackboard el que
             * se conecta a ellas (asi solo es necesario configurar una
             * aplicacion). Se le indica nombre del modulo, puerto de conexion
             * y el gestor de comandos. El modulo y puerto deben ser
             * configurados en el blackboard
            */
            connectionManager = new ConnectionManager("TESTER", 2000, 2000, IPAddress.Loopback, commandManager);
            connectionManager.Started += new ConnectionManagerStatusChangedEventHandler(connectionManager_Started);
            connectionManager.Stopped += new ConnectionManagerStatusChangedEventHandler(connectionManager_Stopped);
            connectionManager.ClientDisconnected += new TcpClientDisconnectedEventHandler(connectionManager_ClientDisconnected);
            connectionManager.ClientConnected += new TcpClientConnectedEventHandler(connectionManager_ClientConnected);

            // Configuro el reloj
            sw = new System.Diagnostics.Stopwatch();
        }
示例#15
0
 public AppManager(ConnectionManager connectionManager, 
     IDeviceInfo deviceInfo,
     AccountManager accountManager) : base(connectionManager)
 {
     _deviceInfo = deviceInfo;
     _accountManager = accountManager;
 }
示例#16
0
 public ConnectionRun(RunData runData)
     : base(runData)
 {
     var connectionManager = new ConnectionManager(Resolver);
     _context = connectionManager.GetConnectionContext<StressConnection>();
     _transportConnection = (ITransportConnection)_context.Connection;
 }
        void IDtsConnectionManagerUI.Initialize(ConnectionManager connectionManager, IServiceProvider serviceProvider)
        {
            Debug.Assert((connectionManager != null) && (serviceProvider != null));

            this._serviceProvider = serviceProvider;
            this._connectionManager = connectionManager;
        }
示例#18
0
        public SQLServerWrapper(ConnectionManager cm, object txn)
        {
            this.cm = cm;
            this.txn = txn;

            this.StartSession();
        }
        // Setup function
        public void Setup()
        {
            _transport = new SerialTransport {CurrentSerialSettings = {DtrEnable = false}};
            // some boards (e.g. Sparkfun Pro Micro) DtrEnable may need to be true.                        
            // We do not need to set serial port and baud rate: it will be found by the connection manager                                                           

            // Initialize the command messenger with the Serial Port transport layer
            // Set if it is communicating with a 16- or 32-bit Arduino board
            _cmdMessenger = new CmdMessenger(_transport, BoardType.Bit16)
            {
                PrintLfCr = false // Do not print newLine at end of command, to reduce data being sent
            };

            // The Connection manager is capable or storing connection settings, in order to reconnect more quickly  
            // the next time the application is run. You can determine yourself where and how to store the settings
            // by supplying a class, that implements ISerialConnectionStorer. For convenience, CmdMessenger provides
            //  simple binary file storage functionality
            var serialConnectionStorer = new SerialConnectionStorer("SerialConnectionManagerSettings.cfg");

            // We don't need to provide a handler for the Identify command - this is a job for Connection Manager.
            _connectionManager = new SerialConnectionManager(
                _transport as SerialTransport, 
                _cmdMessenger,
                (int) Command.Identify, 
                CommunicationIdentifier,
                serialConnectionStorer)
            {
                // Enable watchdog functionality.
                WatchdogEnabled = true,

                // Instead of scanning for the connected port, you can disable scanning and only try the port set in CurrentSerialSettings
                //DeviceScanEnabled = false
            };

            // Show all connection progress on command line             
            _connectionManager.Progress += (sender, eventArgs) =>
            {
                // If you want to reduce verbosity, you can only show events of level <=2 or ==1
                if (eventArgs.Level <= 3) Console.WriteLine(eventArgs.Description);
            };

            // If connection found, tell the arduino to turn the (internal) led on
            _connectionManager.ConnectionFound += (sender, eventArgs) =>
            {
                // Create command
                var command = new SendCommand((int)Command.TurnLedOn);
                // Send command
                _cmdMessenger.SendCommand(command);
            };

            //You can also do something when the connection is lost
            _connectionManager.ConnectionTimeout += (sender, eventArgs) =>
            {
                //Do something
            };

            // Finally - activate connection manager
            _connectionManager.StartConnectionManager();
        }
示例#20
0
        public ConnectionHandeling(int port, int maxConnections, int connectionsPerIP, bool enabeNagles)
        {
			this.liveConnections = new Hashtable(maxConnections);
			this.manager = new ConnectionManager(port, maxConnections, new InitialPacketParser(), !enabeNagles);
			//this.manager = new SocketManager();
			//int portID, int maxConnections, int connectionsPerIP, IDataParser parser, bool disableNaglesAlgorithm)
			//this.manager.init(port, maxConnections, connectionsPerIP, new InitialPacketParser(), !enabeNagles);
        }
示例#21
0
        public GroupsManager(MessagesManager messagesManager, ConnectionManager connectionManager, GroupChatsService groupChatsService)
        {
            this.messagesManager = messagesManager;
            this.connectionManager = connectionManager;
            this.groupChatsService = groupChatsService;

            groupChatsService.GroupChanged += OnGroupChanged;
        }
 public void ShouldLeaveOpenConnectionOpen()
 {
     DbConnection connection = Substitute.For<DbConnection>();
     connection.State.Returns(ConnectionState.Open);
     ConnectionManager manager = new ConnectionManager(connection);
     manager.Dispose();
     connection.Received(0).Close();
 }
        public RabbitMQConnectionManagerUIForm(Microsoft.SqlServer.Dts.Runtime.ConnectionManager connectionManager, IServiceProvider serviceProvider)
            : this()
        {
            this.connectionManager = connectionManager;
              this.serviceProvider = serviceProvider;

              SetFormValuesFromConnectionManager();
        }
示例#24
0
 internal BuildManager(GlobalManager globalManager)
 {
     _globalManager = globalManager;
     _connectionManager = new ConnectionManager(globalManager);
     _colorManager = new ColorManager(globalManager);
     _sizeManager = new SizeManager(globalManager);
     _jsonTreeManager = new JsonTreeManager(globalManager);
 }
示例#25
0
 public EzConnectionManager(EzPackage parent) 
 {
     if (parent == null)
         throw new ArgumentNullException("parent");
     m_parent = parent; 
     m_conn = parent.Connections.Add(GetConnMgrID());
     Name = GetType().Name + ID;
 }
示例#26
0
 private void appStartup(object sender, StartupEventArgs e)
 {
     // create connection manager
     connectionManager = new ConnectionManager();
     // create main window and display it
     mainWindow = new MainWindow();
     mainWindow.Show();
 }
示例#27
0
        public ChatManager(ConnectionManager connectionManager, ChatServiceProxy chatServiceProxy, AccountManager accountManager)
            : base(connectionManager)
        {
            _chatServiceProxy = chatServiceProxy;
            _accountManager = accountManager;

            Messages = new ObservableCollection<Event>();
            OnlineUsers = new ObservableCollection<UserDto>();
        }
 public void ShouldOpenAndCloseClosedConnection()
 {
     DbConnection connection = Substitute.For<DbConnection>();
     connection.State.Returns(ConnectionState.Closed);
     ConnectionManager manager = new ConnectionManager(connection);
     manager.Dispose();
     connection.Received(1).Open();
     connection.Received(1).Close();
 }
示例#29
0
 // Class definition for OLE DB Provider.
 public void CreateOLEDBConnection(Package p)
 {
     ConMgr = p.Connections.Add("OLEDB");
     ConMgr.ConnectionString = "Provider=SQLOLEDB.1;" +
       "Integrated Security=SSPI;Initial Catalog=AdventureWorks;" +
       "Data Source=(local);";
     ConMgr.Name = "SSIS Connection Manager for OLE DB";
     ConMgr.Description = "OLE DB connection to the AdventureWorks database.";
 }
示例#30
0
        public MainWindow()
        {
            InitializeComponent();
            // uloz si odkaz na connection manager z aplikace
            OracleAdmin app = Application.Current as OracleAdmin;
            connectionMgr = app.ConnectionManager;

            masterView.ItemsSource = new CompositeCollection(2) { connectionMgr };
        }
示例#31
0
 public ClienteService(string connectionString)
 {
     conexion = new ConnectionManager(connectionString);
     repositorio = new ClienteRepository(conexion);
 }
示例#32
0
        public object Get(GetConnnectionManager request)
        {
            var xml = ConnectionManager.GetServiceXml(Request.Headers.ToDictionary());

            return(_resultFactory.GetResult(Request, xml, XMLContentType));
        }
 private void AddFavorite(IPEndPoint endPoint)
 {
     try
     {
         string serverName     = endPoint.Address.ToString();
         string connectionName = serverName;
         FavoriteConfigurationElement newFavorite = FavoritesFactory.CreateNewFavorite(connectionName, serverName,
                                                                                       typeof(RDPConnection)
                                                                                       .GetProtocolName(),
                                                                                       ConnectionManager.GetPort(
                                                                                           typeof(RDPConnection)
                                                                                           .GetProtocolName()));
         this.AddFavoriteToDiscovered(newFavorite);
     }
     catch (Exception e)
     {
         Log.Error("Add Favorite Error", e);
     }
 }
示例#34
0
        private static SqlDataAdapter InicializarAdaptador()
        {
            String getSQL    = "dbo.invGetLote";
            String InsertSQL = "[dbo].[invUpdateLote]";
            String UpdateSQL = "[dbo].[invUpdateLote]";
            String DeleteSQL = "[dbo].[invUpdateLote]";

            try
            {
                SqlDataAdapter oAdaptador = new SqlDataAdapter()
                {
                    SelectCommand = new SqlCommand(getSQL, ConnectionManager.GetConnection()),
                    InsertCommand = new SqlCommand(InsertSQL, ConnectionManager.GetConnection()),
                    UpdateCommand = new SqlCommand(UpdateSQL, ConnectionManager.GetConnection()),
                    DeleteCommand = new SqlCommand(DeleteSQL, ConnectionManager.GetConnection())
                };

                //Paremetros Select
                oAdaptador.SelectCommand.CommandType = CommandType.StoredProcedure;
                oAdaptador.SelectCommand.Parameters.Add("@IDLote", SqlDbType.Int).SourceColumn             = "IDLote";
                oAdaptador.SelectCommand.Parameters.Add("@IDProducto", SqlDbType.Int).SourceColumn         = "IDProducto";
                oAdaptador.SelectCommand.Parameters.Add("@LoteInterno", SqlDbType.NVarChar).SourceColumn   = "LoteInterno";
                oAdaptador.SelectCommand.Parameters.Add("@LoteProveedor", SqlDbType.NVarChar).SourceColumn = "LoteProveedor";



                //Paremetros Insert
                oAdaptador.InsertCommand.CommandType = CommandType.StoredProcedure;
                oAdaptador.InsertCommand.Parameters.Add("@Operacion", SqlDbType.NChar).Value               = "I";
                oAdaptador.InsertCommand.Parameters.Add("@IDLote", SqlDbType.Int).SourceColumn             = "IDLote";
                oAdaptador.InsertCommand.Parameters.Add("@IDProducto", SqlDbType.Int).SourceColumn         = "IDProducto";
                oAdaptador.InsertCommand.Parameters.Add("@LoteInterno", SqlDbType.NVarChar).SourceColumn   = "LoteInterno";
                oAdaptador.InsertCommand.Parameters.Add("@LoteProveedor", SqlDbType.NVarChar).SourceColumn = "LoteProveedor";
                oAdaptador.InsertCommand.Parameters.Add("@FechaVencimiento", SqlDbType.Date).SourceColumn  = "FechaVencimiento";
                oAdaptador.InsertCommand.Parameters.Add("@FechaFabricacion", SqlDbType.Date).SourceColumn  = "FechaFabricacion";
                oAdaptador.InsertCommand.Parameters.Add("@FechaIngreso", SqlDbType.DateTime).SourceColumn  = "FechaIngreso";

                //Paremetros Update
                oAdaptador.UpdateCommand.CommandType = CommandType.StoredProcedure;
                oAdaptador.UpdateCommand.Parameters.Add("@Operacion", SqlDbType.NChar).Value               = "U";
                oAdaptador.UpdateCommand.Parameters.Add("@IDLote", SqlDbType.Int).SourceColumn             = "IDLote";
                oAdaptador.UpdateCommand.Parameters.Add("@IDProducto", SqlDbType.Int).SourceColumn         = "IDProducto";
                oAdaptador.UpdateCommand.Parameters.Add("@LoteInterno", SqlDbType.NVarChar).SourceColumn   = "LoteInterno";
                oAdaptador.UpdateCommand.Parameters.Add("@LoteProveedor", SqlDbType.NVarChar).SourceColumn = "LoteProveedor";
                oAdaptador.UpdateCommand.Parameters.Add("@FechaVencimiento", SqlDbType.Date).SourceColumn  = "FechaVencimiento";
                oAdaptador.UpdateCommand.Parameters.Add("@FechaFabricacion", SqlDbType.Date).SourceColumn  = "FechaFabricacion";
                oAdaptador.UpdateCommand.Parameters.Add("@FechaIngreso", SqlDbType.DateTime).SourceColumn  = "FechaIngreso";

                //Paremetros Delete
                oAdaptador.DeleteCommand.CommandType = CommandType.StoredProcedure;
                oAdaptador.DeleteCommand.Parameters.Add("@Operacion", SqlDbType.NChar).Value               = "D";
                oAdaptador.DeleteCommand.Parameters.Add("@IDLote", SqlDbType.Int).SourceColumn             = "IDLote";
                oAdaptador.DeleteCommand.Parameters.Add("@IDProducto", SqlDbType.Int).SourceColumn         = "IDProducto";
                oAdaptador.DeleteCommand.Parameters.Add("@LoteInterno", SqlDbType.NVarChar).SourceColumn   = "LoteInterno";
                oAdaptador.DeleteCommand.Parameters.Add("@LoteProveedor", SqlDbType.NVarChar).SourceColumn = "LoteProveedor";
                oAdaptador.DeleteCommand.Parameters.Add("@FechaVencimiento", SqlDbType.Date).SourceColumn  = "FechaVencimiento";
                oAdaptador.DeleteCommand.Parameters.Add("@FechaFabricacion", SqlDbType.Date).SourceColumn  = "FechaFabricacion";
                oAdaptador.DeleteCommand.Parameters.Add("@FechaIngreso", SqlDbType.DateTime).SourceColumn  = "FechaIngreso";
                return(oAdaptador);
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#35
0
 public static void ClearDatabase(int databaseIndex)
 {
     ConnectionManager.GetServer().FlushDatabase(databaseIndex);
 }
示例#36
0
 public SocketHandeler(ConnectionManager connection)
 {
     Connection = connection;
 }
        public static async Task MyClassInitialize(TestContext testContext)
        {
            // Test script executor (create database)
            await ScriptExecutor.ExecuteScriptAsync(ConnectionManager.GetConnection("Master"),
                                                    @"
USE master
GO

IF EXISTS
(
    SELECT NAME
    FROM Sys.Databases
    WHERE Name = N'UpdateConcurrencyAsyncTest'
)
BEGIN
    DROP DATABASE UpdateConcurrencyAsyncTest
END
GO

CREATE DATABASE UpdateConcurrencyAsyncTest
GO

USE UpdateConcurrencyAsyncTest
GO

CREATE TABLE UpdateConcurrencyAsyncTest..Message(
    [MessageId] INT NOT NULL,
    [Text] VARCHAR(50),
    [RowVersion] ROWVERSION
)
GO

ALTER TABLE UpdateConcurrencyAsyncTest..Message
ADD CONSTRAINT Message_PK PRIMARY KEY (MessageId)
GO

",
                                                    "^GO");

            await ScriptExecutor.ExecuteScriptAsync(ConnectionManager.GetConnection(connectionName),
                                                    @"CREATE PROCEDURE [p_Message_Get]
    @messageId INT
AS
BEGIN

    SET NOCOUNT ON;

    SELECT
        [MessageId],
        [Text],
        [RowVersion]
    FROM [Message]
        WHERE [MessageId] = @messageId

END;
GO

CREATE PROCEDURE [dbo].[p_Message_Update]
    @messageId INT,
    @text VARCHAR(50),
    @rowVersion ROWVERSION OUTPUT
AS
BEGIN

    --SET NOCOUNT ON; If this is ON then ExecuteNonQuery returns -1!

    DECLARE @messageOutputData TABLE
    (
        [RowVersion] BINARY(8)
    );

    UPDATE UpdateConcurrencyAsyncTest..Message
    SET
        [Text] = @text
    OUTPUT
        INSERTED.[RowVersion]
        INTO @messageOutputData
    WHERE [MessageId] = @messageId
    AND [RowVersion] = @rowVersion;

    --IF @@ROWCOUNT != 1 BEGIN
        --RAISERROR('Row versions do not match.', 16, 1);
    --END

    SET @rowVersion = (SELECT
        [RowVersion]
    FROM @messageOutputData);

END;
GO

-- Insert message to modify during the test
INSERT INTO UpdateConcurrencyAsyncTest..Message
(
    [MessageId],
    [Text]
)
VALUES
(
    1,
    'Message to modify'
);

",
                                                    "^GO");
        }
示例#38
0
 public PersonaService(string connectionString)
 {
     _repositorio = new PersonaRepository(_conexion);
     _conexion    = new ConnectionManager(connectionString);
 }
示例#39
0
        protected override void Load(ContainerBuilder builder)
        {
            // IMessageConverter<IRoutingMessage>
            builder.Register(c => new RoutingMessageConverter())
            .As <Core.IMessageConverter <IRoutingMessage> >()
            .SingleInstance();

            // IRoutingPerfCounter
            builder.Register(
                c =>
            {
                Routing.PerfCounter = NullRoutingPerfCounter.Instance;
                return(Routing.PerfCounter);
            })
            .As <IRoutingPerfCounter>()
            .AutoActivate()
            .SingleInstance();

            // IRoutingUserAnalyticsLogger
            builder.Register(
                c =>
            {
                Routing.UserAnalyticsLogger = NullUserAnalyticsLogger.Instance;
                return(Routing.UserAnalyticsLogger);
            })
            .As <IRoutingUserAnalyticsLogger>()
            .AutoActivate()
            .SingleInstance();

            // IRoutingUserMetricLogger
            builder.Register(
                c =>
            {
                Routing.UserMetricLogger = NullRoutingUserMetricLogger.Instance;
                return(Routing.UserMetricLogger);
            })
            .As <IRoutingUserMetricLogger>()
            .AutoActivate()
            .SingleInstance();

            // IMessageConverter<Message>
            builder.Register(c => new DeviceClientMessageConverter())
            .As <Core.IMessageConverter <Message> >()
            .SingleInstance();

            // IMessageConverter<Twin>
            builder.Register(c => new TwinMessageConverter())
            .As <Core.IMessageConverter <Twin> >()
            .SingleInstance();

            // IMessageConverter<TwinCollection>
            builder.Register(c => new TwinCollectionMessageConverter())
            .As <Core.IMessageConverter <TwinCollection> >()
            .SingleInstance();

            // IMessageConverterProvider
            builder.Register(
                c => new MessageConverterProvider(
                    new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Message), c.Resolve <Core.IMessageConverter <Message> >() },
                { typeof(Twin), c.Resolve <Core.IMessageConverter <Twin> >() },
                { typeof(TwinCollection), c.Resolve <Core.IMessageConverter <TwinCollection> >() }
            }))
            .As <IMessageConverterProvider>()
            .SingleInstance();

            // IDeviceConnectivityManager
            builder.Register(
                c =>
            {
                var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials");
                IDeviceConnectivityManager deviceConnectivityManager = new DeviceConnectivityManager(this.connectivityCheckFrequency, TimeSpan.FromMinutes(2), edgeHubCredentials.Identity);
                return(deviceConnectivityManager);
            })
            .As <IDeviceConnectivityManager>()
            .SingleInstance();

            // IDeviceClientProvider
            builder.Register(
                c =>
            {
                IClientProvider underlyingClientProvider        = new ClientProvider();
                IClientProvider connectivityAwareClientProvider = new ConnectivityAwareClientProvider(underlyingClientProvider, c.Resolve <IDeviceConnectivityManager>());
                return(connectivityAwareClientProvider);
            })
            .As <IClientProvider>()
            .SingleInstance();

            // Task<ICloudConnectionProvider>
            builder.Register(
                async c =>
            {
                var productInfoStore               = c.Resolve <IProductInfoStore>();
                var messageConverterProvider       = c.Resolve <IMessageConverterProvider>();
                var clientProvider                 = c.Resolve <IClientProvider>();
                var tokenProvider                  = c.ResolveNamed <ITokenProvider>("EdgeHubClientAuthTokenProvider");
                var credentialsCacheTask           = c.Resolve <Task <ICredentialsCache> >();
                var edgeHubCredentials             = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials");
                var deviceScopeIdentitiesCacheTask = c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                var proxy = c.Resolve <Option <IWebProxy> >();
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await deviceScopeIdentitiesCacheTask;
                ICredentialsCache credentialsCache = await credentialsCacheTask;
                ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(
                    messageConverterProvider,
                    this.connectionPoolSize,
                    clientProvider,
                    this.upstreamProtocol,
                    tokenProvider,
                    deviceScopeIdentitiesCache,
                    credentialsCache,
                    edgeHubCredentials.Identity,
                    this.cloudConnectionIdleTimeout,
                    this.closeCloudConnectionOnIdleTimeout,
                    this.operationTimeout,
                    proxy,
                    productInfoStore);
                return(cloudConnectionProvider);
            })
            .As <Task <ICloudConnectionProvider> >()
            .SingleInstance();

            // IIdentityProvider
            builder.Register(_ => new IdentityProvider(this.iotHubName))
            .As <IIdentityProvider>()
            .SingleInstance();

            // Task<IConnectionManager>
            builder.Register(
                async c =>
            {
                var cloudConnectionProviderTask = c.Resolve <Task <ICloudConnectionProvider> >();
                var credentialsCacheTask        = c.Resolve <Task <ICredentialsCache> >();
                var identityProvider            = c.Resolve <IIdentityProvider>();
                ICloudConnectionProvider cloudConnectionProvider = await cloudConnectionProviderTask;
                ICredentialsCache credentialsCache   = await credentialsCacheTask;
                IConnectionManager connectionManager = new ConnectionManager(
                    cloudConnectionProvider,
                    credentialsCache,
                    identityProvider,
                    this.maxConnectedClients);
                return(connectionManager);
            })
            .As <Task <IConnectionManager> >()
            .SingleInstance();

            // Task<IEndpointFactory>
            builder.Register(
                async c =>
            {
                var messageConverter = c.Resolve <Core.IMessageConverter <IRoutingMessage> >();
                IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >();
                return(new EndpointFactory(connectionManager, messageConverter, this.edgeDeviceId, this.maxUpstreamBatchSize, this.upstreamFanOutFactor) as IEndpointFactory);
            })
            .As <Task <IEndpointFactory> >()
            .SingleInstance();

            // Task<RouteFactory>
            builder.Register(async c => new EdgeRouteFactory(await c.Resolve <Task <IEndpointFactory> >()) as RouteFactory)
            .As <Task <RouteFactory> >()
            .SingleInstance();

            // RouterConfig
            builder.Register(c => new RouterConfig(Enumerable.Empty <Route>()))
            .As <RouterConfig>()
            .SingleInstance();

            if (!this.isStoreAndForwardEnabled)
            {
                // EndpointExecutorConfig
                builder.Register(
                    c =>
                {
                    RetryStrategy defaultRetryStrategy = new FixedInterval(0, TimeSpan.FromSeconds(1));
                    TimeSpan defaultRevivePeriod       = TimeSpan.FromHours(1);
                    TimeSpan defaultTimeout            = TimeSpan.FromSeconds(60);
                    return(new EndpointExecutorConfig(defaultTimeout, defaultRetryStrategy, defaultRevivePeriod, true));
                })
                .As <EndpointExecutorConfig>()
                .SingleInstance();

                // IEndpointExecutorFactory
                builder.Register(c => new SyncEndpointExecutorFactory(c.Resolve <EndpointExecutorConfig>()))
                .As <IEndpointExecutorFactory>()
                .SingleInstance();

                // Task<Router>
                builder.Register(
                    async c =>
                {
                    var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>();
                    var routerConfig            = c.Resolve <RouterConfig>();
                    Router router = await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory);
                    return(router);
                })
                .As <Task <Router> >()
                .SingleInstance();

                // Task<ITwinManager>
                builder.Register(
                    async c =>
                {
                    if (this.useV1TwinManager)
                    {
                        var messageConverterProvider         = c.Resolve <IMessageConverterProvider>();
                        IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >();
                        ITwinManager twinManager             = new PassThroughTwinManager(connectionManager, messageConverterProvider);
                        return(twinManager);
                    }
                    else
                    {
                        var messageConverterProvider         = c.Resolve <IMessageConverterProvider>();
                        IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >();
                        return(TwinManager.CreateTwinManager(connectionManager, messageConverterProvider, Option.None <IStoreProvider>()));
                    }
                })
                .As <Task <ITwinManager> >()
                .SingleInstance();
            }
            else
            {
                // EndpointExecutorConfig
                builder.Register(
                    c =>
                {
                    // Endpoint executor config values -
                    // ExponentialBackoff - minBackoff = 1s, maxBackoff = 60s, delta (used to add randomness to backoff) - 1s (default)
                    // Num of retries = int.MaxValue(we want to keep retrying till the message is sent)
                    // Revive period - period for which the endpoint should be considered dead if it doesn't respond - 1 min (we want to try continuously till the message expires)
                    // Timeout - time for which we want for the ack from the endpoint = 30s
                    // TODO - Should the number of retries be tied to the Store and Forward ttl? Not
                    // doing that right now as that value can be changed at runtime, but these settings
                    // cannot. Need to make the number of retries dynamically configurable for that.
                    TimeSpan minWait            = TimeSpan.FromSeconds(1);
                    TimeSpan maxWait            = TimeSpan.FromSeconds(60);
                    TimeSpan delta              = TimeSpan.FromSeconds(1);
                    int retries                 = int.MaxValue;
                    RetryStrategy retryStrategy = new ExponentialBackoff(retries, minWait, maxWait, delta);
                    TimeSpan timeout            = TimeSpan.FromSeconds(30);
                    TimeSpan revivePeriod       = TimeSpan.FromSeconds(30);
                    return(new EndpointExecutorConfig(timeout, retryStrategy, revivePeriod));
                })
                .As <EndpointExecutorConfig>()
                .SingleInstance();

                // ICheckpointStore
                builder.Register(
                    c =>
                {
                    var dbStoreProvider          = c.Resolve <IDbStoreProvider>();
                    IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
                    return(CheckpointStore.Create(storeProvider));
                })
                .As <ICheckpointStore>()
                .SingleInstance();

                // IMessageStore
                builder.Register(
                    c =>
                {
                    var checkpointStore          = c.Resolve <ICheckpointStore>();
                    var dbStoreProvider          = c.Resolve <IDbStoreProvider>();
                    IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
                    IMessageStore messageStore   = new MessageStore(storeProvider, checkpointStore, TimeSpan.MaxValue);
                    return(messageStore);
                })
                .As <IMessageStore>()
                .SingleInstance();

                // IEndpointExecutorFactory
                builder.Register(
                    c =>
                {
                    var endpointExecutorConfig = c.Resolve <EndpointExecutorConfig>();
                    var messageStore           = c.Resolve <IMessageStore>();
                    IEndpointExecutorFactory endpointExecutorFactory = new StoringAsyncEndpointExecutorFactory(endpointExecutorConfig, new AsyncEndpointExecutorOptions(10, TimeSpan.FromSeconds(10)), messageStore);
                    return(endpointExecutorFactory);
                })
                .As <IEndpointExecutorFactory>()
                .SingleInstance();

                // Task<Router>
                builder.Register(
                    async c =>
                {
                    var checkpointStore         = c.Resolve <ICheckpointStore>();
                    var routerConfig            = c.Resolve <RouterConfig>();
                    var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>();
                    return(await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory, checkpointStore));
                })
                .As <Task <Router> >()
                .SingleInstance();

                // Task<ITwinManager>
                builder.Register(
                    async c =>
                {
                    if (this.useV1TwinManager)
                    {
                        var dbStoreProvider                  = c.Resolve <IDbStoreProvider>();
                        var messageConverterProvider         = c.Resolve <IMessageConverterProvider>();
                        IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >();
                        return(TwinManager.CreateTwinManager(connectionManager, messageConverterProvider, Option.Some <IStoreProvider>(new StoreProvider(dbStoreProvider))));
                    }
                    else
                    {
                        var messageConverterProvider  = c.Resolve <IMessageConverterProvider>();
                        var deviceConnectivityManager = c.Resolve <IDeviceConnectivityManager>();
                        var connectionManagerTask     = c.Resolve <Task <IConnectionManager> >();
                        IEntityStore <string, TwinStoreEntity> entityStore = await this.GetTwinStore(c);
                        IConnectionManager connectionManager = await connectionManagerTask;
                        ITwinManager twinManager             = StoringTwinManager.Create(
                            connectionManager,
                            messageConverterProvider,
                            entityStore,
                            deviceConnectivityManager,
                            new ReportedPropertiesValidator(),
                            this.minTwinSyncPeriod,
                            this.reportedPropertiesSyncFrequency);
                        return(twinManager);
                    }
                })
                .As <Task <ITwinManager> >()
                .SingleInstance();
            }

            // IClientCredentials "EdgeHubCredentials"
            builder.Register(
                c =>
            {
                var identityFactory = c.Resolve <IClientCredentialsFactory>();
                IClientCredentials edgeHubCredentials = this.connectionString.Map(cs => identityFactory.GetWithConnectionString(cs)).GetOrElse(
                    () => identityFactory.GetWithIotEdged(this.edgeDeviceId, this.edgeModuleId));
                return(edgeHubCredentials);
            })
            .Named <IClientCredentials>("EdgeHubCredentials")
            .SingleInstance();

            // Task<IInvokeMethodHandler>
            builder.Register(
                async c =>
            {
                IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >();
                return(new InvokeMethodHandler(connectionManager) as IInvokeMethodHandler);
            })
            .As <Task <IInvokeMethodHandler> >()
            .SingleInstance();

            // Task<ISubscriptionProcessor>
            builder.Register(
                async c =>
            {
                var connectionManagerTask = c.Resolve <Task <IConnectionManager> >();
                if (this.disableCloudSubscriptions)
                {
                    return(new LocalSubscriptionProcessor(await connectionManagerTask) as ISubscriptionProcessor);
                }
                else
                {
                    var invokeMethodHandlerTask              = c.Resolve <Task <IInvokeMethodHandler> >();
                    var deviceConnectivityManager            = c.Resolve <IDeviceConnectivityManager>();
                    IConnectionManager connectionManager     = await connectionManagerTask;
                    IInvokeMethodHandler invokeMethodHandler = await invokeMethodHandlerTask;
                    return(new SubscriptionProcessor(connectionManager, invokeMethodHandler, deviceConnectivityManager) as ISubscriptionProcessor);
                }
            })
            .As <Task <ISubscriptionProcessor> >()
            .SingleInstance();

            // Task<IEdgeHub>
            builder.Register(
                async c =>
            {
                var routingMessageConverter = c.Resolve <Core.IMessageConverter <IRoutingMessage> >();
                var routerTask                = c.Resolve <Task <Router> >();
                var twinManagerTask           = c.Resolve <Task <ITwinManager> >();
                var invokeMethodHandlerTask   = c.Resolve <Task <IInvokeMethodHandler> >();
                var connectionManagerTask     = c.Resolve <Task <IConnectionManager> >();
                var subscriptionProcessorTask = c.Resolve <Task <ISubscriptionProcessor> >();
                Router router                                = await routerTask;
                ITwinManager twinManager                     = await twinManagerTask;
                IConnectionManager connectionManager         = await connectionManagerTask;
                IInvokeMethodHandler invokeMethodHandler     = await invokeMethodHandlerTask;
                ISubscriptionProcessor subscriptionProcessor = await subscriptionProcessorTask;
                IEdgeHub hub = new RoutingEdgeHub(
                    router,
                    routingMessageConverter,
                    connectionManager,
                    twinManager,
                    this.edgeDeviceId,
                    invokeMethodHandler,
                    subscriptionProcessor);
                return(hub);
            })
            .As <Task <IEdgeHub> >()
            .SingleInstance();

            // Task<ConfigUpdater>
            builder.Register(
                async c =>
            {
                IMessageStore messageStore = this.isStoreAndForwardEnabled ? c.Resolve <IMessageStore>() : null;
                Router router     = await c.Resolve <Task <Router> >();
                var configUpdater = new ConfigUpdater(router, messageStore, this.configUpdateFrequency);
                return(configUpdater);
            })
            .As <Task <ConfigUpdater> >()
            .SingleInstance();

            // Task<IConfigSource>
            builder.Register(
                async c =>
            {
                RouteFactory routeFactory = await c.Resolve <Task <RouteFactory> >();
                if (this.useTwinConfig)
                {
                    var edgeHubCredentials             = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials");
                    var twinCollectionMessageConverter = c.Resolve <Core.IMessageConverter <TwinCollection> >();
                    var twinMessageConverter           = c.Resolve <Core.IMessageConverter <Twin> >();
                    var twinManagerTask                  = c.Resolve <Task <ITwinManager> >();
                    var edgeHubTask                      = c.Resolve <Task <IEdgeHub> >();
                    ITwinManager twinManager             = await twinManagerTask;
                    IEdgeHub edgeHub                     = await edgeHubTask;
                    IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >();
                    IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                    IConfigSource edgeHubConnection = await EdgeHubConnection.Create(
                        edgeHubCredentials.Identity,
                        edgeHub,
                        twinManager,
                        connectionManager,
                        routeFactory,
                        twinCollectionMessageConverter,
                        twinMessageConverter,
                        this.versionInfo,
                        deviceScopeIdentitiesCache);
                    return(edgeHubConnection);
                }
                else
                {
                    return(new LocalConfigSource(routeFactory, this.routes, this.storeAndForwardConfiguration));
                }
            })
            .As <Task <IConfigSource> >()
            .SingleInstance();

            // Task<IConnectionProvider>
            builder.Register(
                async c =>
            {
                var connectionManagerTask              = c.Resolve <Task <IConnectionManager> >();
                var edgeHubTask                        = c.Resolve <Task <IEdgeHub> >();
                IConnectionManager connectionManager   = await connectionManagerTask;
                IEdgeHub edgeHub                       = await edgeHubTask;
                IConnectionProvider connectionProvider = new ConnectionProvider(connectionManager, edgeHub);
                return(connectionProvider);
            })
            .As <Task <IConnectionProvider> >()
            .SingleInstance();

            base.Load(builder);
        }
示例#40
0
 public void createNewConnectionWithInvalidURL()
 {
     ConnectionManager connMgr     = ConnectionManager.Instance;
     HttpWebRequest    httpRequest = connMgr.getConnection("Not a url");
 }
示例#41
0
        public async Task <bool> DeleteWhereAsync(Expression <Func <TModel, bool> > where, QueryExecutionOptions options = null)
        {
            var(whereClauseSql, whereClauseParameters) = WhereClauseCompiler.ToSql(where, language: WhereClauseCompiler.Language.MYSQL);
            var parameters = new DynamicParameters(whereClauseParameters);

            using (var unitOfWork = ConnectionManager.Connect())
            {
                var rowsDeleted = await unitOfWork.Connection.ExecuteAsync($"DELETE FROM {TableName} WHERE {whereClauseSql}", parameters, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds);

                return(rowsDeleted >= 0);
            }
        }
示例#42
0
        public static void UpdateDatabase(string sourceUri, ConnectionManager manager)
        {
            WebClient webClient = new WebClient();

            string[] data = webClient.DownloadString(new Uri(sourceUri)).Split('\n');

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = data[i].Split('\r')[0];
            }

            for (int i = 0; i < data.Length / 10; i++)
            {
                if (data[i].Equals("\t<item>"))
                {
                    Article article = new Article();

                    article.Title = data[i + 1].Split('\t')[2];

                    article.Title = article.Title.Substring(7, article.Title.Length - 15);

                    if (manager.ConfirmArticlePresence(article.Title))
                    {
                        return;
                    }

                    article.Link = data[i + 2].Split('\t')[2];

                    article.Link = article.Link.Substring(6, article.Link.Length - 13);

                    try
                    {
                        article.Description = data[i + 3].Split('&')[2];

                        article.Description = article.Description.Substring(5, article.Description.Length - 5);

                        if (article.Description.Split(';')[0].Equals("quot"))
                        {
                            article.Description = data[i + 3].Split('&')[4];

                            article.Description = article.Description.Substring(5, article.Description.Length - 5);
                        }
                    }
                    catch
                    {
                        article.Description = data[i + 3].Split('>')[1].Split('<')[0];

                        article.ImageUri = "None";
                    }

                    if (article.ImageUri != "None")
                    {
                        string imageSource = data[i + 3].Split('"')[1];

                        article.ImageUri = imageSource;
                    }

                    string[] date = data[i + 10].Split('>');

                    int offset = 0;
                    while (!date[0].Equals("\t\t<pubDate"))
                    {
                        date = data[i + 11 + offset].Split('>');
                        offset++;
                    }

                    date = date[1].Split('<');

                    article.Date = DateTime.Parse(date[0]);

                    manager.AddArticle(article);

                    i += 9;
                }
            }
        }
示例#43
0
 public MarcaService(string connectionString)
 {
     conexion    = new ConnectionManager(connectionString);
     repositorio = new MarcaRepository(conexion);
 }
 public MetadataMode(TorrentManager manager, DiskManager diskManager, ConnectionManager connectionManager, EngineSettings settings, string savePath, bool stopWhenDone)
     : base(manager, diskManager, connectionManager, settings)
 {
     this.savePath     = savePath;
     this.stopWhenDone = stopWhenDone;
 }
示例#45
0
 public WebSocketMessageHandler(ConnectionManager connections) : base(connections)
 {
 }
示例#46
0
        public async Task InvokeMethodLateSubscriptionTest()
        {
            // Create a mock endpoint capable of returning a mock processor
            var processor = Mock.Of<IProcessor>();
            var endpoint = new Mock<Endpoint>("myId");
            endpoint.Setup(ep => ep.CreateProcessor()).Returns(processor);
            endpoint.SetupGet(ep => ep.Id).Returns("myId");

            // Create a mock endpoint executor factory to create the endpoint executor to verify invocation
            var endpointExecutor = Mock.Of<IEndpointExecutor>();
            Mock.Get(endpointExecutor).SetupGet(ee => ee.Endpoint).Returns(() => endpoint.Object);
            var endpointExecutorFactory = Mock.Of<IEndpointExecutorFactory>();
            Mock.Get(endpointExecutorFactory).Setup(eef => eef.CreateAsync(It.IsAny<Endpoint>())).ReturnsAsync(endpointExecutor);

            // Create a route to map to the message
            var endpoints = new HashSet<Endpoint> { endpoint.Object };
            var route = new Route("myRoute", "true", "myIotHub", TelemetryMessageSource.Instance, endpoints);

            // Create a router
            var routerConfig = new RouterConfig(new[] { route });
            Router router = await Router.CreateAsync("myRouter", "myIotHub", routerConfig, endpointExecutorFactory);

            // Create mock message converter to generate a message with source matching the route
            var messageConverter = Mock.Of<Core.IMessageConverter<Devices.Routing.Core.IMessage>>();
            var methodRequest = new DirectMethodRequest("device1/module1", "shutdown", null, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(20));

            // Mock of twin manager
            var twinManager = Mock.Of<ITwinManager>();

            // DeviceListener
            var identity = Mock.Of<IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1");
            var cloudProxy = new Mock<ICloudProxy>();

            // ICloudConnectionProvider
            var cloudConnection = Mock.Of<ICloudConnection>(c => c.IsActive && c.CloudProxy == Option.Some(cloudProxy.Object));
            var cloudConnectionProvider = new Mock<ICloudConnectionProvider>();
            cloudConnectionProvider.Setup(c => c.Connect(It.IsAny<IIdentity>(), It.IsAny<Action<string, CloudConnectionStatus>>()))
                .ReturnsAsync(Try.Success(cloudConnection));
            var connectionManager = new ConnectionManager(cloudConnectionProvider.Object, Mock.Of<ICredentialsCache>(), new IdentityProvider("myIotHub"));

            IInvokeMethodHandler invokeMethodHandler = new InvokeMethodHandler(connectionManager);
            var subscriptionProcessor = new SubscriptionProcessor(connectionManager, invokeMethodHandler, Mock.Of<IDeviceConnectivityManager>());

            // RoutingEdgeHub
            var routingEdgeHub = new RoutingEdgeHub(
                router,
                messageConverter,
                connectionManager,
                twinManager,
                "testEdgeDevice",
                invokeMethodHandler,
                subscriptionProcessor);

            var deviceMessageHandler = new DeviceMessageHandler(identity, routingEdgeHub, connectionManager);
            var underlyingDeviceProxy = new Mock<IDeviceProxy>();

            // Arrange
            Message message = new EdgeMessage.Builder(new byte[0]).Build();
            message.Properties[SystemProperties.CorrelationId] = methodRequest.CorrelationId;
            message.Properties[SystemProperties.StatusCode] = "200";

            underlyingDeviceProxy.Setup(d => d.InvokeMethodAsync(It.IsAny<DirectMethodRequest>()))
                .Callback(() => deviceMessageHandler.ProcessMethodResponseAsync(message))
                .ReturnsAsync(default(DirectMethodResponse));
            underlyingDeviceProxy.SetupGet(d => d.IsActive).Returns(true);

            // Act
            deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object);
            Task<DirectMethodResponse> responseTask = routingEdgeHub.InvokeMethodAsync(identity.Id, methodRequest);

            // Assert
            Assert.False(responseTask.IsCompleted);

            // Act
            await routingEdgeHub.AddSubscription(identity.Id, DeviceSubscription.Methods);
            await Task.Delay(TimeSpan.FromSeconds(5));

            // Assert
            Assert.True(responseTask.IsCompleted);
            Assert.Equal(methodRequest.CorrelationId, responseTask.Result.CorrelationId);
            Assert.Equal(200, responseTask.Result.Status);
            Assert.False(responseTask.Result.Exception.HasValue);
            Assert.Equal(HttpStatusCode.OK, responseTask.Result.HttpStatusCode);
        }
示例#47
0
 private void Awake()
 {
     connectionManager = GameObject.FindGameObjectWithTag("ConnectionManager").GetComponent <ConnectionManager>();
 }
示例#48
0
 public HDFSConnectionManagerUIForm(ConnectionManager connectionManager, IServiceProvider serviceProvider)
     : this()
 {
     this.connectionManager = connectionManager;
     this.serviceProvider   = serviceProvider;
 }
 public PulsacionesServicesDB(string connectionString)
 {
     conexion = new ConnectionManager(connectionString);
     pulsacionesRepositoryDB = new PulsacionesRepositoryDB(conexion);
 }
示例#50
0
        private async Task loadServicesAsync()
        {
            ServiceTypes serviceType;

            foreach (Service service in deviceDescription.Device.Services)
            {
                switch (service.ServiceType)
                {
                case ServiceTypesString.AVTRANSPORT:
                    AVTransport = await XmlExtension.DeserializeUriAsync <AVTransport>(new Uri(HtmlExtension.CompleteHttpString(ipAddress, port, service.SCPDURL)));

                    AVTransport.SetParent();
                    serviceType = ServiceTypes.AVTRANSPORT;
                    break;

                case ServiceTypesString.CONNECTIONMANAGER:
                    ConnectionManager = await XmlExtension.DeserializeUriAsync <ConnectionManager>(new Uri(HtmlExtension.CompleteHttpString(ipAddress, port, service.SCPDURL)));

                    ConnectionManager.SetParent();
                    serviceType = ServiceTypes.CONNECTIONMANAGER;
                    break;

                case ServiceTypesString.CONTENTDIRECTORY:
                    ContentDirectory = await XmlExtension.DeserializeUriAsync <ContentDirectory>(new Uri(HtmlExtension.CompleteHttpString(ipAddress, port, service.SCPDURL)));

                    ContentDirectory.SetParent();
                    serviceType = ServiceTypes.CONTENTDIRECTORY;
                    break;

                case ServiceTypesString.MEDIARECEIVERREGISTRAR:
                    MediaReceiverRegistrar = await XmlExtension.DeserializeUriAsync <MediaReceiverRegistrar>(new Uri(HtmlExtension.CompleteHttpString(ipAddress, port, service.SCPDURL)));

                    MediaReceiverRegistrar.SetParent();
                    serviceType = ServiceTypes.MEDIARECEIVERREGISTRAR;
                    break;

                case ServiceTypesString.RENDERINGCONTROL:
                    RenderingControl = await XmlExtension.DeserializeUriAsync <RenderingControl>(new Uri(HtmlExtension.CompleteHttpString(ipAddress, port, service.SCPDURL)));

                    RenderingControl.SetParent();
                    serviceType = ServiceTypes.RENDERINGCONTROL;
                    break;

                default:
                    serviceType = ServiceTypes.NEUTRAL;
                    break;
                }

                if (serviceType != ServiceTypes.NEUTRAL)
                {
                    serviceSCPDs.Add(new NetWorkSubscriberPayload {
                        MediaDevice = this, URI = HtmlExtension.CompleteHttpString(ipAddress, port, service.SCPDURL), ServiceType = serviceType,
                    });
                    serviceControls.Add(new NetWorkSubscriberPayload {
                        MediaDevice = this, URI = HtmlExtension.CompleteHttpString(ipAddress, port, service.ControlURL), ServiceType = serviceType,
                    });
                    serviceEvents.Add(new NetWorkSubscriberPayload {
                        MediaDevice = this, URI = HtmlExtension.CompleteHttpString(ipAddress, port, service.EventSubURL), ServiceType = serviceType,
                    });
                }
            }
        }
 public SSISAdoNetSource(AdoNetSource src, MainPipe pipe, ConnectionManager cm, ILogger logger, Application app)
     : base(pipe, "ADO NET Source", logger, app)
 {
     _src = src;
     _cm  = cm;
 }
 public MetadataMode(TorrentManager manager, DiskManager diskManager, ConnectionManager connectionManager, EngineSettings settings, string savePath)
     : this(manager, diskManager, connectionManager, settings, savePath, false)
 {
 }
示例#53
0
 public virtual IBatcher CreateBatcher(ConnectionManager connectionManager, IInterceptor interceptor)
 {
     return(new MySqlClientBatchingBatcher(connectionManager, interceptor));
 }
示例#54
0
        private void ManageConnectionControl()
        {
            cManager = ConnectionManager.Instance;
            cManager.RequestPassword   += (sender, e) => fHelper.RequestPassword(e.ConnectionDetail);
            cManager.StepChanged       += (sender, e) => ccsb.SetMessage(e.CurrentStep);
            cManager.ConnectionSucceed += (sender, e) =>
            {
                var parameter = e.Parameter as ConnectionParameterInfo;
                if (parameter != null)
                {
                    Controls.Remove(parameter.InfoPanel);
                    parameter.InfoPanel.Dispose();
                }

                currentConnectionDetail = e.ConnectionDetail;
                service = e.OrganizationService;
                ccsb.SetConnectionStatus(true, e.ConnectionDetail);
                ccsb.SetMessage(string.Empty);

                if (parameter != null)
                {
                    var control = parameter.ConnectionParmater as UserControl;
                    if (control != null)
                    {
                        var pluginModel = control.Tag as Lazy <IXrmToolBoxPlugin, IPluginMetadata>;
                        if (pluginModel == null)
                        {
                            // Actual Plugin was passed, Just update the plugin's Tab.
                            UpdateTabConnection((TabPage)control.Parent);
                        }
                        else
                        {
                            this.DisplayPluginControl(pluginModel);
                        }
                    }
                    else if (parameter.ConnectionParmater.ToString() == "ApplyConnectionToTabs" && tabControl1.TabPages.Count > 1)
                    {
                        ApplyConnectionToTabs();
                    }
                    else
                    {
                        var args = parameter.ConnectionParmater as RequestConnectionEventArgs;
                        if (args != null)
                        {
                            var userControl = (UserControl)args.Control;

                            args.Control.UpdateConnection(e.OrganizationService, currentConnectionDetail, args.ActionName, args.Parameter);

                            userControl.Parent.Text = string.Format("{0} ({1})",
                                                                    userControl.Parent.Text.Split(' ')[0],
                                                                    e.ConnectionDetail.ConnectionName);
                        }
                    }
                }
                else if (tabControl1.TabPages.Count > 1)
                {
                    ApplyConnectionToTabs();
                }

                this.StartPluginWithConnection();
            };
            cManager.ConnectionFailed += (sender, e) =>
            {
                this.Invoke(new Action(() =>
                {
                    var infoPanel = ((ConnectionParameterInfo)e.Parameter).InfoPanel;
                    Controls.Remove(infoPanel);
                    if (infoPanel != null)
                    {
                        infoPanel.Dispose();
                    }

                    MessageBox.Show(this, e.FailureReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    currentConnectionDetail = null;
                    service = null;
                    ccsb.SetConnectionStatus(false, null);
                    ccsb.SetMessage(e.FailureReason);

                    this.StartPluginWithConnection();
                }));
            };

            fHelper = new FormHelper(this);
            ccsb    = new CrmConnectionStatusBar(fHelper)
            {
                Dock = DockStyle.Bottom
            };
            Controls.Add(ccsb);
        }
示例#55
0
 public TrackArtistRepository(ConnectionManager connectionManager) : base(connectionManager)
 {
 }
示例#56
0
 public PageStatus(MainWindow ParentWindow)
 {
     this.ParentWindow = ParentWindow;
     Connection        = ((App)Application.Current).Connection;
     InitializeComponent();
 }
示例#57
0
        private void MainForm_CalcBalance(object sender, EventArgs e)
        {
            ConnectionManager connectionManager = new ConnectionManager();

            numericUpDownSum.Text = connectionManager.CalcBalance().ToString();
        }
示例#58
0
        private async void modifyVideoButton_Click(object sender, RoutedEventArgs e)
        {
            progressRing.isActive = true;
            VideoUpdateRequest request = new VideoUpdateRequest()
            {
                VideoID     = VideoID,
                Title       = titleTextBlock.Text,
                Description = descriptionTextBlock.Text,
                IsThumbnailUpdateRequired = thumbnailChosen,
                Tags = new List <string>()
            };

            foreach (Tags tags in ((WrapPanel)tagsContainer).Children)
            {
                request.Tags.Add(tags.TagName);
            }
            Object resp = await ConnectionManager.SendRequestAsync(request, RequestType.VideoUpdate, ResponseType.VideoUpdate);

            if (resp != null)
            {
                VideoUpdateResponse ack = ((JObject)resp).ToObject <VideoUpdateResponse>();
                if (ack.Status == "OK")
                {
                    if (thumbnailChosen)
                    {
                        string tempPath = "Temporary/" + Guid.NewGuid() + ".jpg";
                        if (Directory.Exists("Temporary/"))
                        {
                            Directory.CreateDirectory("Temporary/");
                        }
                        File.Copy(thumbnailPath, tempPath);
                        var result = await ConnectionManager.SendFileAsync(tempPath, null);

                        if (result != null)
                        {
                            var response = ((JObject)result).ToObject <Acknowledge>();
                            errorTextBlock.Text = response.Reason;
                            if (response.Status == "OK")
                            {
                                AppNotificationManager.PushMessage(new AppNotification()
                                {
                                    Message = response.Reason
                                });
                                Close();
                            }
                        }
                        if (File.Exists(tempPath))
                        {
                            File.Delete(tempPath);
                        }
                    }
                    AppNotificationManager.PushMessage(new AppNotification()
                    {
                        Message = ack.Reason
                    });
                    Close();
                }
                errorTextBlock.Text = ack.Reason;
            }
            else
            {
                errorTextBlock.Text = "Connection Error.";
            }
        }
示例#59
0
        private void MainForm_UpdateDiagram(object sender, EventArgs e)
        {
            ConnectionManager connectionManager = new ConnectionManager();

            this.pieChart.DrawFromData(connectionManager.GetAlterations());
        }
示例#60
0
 public ServiciosService(string connectionString)
 {
     conexion            = new ConnectionManager(connectionString);
     serviciorepositorio = new ServiciosRepository(conexion);
 }