Exemplo n.º 1
0
        public RatStore()
        {
            DataStore = new DatabaseStore();
            if (!DataStore.Connected())
            {
                DataStore = new TextStore();
            }

            DataStore.Initialize();

            try
            {
                ChangeLocation(1);
            }
            catch
            {
                // Add test location if none available
                Address    = "123 Test St, Everett, WA 98203";
                LocationId = 1;
                DataStore.AddLocation(this);
                DataStore.Save();

                ChangeLocation(1);
            }
        }
Exemplo n.º 2
0
        private void RegisterInstallationConfiguration(IServiceCollection services)
        {
            SetupTools.DbTools = new SqlServerTools(() => OpenConnection(CoderrClaims.SystemPrincipal));
            var store = new DatabaseStore(() => OpenConnection(CoderrClaims.SystemPrincipal));

            services.AddSingleton <ConfigurationStore>(store);
        }
Exemplo n.º 3
0
 public async Task <T> PerformDbTaskAsync <T>(Func <DatabaseStore, Task <T> > dbUser)
 {
     using (var db = new DatabaseStore())
     {
         return(await dbUser(db));
     }
 }
Exemplo n.º 4
0
        public DatabaseManager(IServiceProvider provider)
        {
            var migrations = new List <IDatabaseMigration>(provider.GetServices <IDatabaseMigration>());

            migrations.Sort((m1, m2) => m1.Priority - m2.Priority);
            using (var db = new DatabaseStore())
            {
                db.Database.Migrate();
                string version;
                try
                {
                    version = db.DatabaseMetadata.Find("db.version").Value;
                }
                catch
                {
                    version = null;
                }

                foreach (var databaseMigration in migrations)
                {
                    if (databaseMigration.ShouldRun(version))
                    {
                        databaseMigration.Execute(db);
                    }
                }
                db.SaveChanges();
            }
        }
Exemplo n.º 5
0
 public T PerformDbTask <T>(Func <DatabaseStore, T> dbUser)
 {
     using (var db = new DatabaseStore())
     {
         return(dbUser(db));
     }
 }
Exemplo n.º 6
0
 public UpdateBucketInfoTask(DatabaseStore dbstore, NodeContext nodeContext, string dbName)
 {
     _dbStore     = dbstore;
     _nodeContext = nodeContext;
     _dbName      = dbName;
     _startSignal = new ManualResetEvent(false);
 }
Exemplo n.º 7
0
 private void Salir()
 {
     MostrarAlerta("Gracias por usar el cajero automatico", true, true);
     using (var db = new DatabaseStore())
     {
         db.CerrarSesion(cuenta);
     }
 }
Exemplo n.º 8
0
        private void ConfigureCoderr(IApplicationBuilder app)
        {
            var url = new Uri("https://report.coderr.io/");

            Err.Configuration.Credentials(url,
                                          "2b3002d3ab3e4a57ad45cff2210221ab",
                                          "f381a5c9797f49bd8a3238b892d02806");
            Err.Configuration.ThrowExceptions = false;
            app.CatchMiddlewareExceptions();


            if (!HostConfig.Instance.IsConfigured)
            {
                return;
            }

            CoderrConfigSection config;

            try
            {
                var dbStore = new DatabaseStore(() => OpenConnection(CoderrClaims.SystemPrincipal));
                config = dbStore.Load <CoderrConfigSection>();
                if (config == null)
                {
                    return;
                }
            }
            catch (SqlException)
            {
                // We have not yet configured coderr.
                return;
            }


            // partitions allow us to see the number of affected installations
            Err.Configuration.AddPartition(x => x.AddPartition("InstallationId", config.InstallationId));

            Err.Configuration.FilterCollection.Add(new BundleSlowReportPosts());

            if (string.IsNullOrWhiteSpace(config.ContactEmail))
            {
                return;
            }

            // Allows us to notify you once the error is corrected.
            Err.Configuration.ReportPreProcessor = report =>
            {
                if (string.IsNullOrWhiteSpace(config.ContactEmail))
                {
                    return;
                }

                var collection  = CollectionBuilder.Feedback(config.ContactEmail, null);
                var collections = new List <ContextCollectionDTO>(report.ContextCollections.Length + 1);
                collections.AddRange(report.ContextCollections);
                collections.Add(collection);
            };
        }
Exemplo n.º 9
0
 public void Execute(DatabaseStore context)
 {
     context.Database.ExecuteSqlCommand(@"
         create table if not exists Preferences (
             key TEXT PRIMARY KEY,
             value TEXT,
             Discriminator TEXT
         );
     ");
 }
Exemplo n.º 10
0
 private void obtenerCuenta()
 {
     buttonEnabled = false;
     Task.Run(() =>
     {
         using (var db = new DatabaseStore())
         {
             cuentaLogin = db.InicioSesion(int.Parse(textbox.Text), Hasher.EncryptSHA1(passbox.Text));
         }
     });
 }
Exemplo n.º 11
0
 public override void Initialize()
 {
     // create a top-level DAI objects, there shouldn't be too many.
     // note '1' is the ID of the record we're interested in in 'app.Application' There should only be one record in this case
     // hard-coding the id ensures only one record is returned.
     // Better to constrain the table to only record, and remove the hard coded ID
     // Ultimately we make the whole issue go away and convert this configuration data to name-value pairs
     //settings = new DatabaseStore(new DatabaseRelation(1)).Read<BO.Settings>();
     //settings = new BO.Settings();
     names = new DatabaseStore().Read <Name, Names, Name>();
 }
Exemplo n.º 12
0
 public void Execute(DatabaseStore context)
 {
     context.Database.ExecuteSqlCommand(@"
         create table if not exists DatabaseMetadata (
             key TEXT PRIMARY KEY,
             value TEXT,
             Discriminator TEXT
         );
     ");
     context.SaveChanges();
     context.DatabaseMetadata.Add(new MetaDataKeyValuePair("db.version", "1"));
 }
Exemplo n.º 13
0
        public ApplicationInitialiser(DatabaseStore databaseStoreInterceptore, ILog log)
        {
            if (databaseStoreInterceptore == null)
            {
                throw new ArgumentNullException("databaseStoreInterceptore");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            this.databaseStoreInterceptore = databaseStoreInterceptore;
            this.log = log;
        }
Exemplo n.º 14
0
        public void ValidName_Add_AddsToDatabase()
        {
            // GIVEN
            const string ExpectedName = "ExpectedName";
            var          store        = new DatabaseStore();

            // WHEN
            store.Add(ExpectedName);

            // THEN
            var contains = store.GetTasks().Any(t => t.Name == ExpectedName);

            Assert.IsTrue(contains, "The added item should be available to others in the database.");
        }
Exemplo n.º 15
0
        private void load()
        {
            using (var bd = new DatabaseStore())
            {
                foreach (var h in bd.ObtenerHistorial(cuenta).GroupBy(ent => new { ent.FechaHora.Month, ent.FechaHora.Year }))
                {
                    seleccionMes.AddDropdownItem(new YearMonthTuple(h.Key.Year, h.Key.Month));

                    foreach (var g in h)
                    {
                        entradas.Add(g);
                    }
                }
            }

            seleccionMes.Current.Value = seleccionMes.Items.First();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Check for if collection is disposed already
        /// Used for State Transfer Purpose
        /// if Collection Name is not specified check for whole database disposed
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="colName"></param>
        /// <returns></returns>
        public bool HasDisposed(string dbName, string colName = "")
        {
            DatabaseExists(dbName);


            DatabaseStore database = (DatabaseStore)_databases[dbName];

            if (!String.IsNullOrEmpty(colName))
            {
                if (database.Collections.ContainsKey(colName))
                {
                    var collection = database.Collections[colName];
                    return(collection != null ? collection.HasDisposed : true);
                }
            }

            return(true);
        }
Exemplo n.º 17
0
        private void retirar(double cantidad)
        {
            using (var db = new DatabaseStore())
            {
                switch (db.RetiroUsuario(cuenta, cantidad))
                {
                case ResultadoOperacion.Correcto:
                    MostrarAlerta("Por favor tome su dinero al presionar una tecla\nRetiro correcto", true, false);
                    break;

                case ResultadoOperacion.NoDinero:
                    MostrarAlerta("El cajero no tiene suficientes billetes para realizar su operación\nIntente otra cantidad", false, true);
                    break;

                case ResultadoOperacion.NoSaldo:
                    MostrarAlerta("Usted no tiene suficiente saldo para realizar esta operación\nIntente una cantidad menor", false, true);
                    break;
                }
            }
        }
Exemplo n.º 18
0
 public void Execute(DatabaseStore context)
 {
     context.Database.ExecuteSqlCommand(@"
         create table if not exists Library (
             id INTEGER PRIMARY KEY,
             added TEXT,
             state INTEGER,
             libraryLocation TEXT,
             description TEXT,
             dataSourceId TEXT NOT NULL,
             sourceBookId TEXT NOT NULL,
             title TEXT,
             author TEXT,
             imageUrl TEXT,
             series TEXT,
             seriesPart NUMERIC,
             publicationDate TEXT,
             Discriminator TEXT
         );
     ");
 }
Exemplo n.º 19
0
        public bool CreateDatabase(DatabaseConfiguration configuration, NodeContext context, IDictionary <string, IDistribution> colDistributions)
        {
            lock (_databases)
            {
                if (!_databases.ContainsKey(configuration.Name))
                {
                    IDatabaseStore dbStore = new DatabaseStore();
                    if (((DatabaseStore)dbStore).Initialize(configuration, context, colDistributions))
                    {
                        _databases.Add(configuration.Name, dbStore);
                        return(true);
                    }
                }
                else
                {
                    throw new Exception("Database with specified name already exist.");
                }
            }

            return(false);
        }
Exemplo n.º 20
0
        public static void Main(string[] parameters)
        {
            // your code goes here
            DatabaseStore         _dbs = new DatabaseStore();
            DistributedCacheStore _dcs = new DistributedCacheStore();

            DataSource.DataSource _ds = new DataSource.DataSource(_dcs); // Attach

            for (int k = 0; k < 10; k++)
            {
                _dbs.StoreValue("key" + k, "value" + k); //Populate DatabaseStore with data
                _dcs.StoreValue("key" + k, "value" + k); //Distribute Data to DistributedCacheStore for current default "working node"
            }

            for (var i = 0; i < 10; i++)
            {
                new Thread(() =>
                {
                    // your code goes here
                    Random rnd          = new Random();
                    Stopwatch stopWatch = new Stopwatch();
                    string key          = string.Empty;
                    object d;

                    for (int t = 0; t < 50; t++)
                    {
                        key = "key" + rnd.Next(0, 9);
                        stopWatch.Reset();
                        stopWatch.Start();
                        d = _ds.GetValue(key);
                        stopWatch.Stop();

                        Console.WriteLine("[{0}] Request '{1}', response '{2}', time: {3} ms", Thread.CurrentThread.ManagedThreadId, key, d as string, stopWatch.ElapsedMilliseconds.ToString("0.00"));
                    }
                }).Start();
            }

            Console.ReadKey();
        }
Exemplo n.º 21
0
        public bool Initialize(DatabaseConfigurations configurations, NodeContext context, IDictionary <String, IDictionary <String, IDistribution> > distributionMaps)
        {
            _distributionMap = distributionMaps;

            foreach (DatabaseConfiguration dbConfig in configurations.Configurations.Values)
            {
                lock (_databases)
                {
                    if (!_databases.ContainsKey(dbConfig.Name))
                    {
                        IDatabaseStore dbStore = new DatabaseStore();
                        IDictionary <string, IDistribution> colDistributions;
                        _distributionMap.TryGetValue(dbConfig.Name, out colDistributions);
                        if (((DatabaseStore)dbStore).Initialize(dbConfig, context, colDistributions))
                        {
                            _databases.Add(dbConfig.Name, dbStore);
                        }
                    }
                }
            }

            return(true);
        }
Exemplo n.º 22
0
        private void revisarRetiro()
        {
            buttonEnabled = false;
            using (var db = new DatabaseStore())
            {
                var res = db.DepositoUsuario(cuenta, double.Parse(textbox.Text), CuentaDestino, out salida);
                switch (res)
                {
                case ResultadoOperacion.Correcto:
                    tiempoDeposito = Time.Current;
                    MostrarAlerta("Introduzca su efectivo usando cualquier tecla\nTiene 2 minutos para esta operación.", false, false);
                    Scheduler.AddDelayed(depositoFallido, 120000);
                    break;

                case ResultadoOperacion.NoCuenta:
                    OnAlertHide = null;
                    MostrarAlerta("Esta cuenta no existe o no permite depositos", true, true);
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 23
0
        public void Execute(DatabaseStore context)
        {
            var data  = File.ReadAllText(PreferencesFile);
            var lines = data.Split(new[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                var parsableLine = line;
                if (parsableLine.Contains("#"))
                {
                    var commentIndex = parsableLine.IndexOf('#');
                    parsableLine = parsableLine.Substring(0, commentIndex);
                }

                if (!parsableLine.Contains("="))
                {
                    continue;
                }

                var index = parsableLine.IndexOf('=');
                var key   = parsableLine.Substring(0, index);
                var val   = index + 1 < parsableLine.Length ? parsableLine.Substring(index + 1) : "";

                var kvp = context.Preferences.Find(key);
                if (kvp != null)
                {
                    kvp.Value = val;
                }
                else
                {
                    context.Add(new PreferenceKeyValuePair(key, val));
                }
                context.SaveChanges();
            }
            context.SaveChanges();
        }
Exemplo n.º 24
0
 public Startup()
 {
     _serviceRunner     = new ServiceRunner();
     ConfigurationStore = new DatabaseStore(() => DbConnectionFactory.Open(true));
 }
        public ControllerIntegrationTestBase() : base()
        {
            var databaseStoreLogger = new Mock <ILogger <DatabaseStore> >();

            _databaseStore = new DatabaseStore(databaseStoreLogger.Object, this._context, this._context_wp);
        }
Exemplo n.º 26
0
        private RecoveryOperationStatus ValidatePrequisites(RecoveryOperation opContext)
        {
            RecoveryOperationStatus state = new RecoveryOperationStatus(RecoveryStatus.Success);

            state.JobIdentifier = opContext.JobIdentifer;
            try
            {
                // must check state transfer
                //if (_context.StatusLatch.IsAnyBitsSet(BucketStatus.UnderStateTxfr))
                //{
                //    state.Status = RecoveryStatus.Success;//M_TODO: change this to false, once this state transfer code is complete
                //    if (LoggerManager.Instance.RecoveryLogger != null && LoggerManager.Instance.RecoveryLogger.IsInfoEnabled)
                //        LoggerManager.Instance.RecoveryLogger.Info("ShardRecoveryManager.Validate()", opContext.JobIdentifer + "  failed because node is in state transfer");
                //}

                if (state.Status == RecoveryStatus.Success)
                {
                    string path     = string.Empty;
                    string username = "";
                    string password = "";
                    Dictionary <string, Dictionary <string, string[]> > dbMap = new Dictionary <string, Dictionary <string, string[]> >();
                    switch (opContext.OpCode)
                    {
                    case RecoveryOpCodes.SubmitBackupJob:
                        SubmitBackupOpParams _bckpParam = (SubmitBackupOpParams)opContext.Parameter;
                        path     = _bckpParam.PersistenceConfiguration.FilePath;
                        dbMap    = _bckpParam.PersistenceConfiguration.DbCollectionMap;
                        username = _bckpParam.PersistenceConfiguration.UserName;
                        password = _bckpParam.PersistenceConfiguration.Password;
                        break;

                    case RecoveryOpCodes.SubmitRestoreJob:
                        SubmitRestoreOpParams _resParam = (SubmitRestoreOpParams)opContext.Parameter;

                        path     = Path.Combine(_resParam.PersistenceConfiguration.FilePath);
                        username = _resParam.PersistenceConfiguration.UserName;
                        password = _resParam.PersistenceConfiguration.Password;
                        dbMap    = _resParam.PersistenceConfiguration.DbCollectionMap;
                        List <string> shardNameList = new List <string>();
                        shardNameList.Add(_context.LocalShardName);
                        Impersonation impersonation = null;
                        bool          isSharedPath  = RecoveryFolderStructure.PathIsNetworkPath(path);
                        if (isSharedPath)
                        {
                            impersonation = new Impersonation(username, password);
                        }

                        state = RecoveryFolderStructure.ValidateFolderStructure(path, RecoveryJobType.DataRestore, false, shardNameList);

                        if (isSharedPath)
                        {
                            impersonation.Dispose();
                        }

                        if (state.Status == RecoveryStatus.Failure)
                        {
                            if (LoggerManager.Instance.RecoveryLogger != null && LoggerManager.Instance.RecoveryLogger.IsErrorEnabled)
                            {
                                LoggerManager.Instance.RecoveryLogger.Error("ShardRecoveryManager.Validate()", state.Message);
                            }
                            return(state);
                        }
                        else
                        {
                            #region validate files
                            string folderName = string.Empty;
                            string fileName   = dbMap.First().Key;
                            string folderPath = Path.Combine(path, folderName);
                            string filePath   = Path.Combine(folderPath, fileName);

                            isSharedPath = RecoveryFolderStructure.PathIsNetworkPath(folderPath);
                            bool fileExists = false;
                            if (isSharedPath)
                            {
                                BackupFile file = new BackupFile(fileName, folderPath, null, null);
                                impersonation = new Impersonation(username, password);
                                fileExists    = File.Exists(filePath);
                                impersonation.Dispose();
                            }
                            else
                            {
                                fileExists = File.Exists(filePath);
                            }

                            if (fileExists)
                            {
                                BackupFile file = new BackupFile(fileName, folderPath, username, password);


                                Alachisoft.NosDB.Core.Recovery.Persistence.BackupFile.Header header = file.ReadFileHeader();

                                if (!header.Database.ToLower().Equals(dbMap.First().Key))
                                {
                                    state.Status  = RecoveryStatus.Failure;
                                    state.Message = "Provided file does not contain the source database " + fileName;
                                    file.Close();
                                    return(state);
                                }
                                file.Close();
                            }
                            else
                            {
                                state.Status  = RecoveryStatus.Failure;
                                state.Message = "No file exists in the given folder";
                                return(state);
                            }

                            #endregion
                        }

                        break;
                    }

                    // this will only be false for backup
                    if (!Directory.Exists(path))
                    {
                        try
                        {
                            Impersonation impersonation = null;
                            if (RecoveryFolderStructure.PathIsNetworkPath(path))
                            {
                                impersonation = new Impersonation(username, password);
                            }

                            Directory.CreateDirectory(path);

                            if (dbMap.Count > 0)
                            {
                                // check space for backup job
                                long size = 0;
                                foreach (string db in dbMap.Keys)
                                {
                                    DatabaseStore database = _context.DatabasesManager.GetDatabase(db) as DatabaseStore;
                                    size = database.Size;
                                }

                                ulong availableFreeSpace = Util.DirectoryUtil.GetDiskFreeSpace(path);
                                ulong requiredSize       = (ulong)size;
                                if (availableFreeSpace > requiredSize)
                                {
                                    state.Status = RecoveryStatus.Success;
                                }
                                else
                                {
                                    state.Status  = RecoveryStatus.Failure;
                                    state.Message = "Available memory is less than the required memory for backup";
                                    return(state);
                                }
                            }
                            if (impersonation != null)
                            {
                                impersonation.Dispose();
                            }
                        }
                        catch (Exception ex)
                        {
                            state.Status  = RecoveryStatus.Failure;
                            state.Message = ex.Message;
                            if (LoggerManager.Instance.RecoveryLogger != null && LoggerManager.Instance.RecoveryLogger.IsErrorEnabled)
                            {
                                LoggerManager.Instance.RecoveryLogger.Error("ShardRecoveryManager.Validate()", ex.ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                state.Status  = RecoveryStatus.Failure;
                state.Message = exp.ToString();
                if (LoggerManager.Instance.RecoveryLogger != null && LoggerManager.Instance.RecoveryLogger.IsErrorEnabled)
                {
                    LoggerManager.Instance.RecoveryLogger.Error("ShardRecoveryManager.Validate()", opContext.JobIdentifer + " : " + exp.ToString());
                }
            }
            return(state);
        }
Exemplo n.º 27
0
 public void Setup()
 {
     _subject = new DatabaseStore();
     _subject.Open();
 }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            #region Display Header Info

            System.Console.ForegroundColor = ConsoleColor.DarkGreen;
            System.Console.WriteLine("---------------------------------------------------------------");
            System.Console.WriteLine("Welcome to NearMap Test ---------------------------------------");
            System.Console.WriteLine("------------------------ https://github.com/izevaka/nearmap-test");
            System.Console.WriteLine("Amir--Pour-----------------------------------------------------");
            System.Console.WriteLine("Mobile: 0414 888 931-------------------------------------------");
            System.Console.WriteLine("---------------------------------------------------------------");
            System.Console.ResetColor();

            #endregion

            #region Setting up log

            ILog log = LogManager.GetLogger(typeof(Program));

            FileInfo configFile = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.xml"));

            XmlConfigurator.ConfigureAndWatch(configFile);

            #endregion

            #region Composition root- Any kind of Dependency injector can be used to set it up

            DatabaseStore databaseStore = new DatabaseStore(log);

            ApplicationInitialiser applicationInitialiser = new ApplicationInitialiser(databaseStore, log);

            applicationInitialiser.Initialise();

            //getting all configs required for application
            CacheConfiguration cacheConfiguration = new CacheConfiguration();

            ICacheStoreAccelerator cacheStoreAccelerator = new CacheStoreAccelerator(cacheConfiguration, log);

            //this class helps local cache work faster, it adds more functionality
            LocalCacheStoreAccelerator localCacheAccelerator = new LocalCacheStoreAccelerator(cacheStoreAccelerator, cacheConfiguration, log);

            //this is the distributed cache
            DistributedCacheStore distributedCacheStore = new DistributedCacheStore(cacheConfiguration, log);

            //this class combines the localcache and distributed cache together  to provide a faster caching mechanism after a while
            //for more demanded objects, this class is the cache layer of the application
            SmartCacheStore fastCacheInterceptor = new SmartCacheStore(distributedCacheStore, localCacheAccelerator, log);

            //this class is responsible to retrieve the data either from cache layer or from database
            Repository repository = new Repository(fastCacheInterceptor, databaseStore, log);

            //this is the service that is going to expose to all consumers
            MyService myService = new MyService(repository);

            #endregion

            System.Console.WriteLine("Start up finished");
            System.Console.WriteLine("---------------------------------------------------------------");

            for (int i = 0; i < 10; i++)
            {
                new Thread(() =>
                {
                    //Sets the resolution of the timer. This has to be done per thread to ensure that 5ms sleep is actually 5 ms.
                    //http://stackoverflow.com/a/522681
                    timeBeginPeriod(5);

                    for (int j = 0; j < 50; j++)
                    {
                        string key = string.Format("key_{0}", random.Next(0, 9));

                        Stopwatch myStopwatch = new Stopwatch();

                        myStopwatch.Reset();
                        myStopwatch.Start();

                        var value = myService.GetItem(key);

                        myStopwatch.Stop();

                        var duration = myStopwatch.ElapsedMilliseconds;

                        System.Console.WriteLine("[{0}] Request '{1}', response '{2}', time: {3}",
                                                 Thread.CurrentThread.ManagedThreadId,
                                                 key,
                                                 value,
                                                 duration.ToString("F2"));

                        System.Console.ResetColor();
                    }

                    timeEndPeriod(5);
                }).Start();
            }

            System.Console.WriteLine("----E--N--D---");

            System.Console.Read();
        }