public void Execute_Processes_AggregatedCounterTable()
        {
            using (var connection = ConnectionUtils.CreateConnection())
            {
                // Arrange
                connection.StateData.InsertOne(new AggregatedCounterDto
                {
                    Key      = "key",
                    Value    = 1,
                    ExpireAt = DateTime.UtcNow.AddMonths(-1)
                });

                var manager = CreateManager();

                // Act
                manager.Execute(_token);

                // Assert
                Assert.Equal(0, connection
                             .StateData
                             .OfType <CounterDto>()
                             .Find(new BsonDocument()).Count());
            }
        }
Esempio n. 2
0
        public CommentPayload(ICommentService commentService)
        {
            _commentService = commentService;

            Name = nameof(Models.Comment);

            Id(x => x.Id);
            Field(x => x.Likes);
            Field(x => x.Dislikes);
            Field(x => x.Body).Description("The body of the comment");
            Field <DateGraphType>("dateAdded", "The date when the comment was made");
            Field <NonNullGraphType <AccountPayload> >("user", "The user who added the comment");
            Field <NonNullGraphType <AudioInterface> >("audio", "The audio that the comment was added to");
            Field <CommentPayload>("originalComment", "The original comment that this is a reply to");
            Connection <CommentPayload>()
            .Name("replies")
            .Description("The reply tree for the top level comments")
            .Resolve(c =>
            {
                var topLevelReplies = c.Source.TopLevelReplies(c.Source);

                return(ConnectionUtils.ToConnection(topLevelReplies, c));
            });
        }
Esempio n. 3
0
        public void Migrate_DropNoBackup_Success()
        {
            var dbContext =
                new HangfireDbContext(ConnectionUtils.GetConnectionString(), "Hangfire-Mongo-Migration-Tests");

            // ARRANGE
            dbContext.Client.DropDatabase(dbContext.Database.DatabaseNamespace.DatabaseName);
            SeedCollectionFromZipArchive(dbContext, Path.Combine("Migration", "Hangfire-Mongo-Schema-006.zip"));

            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = new MongoMigrationOptions
                {
                    Strategy       = MongoMigrationStrategy.Drop,
                    BackupStrategy = MongoBackupStrategy.None
                }
            };

            // ACT
            MongoMigrationManager.MigrateIfNeeded(storageOptions, dbContext.Database);

            // ASSERT
            AssertDataIntegrity(dbContext, assertCollectionHasItems: false);
        }
        public void Execute_Processes_JobTable()
        {
            using (var connection = ConnectionUtils.CreateConnection())
            {
                // Arrange
                connection.Job.InsertOne(new JobDto
                {
                    Id             = ObjectId.GenerateNewId(),
                    InvocationData = "",
                    Arguments      = "",
                    CreatedAt      = DateTime.UtcNow,
                    ExpireAt       = DateTime.UtcNow.AddMonths(-1),
                });

                var manager = CreateManager();

                // Act
                manager.Execute(_token);

                // Assert
                var count = connection.Job.Count(new BsonDocument());
                Assert.Equal(0, count);
            }
        }
        /// <summary>
        /// This method is running the thread started by the ServerConnect() method
        /// It listens to incoming messages and enters the switch case which switches on the id from the message
        /// </summary>
        public void MethodThread()
        {
            Console.WriteLine("started listening");
            Boolean connected = false;

            while (!connected)
            {
                dynamic jsonReceive = JsonConvert.DeserializeObject(ConnectionUtils.ReadMessage(stream));
                string  id          = jsonReceive.id;
                switch (id)
                {
                case "LoginResponse":
                    Boolean response = jsonReceive.response;
                    if (!response)
                    {
                        errorLabel.Invoke(new MethodInvoker(delegate
                        {
                            errorLabel.Text = "The credentials you supplied were not correct.";
                        }));
                    }
                    else
                    {
                        Thread t = new Thread(new ThreadStart(ThreadProc));
                        t.Start();
                        login.Invoke(new MethodInvoker(delegate { login.Close(); }));
                        connected = true;
                        SendAdd();
                    }
                    break;
                }
            }
            Boolean finished = false;

            while (!finished)
            {
                dynamic jsonReceive = JsonConvert.DeserializeObject(ConnectionUtils.ReadMessage(stream));
                string  id          = jsonReceive.id;
                switch (id)
                {
                case "Ack":
                    Console.WriteLine("Bike added");
                    Console.WriteLine(jsonReceive);
                    List <string> bikeNames = GetBikeNames(jsonReceive);
                    Console.WriteLine("BIKENAMES: " + bikeNames.Count);
                    patientNames = GetPatientNames(jsonReceive);
                    Console.WriteLine("AANTAL PATIENTEN: " + patientNames.Count);
                    if (machineNames == null)
                    {
                        machineNames = new List <string>();
                        machineNames = bikeNames;
                    }
                    else
                    {
                        machineNames.Concat(bikeNames);
                    }
                    Form1.patients = patientNames;
                    Form1.getNames();
                    Console.WriteLine("IS FORM NULL: " + form == null);

                    Thread t2 = new Thread(new ThreadStart(StartUpdate));
                    t2.Start();
                    break;

                case "PatientNames":
                    Console.WriteLine("PATIENTS: " + jsonReceive);
                    this.patientNames = GetPatientNames(jsonReceive);
                    this.patientNames.Concat(patientNames);
                    foreach (Patient patient in this.patientNames)
                    {
                        Console.WriteLine(patient.age.ToString());
                    }
                    break;

                case "SendNewName":
                    string newClient = jsonReceive.name;
                    Console.WriteLine("name: " + newClient);
                    if (machineNames == null)
                    {
                        machineNames = new List <string>();
                        machineNames.Add(newClient);
                    }
                    else
                    {
                        machineNames.Add(newClient);
                    }
                    if (form != null)
                    {
                        Console.WriteLine("updated");
                        form.Invoke((MethodInvoker) delegate()
                        {
                            form.UpdateForm(machineNames, patientNames);
                            Console.WriteLine("BIKENAMES: " + machineNames.Count);
                        });
                    }
                    break;

                case "Bike":
                    JObject data = (JObject)jsonReceive;
                    bikeInfoData = data.ToObject <RootObjectSendBikeInfo>();
                    if (AvansAstrand != null)
                    {
                        AvansAstrand.FillChart();
                    }
                    //Console.WriteLine(bikeInfoData.data);
                    break;

                case "HistoryData":
                    Console.WriteLine("RECEIVED HISTORY: " + jsonReceive);
                    SetHistoryData(jsonReceive);
                    break;

                case "Astrand":
                    string AInfo = jsonReceive.info;
                    string AName = jsonReceive.name;
                    int    value = jsonReceive.value;
                    AvansAstrand.SetInfo(AInfo, AName, value);
                    break;

                case "Time":
                    string time  = jsonReceive.time;
                    string TName = jsonReceive.name;
                    AvansAstrand.SetTime(time, TName);
                    break;

                case "VO2":
                    string VName = jsonReceive.name;
                    double Vo2   = jsonReceive.VO2;
                    if (AvansAstrand.machineName == VName)
                    {
                        AvansAstrand.Invoke(new MethodInvoker(delegate
                        {
                            AvansAstrand.Vo2.Text = Vo2.ToString();
                        }));
                    }
                    break;
                }
            }
        }
        public void StartSession(int seconds)
        {
            dynamic json = jc.getJson(jc.StartSes(seconds));

            ConnectionUtils.SendMessage(this.stream, json);
        }
Esempio n. 7
0
 /// <summary>
 /// Сервис взаимодействия с API.
 /// </summary>
 public PersonService()
 {
     HttpClient = new HttpClient();
     Address    = ConnectionUtils.GetAddressConnection().Address;
 }
Esempio n. 8
0
 public MySqlJobQueueTests()
 {
     _connection = ConnectionUtils.CreateConnection();
     _storage    = new MySqlStorage(_connection);
 }
        public static bool guardar(FichaPreEgreso ficha, bool nuevo)
        {
            String query = "";

            if (nuevo)
            {
                query = "INSERT INTO dbo.FichaPreEgreso (fechaNacimiento,sexo,nacionalidad,telefono,email,calle,numeroCasa,colonia,ciudad,estado,codigoPostal,idEgresado) " +
                        "VALUES(GETDATE(),@sexo,@nacionalidad,@telefono,@email,@calle,@numeroCasa,@colonia,@ciudad,@estado,@codigoPostal,@idEgresado);";
            }
            else
            {
                query = "UPDATE dbo.FichaPreEgreso SET " +
                        "fechaNacimiento= @fechaNacimiento, " +
                        "sexo=@sexo, " +
                        "nacionalidad=@nacionalidad, " +
                        "telefono=@telefono, " +
                        "email=@email, " +
                        "calle=@calle, " +
                        "numeroCasa=@numeroCasa, " +
                        "colonia=@colonia, " +
                        "ciudad=@ciudad, " +
                        "estado=@estado, " +
                        "codigoPostal=@codigoPostal " +
                        "WHERE idFichaPreEgreso=@idFichaPreEgreso;";
            }

            SqlConnection conn = null;

            try
            {
                conn = ConnectionUtils.getConnection();
                SqlCommand command;
                if (conn != null)
                {
                    Console.WriteLine(query);
                    command             = new SqlCommand(query, conn);
                    command.CommandType = CommandType.Text;
                    command.Parameters.AddWithValue("@sexo", ficha.Sexo);
                    command.Parameters.AddWithValue("@nacionalidad", ficha.Nacionalidad);
                    command.Parameters.AddWithValue("@telefono", ficha.Telefono);
                    command.Parameters.AddWithValue("@email", ficha.Email);
                    command.Parameters.AddWithValue("@calle", ficha.Calle);
                    command.Parameters.AddWithValue("@numeroCasa", ficha.NumeroCasa);
                    command.Parameters.AddWithValue("@colonia", ficha.Colonia);
                    command.Parameters.AddWithValue("@ciudad", ficha.Ciudad);
                    command.Parameters.AddWithValue("@estado", ficha.Estado);
                    command.Parameters.AddWithValue("@codigoPostal", ficha.CodigoPostal);

                    if (nuevo)
                    {
                        command.Parameters.AddWithValue("@idEgresado", ficha.IdEgresado);
                    }
                    else
                    {
                        command.Parameters.AddWithValue("@idFichaPreEgreso", ficha.IdFichaPreEgreso);
                    }


                    int i = command.ExecuteNonQuery();
                    Console.WriteLine("Filas afectadas: " + i);
                    if (i > 0)
                    {
                        return(true);
                    }
                    command.Dispose();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("No se pudo guardar la información...");
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
            return(false);
        }
 public MongoConnectionFacts()
 {
     _jobQueueSemaphoreMock = new Mock <IJobQueueSemaphore>(MockBehavior.Strict);
     _dbContext             = ConnectionUtils.CreateDbContext();
     _connection            = new MongoConnection(_dbContext, new MongoStorageOptions(), _jobQueueSemaphoreMock.Object);
 }
Esempio n. 11
0
 private FluentNHibernateStorage.FluentNHibernateJobStorage CreateStorage()
 {
     return(ConnectionUtils.GetStorage(_options));
 }
Esempio n. 12
0
        public String Read()
        {
            string response = ConnectionUtils.ReadMessage(NetworkStream);

            return(response);
        }
Esempio n. 13
0
 public void Send(String message)
 {
     ConnectionUtils.SendMessage(NetworkStream, message);
 }
Esempio n. 14
0
        public static void guardarUsuario(Personal personal, bool nuevo)
        {
            String query = "";

            if (nuevo)
            {
                query = "INSERT INTO dbo.Personal (tipoPersonal,apellidos,nombre,cargo,usuario,contrasena,nombreDelegacion,estado,fechaCreacion) " +
                        "VALUES(@tipoPersonal,@apellidos,@nombre,@cargo,@usuario,@contrasena,@nombreDelegacion,@estado,@fechaCreacion);";
            }
            else
            {
                query = "UPDATE dbo.Personal SET " +
                        "tipoPersonal = @tipoPersonal, " +
                        "apellidos = @apellidos, " +
                        "nombre = @nombre, " +
                        "cargo = @cargo, " +
                        "usuario = @usuario, " +
                        "contrasena = @contrasena, " +
                        "nombreDelegacion = @nombreDelegacion, " +
                        "estado = @estado " +
                        "WHERE idPersonal = @idPersonal;";
            }


            Console.WriteLine("Se guardo la infomacion");

            SqlConnection conn = null;

            try
            {
                conn = ConnectionUtils.getConnection();
                SqlCommand command;
                if (conn != null)
                {
                    Console.WriteLine(query);
                    command             = new SqlCommand(query, conn);
                    command.CommandType = CommandType.Text;
                    command.Parameters.AddWithValue("@tipoPersonal", personal.TipoPersonal);
                    command.Parameters.AddWithValue("@apellidos", personal.Apellidos);
                    command.Parameters.AddWithValue("@nombre", personal.Nombre);
                    command.Parameters.AddWithValue("@cargo", personal.Cargo);
                    command.Parameters.AddWithValue("@usuario", personal.Usuario);
                    command.Parameters.AddWithValue("@contrasena", personal.Contrasenia);
                    command.Parameters.AddWithValue("@nombreDelegacion", personal.NombreDelegacion);
                    command.Parameters.AddWithValue("@estado", personal.Estado);

                    if (nuevo)
                    {
                        command.Parameters.AddWithValue("@fechaCreacion", personal.FechaCreacion);
                    }
                    else
                    {
                        command.Parameters.AddWithValue("@idPersonal", personal.IdPersonal);
                    }

                    int i = command.ExecuteNonQuery();
                    Console.WriteLine("Filas afectadas: " + i);
                    command.Dispose();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("No se pudo guardar la información...");
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
        //[Fact, Trait("Category", "DataGeneration")]
        public void Clean_Database_Filled()
        {
            var databaseName = "Mongo-Hangfire-Filled";
            var context      = ConnectionUtils.CreateDbContext(databaseName);

            // Make sure we start from scratch
            context.Database.Client.DropDatabase(databaseName);

            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = new MongoMigrationOptions
                {
                    MigrationStrategy = new DropMongoMigrationStrategy(),
                    BackupStrategy    = new NoneMongoBackupStrategy()
                },
                QueuePollInterval = TimeSpan.FromMilliseconds(500)
            };
            var serverOptions = new BackgroundJobServerOptions
            {
                ShutdownTimeout = TimeSpan.FromSeconds(15)
            };

            JobStorage.Current = ConnectionUtils.CreateStorage(databaseName);

            using (new BackgroundJobServer(serverOptions))
            {
                // Recurring Job
                RecurringJob.AddOrUpdate(() => HangfireTestJobs.ExecuteRecurringJob("Recurring job"), Cron.Minutely);

                // Scheduled job
                BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteScheduledJob("Scheduled job"), TimeSpan.FromSeconds(30));

                // Enqueued job
                BackgroundJob.Enqueue(() => HangfireTestJobs.ExecuteEnqueuedJob("Enqueued job"));

                // Continued job
                var parentId = BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteContinueWithJob("ContinueWith job", false), TimeSpan.FromSeconds(15));
                BackgroundJob.ContinueWith(parentId, () => HangfireTestJobs.ExecuteContinueWithJob("ContinueWith job continued", true));

                // Now the waiting game starts
                HangfireTestJobs.ScheduleEvent.WaitOne();
                BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteScheduledJob("Scheduled job (*)"), TimeSpan.FromMinutes(30));

                HangfireTestJobs.ContinueWithEvent.WaitOne();
                HangfireTestJobs.RecurringEvent.WaitOne();

                HangfireTestJobs.EnqueueEvent.WaitOne();
                BackgroundJob.Enqueue(() => HangfireTestJobs.ExecuteEnqueuedJob("Enqueued job (*)"));
            }


            // Some data are cleaned up when hangfire shuts down.
            // Grab a copy so we can write it back - needed for migration tests.
            var connection = JobStorage.Current.GetConnection();

            connection.AnnounceServer("test-server", new ServerContext
            {
                WorkerCount = serverOptions.WorkerCount,
                Queues      = serverOptions.Queues
            });

            connection.AcquireDistributedLock("test-lock", TimeSpan.FromSeconds(30));

            // Create database snapshot in zip file
            var schemaVersion = (int)MongoMigrationManager.RequiredSchemaVersion;

            using (var stream = new FileStream($@"Hangfire-Mongo-Schema-{schemaVersion:000}.zip", FileMode.Create))
            {
                var allowedEmptyCollections = new List <string>
                {
                    "hangfire.migrationLock"
                };

                if (MongoMigrationManager.RequiredSchemaVersion >= MongoSchema.Version09 &&
                    MongoMigrationManager.RequiredSchemaVersion <= MongoSchema.Version15)
                {
                    // Signal collection work was initiated in schema version 9,
                    // and still not put to use in schema version 15.
                    allowedEmptyCollections.Add($@"{storageOptions.Prefix}.signal");
                }
                BackupDatabaseToStream(databaseName, stream, allowedEmptyCollections.ToArray());
            }
        }
Esempio n. 16
0
 public FluentNHibernateJobQueueMonitoringApiTests()
 {
     _storage = ConnectionUtils.GetStorage();
     _sut     = new FluentNHibernateJobQueueMonitoringApi(_storage);
 }
        public void Ctor_ThrowsAnException_IfMongoStorageOptionsIsNull()
        {
            var exception = Assert.Throws <ArgumentNullException>(() => new MongoWriteOnlyTransaction(ConnectionUtils.CreateConnection(), _queueProviders, null));

            Assert.Equal("storageOptions", exception.ParamName);
        }
        public void Ctor_ThrowsAnException_IfProvidersCollectionIsNull()
        {
            var exception = Assert.Throws <ArgumentNullException>(() => new SQLiteWriteOnlyTransaction(ConnectionUtils.CreateConnection(), null));

            Assert.Equal("queueProviders", exception.ParamName);
        }
 public Version15MigrationStepFacts()
 {
     _dbContext             = ConnectionUtils.CreateDbContext();
     _database              = _dbContext.Database;
     _mongoMigrationBagMock = new Mock <IMongoMigrationContext>(MockBehavior.Strict);
 }
        private void UseConnection(Action <HangfireDbContext> action)
        {
            HangfireDbContext connection = ConnectionUtils.CreateConnection();

            action(connection);
        }
        public static FichaPreEgreso obtenerFichaPreEgreso(Int32 idEgresado)
        {
            FichaPreEgreso fp   = null;
            SqlConnection  conn = null;

            try
            {
                conn = ConnectionUtils.getConnection();
                SqlCommand    command;
                SqlDataReader rd;
                if (conn != null)
                {
                    String query = String.Format("SELECT " +
                                                 "x.idFichaPreEgreso, " +
                                                 "x.fechaNacimiento, " +
                                                 "x.sexo, " +
                                                 "x.nacionalidad, " +
                                                 "x.telefono, " +
                                                 "x.email, " +
                                                 "x.calle, " +
                                                 "x.numeroCasa, " +
                                                 "x.colonia, " +
                                                 "x.ciudad, " +
                                                 "x.estado, " +
                                                 "x.codigoPostal, " +
                                                 "x.idEgresado " +
                                                 "FROM dbo.FichaPreEgreso x " +
                                                 "WHERE x.idEgresado = '{0}';", idEgresado);
                    Console.WriteLine(query);
                    command = new SqlCommand(query, conn);
                    rd      = command.ExecuteReader();
                    while (rd.Read())
                    {
                        fp = new FichaPreEgreso();
                        fp.IdFichaPreEgreso = (!rd.IsDBNull(0)) ? rd.GetInt32(0) : 0;
                        fp.FechaNacimiento  = (!rd.IsDBNull(1)) ? rd.GetDateTime(1) : new DateTime();
                        fp.Sexo             = (!rd.IsDBNull(2)) ? rd.GetString(2) : "";
                        fp.Nacionalidad     = (!rd.IsDBNull(3)) ? rd.GetString(3) : "";
                        fp.Telefono         = (!rd.IsDBNull(4)) ? rd.GetString(4) : "";
                        fp.Email            = (!rd.IsDBNull(5)) ? rd.GetString(5) : "";
                        fp.Calle            = (!rd.IsDBNull(6)) ? rd.GetString(6) : "";
                        fp.NumeroCasa       = (!rd.IsDBNull(7)) ? rd.GetString(7) : "";
                        fp.Colonia          = (!rd.IsDBNull(8)) ? rd.GetString(8) : "";
                        fp.Ciudad           = (!rd.IsDBNull(9)) ? rd.GetString(9) : "";
                        fp.Estado           = (!rd.IsDBNull(10)) ? rd.GetString(10) : "";
                        fp.CodigoPostal     = (!rd.IsDBNull(11)) ? rd.GetString(11) : "";
                        fp.IdEgresado       = (!rd.IsDBNull(0)) ? rd.GetInt32(0) : 0;
                    }
                    rd.Close();
                    command.Dispose();
                    Console.WriteLine(fp);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("No se encontro ficha del egresado");
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
            return(fp);
        }
        protected virtual Dictionary <string, DataTable> BuildDatabase(IDictionary <string, Table> tables,
                                                                       SpringBaseDao baseDao, out bool createdDatabase)
        {
            createdDatabase = false;
            ConnectionTxPair connectionTxPairToUse = null;

            try
            {
                connectionTxPairToUse = ConnectionUtils.GetConnectionTxPair(baseDao.DbProvider);
                ConnectionUtils.DisposeConnection(connectionTxPairToUse.Connection, baseDao.DbProvider);
                connectionTxPairToUse = null;
                return(GetCurrentDatabaseTableSchemas(tables, baseDao));
            }
            catch (CannotGetAdoConnectionException)
            {
                // Database probably does not exist, so attempt to create it below
            }
            finally
            {
                if (connectionTxPairToUse != null)
                {
                    ConnectionUtils.DisposeConnection(connectionTxPairToUse.Connection, baseDao.DbProvider);
                    connectionTxPairToUse = null;
                }
            }
            string saveConnectionString = baseDao.DbProvider.ConnectionString;
            string databaseName;
            string newConnectionString =
                SpringBaseDao.RemoveDatabaseFromConnectionString(baseDao.DbProvider, out databaseName);

            if (string.IsNullOrEmpty(databaseName))
            {
                throw new ArgumentException(string.Format("Could not locate database name in connection string: \"{0}\"",
                                                          baseDao.DbProvider.ConnectionString));
            }
            baseDao.DbProvider.ConnectionString = newConnectionString;
            try
            {
                connectionTxPairToUse = ConnectionUtils.GetConnectionTxPair(baseDao.DbProvider);
                string sql = string.Format("CREATE DATABASE {0}", databaseName);
                baseDao.AdoTemplate.ExecuteNonQuery(CommandType.Text, sql);
                createdDatabase = true;
            }
            finally
            {
                if (connectionTxPairToUse != null)
                {
                    ConnectionUtils.DisposeConnection(connectionTxPairToUse.Connection, baseDao.DbProvider);
                    connectionTxPairToUse = null;
                }
                baseDao.DbProvider.ConnectionString = saveConnectionString;
            }
            // Wait for database to be fully created
            long timeoutTicks = DateTime.Now.Ticks + TimeSpan.FromSeconds(CREATE_DATABASE_WAIT_SECONDS).Ticks;

            do
            {
                try
                {
                    return(GetCurrentDatabaseTableSchemas(tables, baseDao));
                }
                catch (DataAccessException)
                {
                }
                Thread.Sleep(300);
            }while (timeoutTicks > DateTime.Now.Ticks);
            throw new CannotGetAdoConnectionException();
        }
Esempio n. 23
0
        private static void UseConnection(Action <HangfireDbContext> action)
        {
            var connection = ConnectionUtils.CreateConnection();

            action(connection);
        }
 public FluentNHibernateJobQueueTests()
 {
     _storage = ConnectionUtils.GetStorage();
 }
 public CountersAggregatorTests()
 {
     _storage            = ConnectionUtils.GetStorage();
     _countersAggregator = new CountersAggregator(_storage);
 }
Esempio n. 26
0
 protected void DisposeConnection(IDbConnection conn, IDbProvider dbProvider)
 {
     ConnectionUtils.DisposeConnection(conn, dbProvider);
 }
 public void SendToServer(string msg)
 {
     ConnectionUtils.SendMessage(stream, msg);
 }
Esempio n. 28
0
        /// <summary>
        /// This method is called when the ClientBike is ready to get added into the servers program.
        /// (Nedds to be called before you want to start sending updates)
        /// </summary>
        public void SendAdd()
        {
            dynamic json = jc.getJson(jc.Connect(false));

            ConnectionUtils.SendMessage(this.stream, json);
        }
Esempio n. 29
0
 public ExpirationManagerFacts()
 {
     _storage = new MongoStorage(ConnectionUtils.GetConnectionString(), ConnectionUtils.GetDatabaseName());
     _token   = new CancellationToken(true);
 }
Esempio n. 30
0
        /// <summary>
        /// This method is running the thread started by the ServerConnect() method
        /// It listens to incoming messages and enters the switch case which switches on the id from the message
        /// </summary>
        public void MethodThread()
        {
            Console.WriteLine("started listening");
            while (true)
            {
                try
                {
                    dynamic jsonRecieve = JsonConvert.DeserializeObject(ConnectionUtils.ReadMessage(stream));
                    string  id          = jsonRecieve.id;
                    switch (id)
                    {
                    case "Ack":
                        Console.WriteLine("Bike added");
                        break;

                    case "Change":
                        int    distance       = jsonRecieve.data.distance;
                        int    requestedPower = jsonRecieve.data.requestedPower;
                        string time           = jsonRecieve.data.time;
                        SimulatorGUI.ChangeBikeValues(distance, requestedPower, time);
                        break;

                    case "ChangeTime":
                        Console.WriteLine("Changed time");
                        string timeChange = jsonRecieve.time;
                        SimulatorGUI.ChangeTime(timeChange);
                        break;

                    case "ChangePower":
                        int rqPower = jsonRecieve.requestedPower;
                        SimulatorGUI.ChangePower(rqPower);
                        break;

                    case "Message":
                        Console.WriteLine("JSON: " + jsonRecieve);
                        string message = jsonRecieve.message;
                        int    value   = jsonRecieve.value;
                        Console.WriteLine("Recieved message: " + message);
                        if (value == 1)
                        {
                            SimulatorGUI.tempMessage = message;
                        }
                        else
                        {
                            SimulatorGUI.warningMessage = message;
                        }
                        break;

                    case "PersonalMessage":
                        string messageP = jsonRecieve.message;
                        Console.WriteLine("Personal message: " + messageP);
                        SimulatorGUI.tempMessage = messageP;
                        break;

                    case "EmergencyStop":
                        Console.WriteLine("Emergency stop!");
                        SimulatorGUI.ChangeBikeValues(25);
                        SimulatorGUI.emergencyStop = true;
                        break;

                    case "Time":
                        string timeT = jsonRecieve.time;
                        SimulatorGUI.time = timeT;
                        break;
                    }
                }
                catch (Exception e)
                {
                }
            }
        }