/// <summary>
 /// Initializes a new instance of the <see cref="RedisCache"/> class.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 public RedisCache(ConfigurationOptions configuration)
 {
     if (RedisCache.connection == null)
     {
         try
         {
             connectionTask = ConnectionMultiplexer.ConnectAsync(configuration);
             connectionTask.ContinueWith(t =>
                 {
                     lock (syncronizationObject)
                     {
                         if (RedisCache.connection == null)
                             RedisCache.connection = t.Result;
                     }
                     this.cache = RedisCache.connection.GetDatabase();
                     Trace.TraceInformation("Redis Cache Provider connection complete - Correlation Id = {0}", Trace.CorrelationManager.ActivityId);
                 });
         }
         catch (AggregateException age)
         {
             age.Handle(e =>
             {
                 Trace.TraceError("Redis Cache Provider error - Correlation Id = {0}\n {1}\n {2}", Trace.CorrelationManager.ActivityId, e.Message, e.StackTrace);
                 return true;
             });
         }
         catch (Exception ex)
         {
             Trace.TraceError("Redis Cache Provider exception - Correlation Id = {0}\n {1}\n {2}", Trace.CorrelationManager.ActivityId, ex.Message, ex.StackTrace);
         }
     }
 }
 public FrmModifyUser(IEngine engine, IDatabase db, OpenDMS.Storage.Security.Session session)
 {
     InitializeComponent();
     _engine = engine;
     _db = db;
     _session = session;
 }
Example #3
0
		private KeyValueCollection ExtendedProperties(IDatabase db, string schema, string entitytype, string entity, string column) 
		{
			KeyValueCollection hash = new KeyValueCollection();
			Recordset rs = db.ExecuteSql(
				String.Format(QUERY, 
				"'" + schema + "'",
				"'" + entitytype + "'",
				"'" + entity + "'", 
				((column == null) ? "null" : "'column'"), 
				((column == null) ? "null" : "'" + column + "'")
				)
				);
			
			if (rs != null) 
			{
				rs.MoveFirst();

				while (!rs.EOF && !rs.BOF)
				{
					hash.AddKeyValue( rs.Fields["name"].Value.ToString(), rs.Fields["value"].Value.ToString());
					rs.MoveNext();
				}
				rs.Close();
				rs = null;
			}
			return hash;
		}
        public DailyGrossRepositoryTest()
        {
            System.Configuration.ConnectionStringSettings cs = System.Configuration.ConfigurationManager.ConnectionStrings["aps"];

            _container = new WindsorContainer();
            _container
                .Register(Component.For<IDatabase>()
                    .ImplementedBy<Database>()
                    .DependsOn(Dependency.OnValue("provider", cs.ProviderName))
                    .DependsOn(Dependency.OnValue("connectionString", cs.ConnectionString))
                    //.DependsOn(Dependency.OnValue("provider", "System.Data.SqlClient"))
                    //.DependsOn(Dependency.OnValue("connectionString", "Data Source=dev-s01;Initial Catalog=aps;User ID=sa;Password=sql@dm1n"))
                )
                .Register(Component.For<IDailyGrossRepository>()
                    .ImplementedBy<DailyGrossRepository>()
                );

            _now = DateTime.Now;
            _ww = _now.WorkWeek();
            _db = _container.Resolve<IDatabase>();
            TestHelpers.TestData.Reset(_db);
            _employee = TestHelpers.TestData.GetEmployee(_db, "Tom");            

            _repos = _container.Resolve<IDailyGrossRepository>();
        }
Example #5
0
        public OrderRepo(IDatabase database)
        {
            if (database == null)
                throw new ArgumentNullException("database");

            _Database = database;
        }
        protected static void Generic_Constructs_The_Corrent_Many2One_Relationshps(IDatabase db)
        {
            var table1 = db.Tables[0];
            var table2 = db.Tables[1];

            Assert.That(table1.Relationships, Is.Not.Null);
            Assert.That(table2.Relationships, Is.Not.Null);
            Assert.That(table1.Relationships, Has.Count(1));
            Assert.That(table2.Relationships, Has.Count(1));
            Assert.That(table1.Relationships[0], Is.Not.Null);
            Assert.That(table2.Relationships[0], Is.Not.Null);
            Assert.That(table1.Relationships[0], Is.SameAs(table2.Relationships[0]));

            Relationship relationship = table1.Relationships[0];
            Assert.That(relationship, Is.Not.Null);
            Assert.That(relationship.PrimaryTable, Is.SameAs(table2));
            Assert.That(relationship.ForeignTable, Is.SameAs(table1));
            Assert.That(relationship.PrimaryCardinality, Is.EqualTo(Cardinality.Many));
            Assert.That(relationship.ForeignCardinality, Is.EqualTo(Cardinality.One));

            Assert.That(relationship.PrimaryKey, Is.Not.Null);
            Assert.That(relationship.PrimaryKey.Columns, Has.Count(1));
            Assert.That(relationship.ForeignKey.Columns, Has.Count(1));
            Assert.That(relationship.PrimaryKey.Keytype, Is.EqualTo(DatabaseKeyType.Primary));
            Assert.That(relationship.ForeignKey.Keytype, Is.EqualTo(DatabaseKeyType.Foreign));
        }
Example #7
0
        private static void SetupDatabase(IDatabase db)
        {
            var table1 = CreateTable(db, "Table1");
            var table2 = CreateTable(db, "Table2");

            table1.CreateRelationshipUsing(table1.Keys[0], table2.Keys[1]);
        }
Example #8
0
        internal static void ResetBlank(IDatabase db)
        {
			/*
            File.Copy(Path.Combine(TestHelpers.TestPaths.TestFolderPath, "src\\App.Config"),
                                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ica.aps.services.dll.config"), true);
			*/
            if (db.IsSqlServerCeProvider)
            {
                File.Copy(Path.Combine(TestHelpers.TestPaths.TestDataFolderPath, "aps_backup.sdf"),
                                    Path.Combine(TestHelpers.TestPaths.TestDataFolderPath, "aps.sdf"), true);
            }
            else if (db.IsSqlServerProvider)
            {
                using (IDbConnection conn = db.Create())
                {
                    conn.Open();

                    conn.ChangeDatabase("master");
                    conn.Execute("DROP DATABASE aps");
                    conn.Execute("CREATE DATABASE aps");

                    /*
                    string sql = string.Format(@"RESTORE DATABASE {0} FROM DISK = '{1}' WITH REPLACE",
                                                conn.Database,
                                                Path.Combine(TestHelpers.TestPaths.TestDataFolderPath, "aps.bak"));
                    // change to master
                    conn.ChangeDatabase("master");
                    // perform restore
                    conn.Execute(sql);
                    */
                }
            }
        }
 public void Up(IDatabase db)
 {
     db.CreateTable(_tableName)
         .WithPrimaryKeyColumn(TimestampColumnName, DbType.Int64)
         .WithPrimaryKeyColumn(ModuleColumnName, DbType.String).OfSize(MigrationExportAttribute.MaximumModuleNameLength)
         .WithNullableColumn(TagColumnName, DbType.String).OfSize(2000);
 }
 public UploadContent(IDatabase db, Data.Version version,
     int sendTimeout, int receiveTimeout, int sendBufferSize, int receiveBufferSize)
     : base(sendTimeout, receiveTimeout, sendBufferSize, receiveBufferSize)
 {
     _db = db;
     _version = version;
 }
 public ShowEmployeesCommand(
     string companyName,
     IDatabase db)
     : base(db)
 {
     this.companyName = companyName;
 }
        private static void AssertMig20(IDatabase db, bool exists)
        {
            if (IntegrationTestContext.IsScripting) return;

            db.Execute(context =>
                {
                    IDbCommand command = context.CreateCommand();
                    command.CommandText = @"SELECT * FROM ""Mig20""";
                    try
                    {
                        context.CommandExecutor.ExecuteNonQuery(command);
                        if (!exists)
                        {
                            Assert.Fail("The table 'Mig20' should not exist at this point.");
                        }
                    }
                    catch (Exception x)
                    {
                        if (!x.IsDbException())
                        {
                            throw;
                        }
                        if (exists)
                        {
                            Assert.Fail("The table 'Mig20' should exist at this point. But there an error occurred: {0}", x.Message);
                        }
                    }
                });
        }
Example #13
0
 public MetadataProvider(IDatabase database, IEnumerable<MetadataBase> metadataProviders,
                         TvDbProvider tvDbProvider)
 {
     _database = database;
     _metadataProviders = metadataProviders;
     _tvDbProvider = tvDbProvider;
 }
 public DownloadGroup(IDatabase db, Security.Group group,
     int sendTimeout, int receiveTimeout, int sendBufferSize, int receiveBufferSize)
     : base(sendTimeout, receiveTimeout, sendBufferSize, receiveBufferSize)
 {
     _db = db;
     _group = group;
 }
Example #15
0
        public void Up(IDatabase db)
        {
            if (!this.IsFeatureSupported(db))
            {
                return;
            }
            MySqlHelper.ActivateStrictMode(db);

            db.CreateTable(Tables[0].Name)
              .WithPrimaryKeyColumn(Tables[0].Columns[0], DbType.Int32).AsIdentity()
              .WithNotNullableColumn(Tables[0].Columns[1], DbType.Decimal).OfSize(3)
              .WithNotNullableColumn(Tables[0].Columns[2], DbType.Decimal).OfSize(5, 2);

            db.Execute(GetInsertStatement((decimal)Tables[0].Value(0, 2) + 0.003m)); // the extra precision should be cut off silently
            db.Execute(context =>
                {
                    IDbCommand command = context.CreateCommand();
                    command.CommandText = GetInsertStatement(1000m);
                    Log.Verbose(LogCategory.Sql, command.CommandText);
                    try
                    {
                        command.ExecuteNonQuery();
                        Assert.Fail("The previous query should have failed.");
                    }
                    catch (Exception x)
                    {
                        if (!x.IsDbException())
                        {
                            throw;
                        }
                    }
                });
        }
Example #16
0
 public CreateCompany(IDatabase db, string companyName, string ceoFirstName, string ceoLastName, decimal salary)
     : base(db, companyName)
 {
     this.ceoFirstName = ceoFirstName;
     this.ceoLastName = ceoLastName;
     this.salary = salary;
 }
Example #17
0
 public void Up(IDatabase db)
 {
     db.CreateTable(FjosTable)
         .WithPrimaryKeyColumn("Id", DbType.Int64).AsIdentity()
         .WithNotNullableColumn("BondegardId", DbType.Int64);
     db.Tables[FjosTable].AddForeignKeyTo(BondegardTable).Through("BondegardId", "Id");
 }
 public DownloadAndUpgradeViewModel(IShellViewModel shell, IDatabase database, IConfigurationManager configuration, ICachedService cashedService, IEventAggregator eventAggregator)
     : base(shell, database, configuration, cashedService, eventAggregator)
 {
     _webClient = new WebClient();
     _webClient.DownloadFileCompleted += OnDownloadFileCompleted;
     _webClient.DownloadProgressChanged += OnDownloadProgressChanged;
 }
 internal CommandController(IDatabase database, IFileStoreProvider fileStore)
 {
     this.database = database;
     this.fileStore = fileStore;
     var thread = new Thread(SaveLoop);
     thread.Start();
 }
Example #20
0
        public void Up(IDatabase db)
        {
            db.CreateTable(Tables[0].Name)
                .WithPrimaryKeyColumn(Tables[0].Columns[0], DbType.Int32).AsIdentity()
                .WithNotNullableColumn(Tables[0].Columns[1], DbType.String)
                .WithNotNullableColumn(Tables[0].Columns[2], DbType.AnsiString);

            db.Execute(context =>
                {
                    bool isCe4Provider = db.Context.ProviderMetadata.Name == ProviderNames.SqlServerCe4;
                    IDbCommand command = context.Connection.CreateCommand();
                    command.Transaction = context.Transaction;
                    IDataParameter text = command.AddParameter("@text", DbType.String, Tables[0].Value(0, 1));
                    if (isCe4Provider)
                    {
                        SetSqlDbTypeToNText(text);
                    }
                    IDataParameter ansiText = command.AddParameter("@ansiText", isCe4Provider ? DbType.String : DbType.AnsiString, Tables[0].Value(0, 2));
                    if (isCe4Provider)
                    {
                        SetSqlDbTypeToNText(ansiText);
                    }
                    command.CommandText = string.Format(CultureInfo.InvariantCulture, @"INSERT INTO ""{0}"" (""{1}"", ""{2}"") VALUES ({3}, {4})",
                        Tables[0].Name,
                        Tables[0].Columns[1],
                        Tables[0].Columns[2],
                        context.ProviderMetadata.GetParameterSpecifier(text),
                        context.ProviderMetadata.GetParameterSpecifier(ansiText));
                    context.CommandExecutor.ExecuteNonQuery(command);
                });
        }
Example #21
0
 public EpisodeProvider(IDatabase database, TvDbProvider tvDbProviderProvider,
         SeasonProvider seasonProvider)
 {
     _tvDbProvider = tvDbProviderProvider;
     _seasonProvider = seasonProvider;
     _database = database;
 }
 public EventStore(
     IEventPublisher publisher,
     IDatabase<EventDescriptors> database)
 {
     _publisher = publisher;
     _database = database;
 }
 public SampleDevelopmentEnvironment()
 {
     AvailableDatabases = new IDatabase[]
     {
         new SqlServerDatabase("localhost", "Data Source=localhost;Initial Catalog=test;User ID=AppUser;Password=AppUser;MultipleActiveResultSets=True")
     };
 }
Example #24
0
        public bool Initialize(string connString, ConnectionType type = ConnectionType.MYSQL)
        {
            connectionString = connString;
            connSettings = new ConnectorSettings(type);
            querySettings = new QuerySettings(type);

            if (type == ConnectionType.MYSQL)
                db = new MySqlDatabase(this);
            else if (type == ConnectionType.MSSQL)
                db = new MSSqlDatabase(this);

            var isOpen = false;

            try
            {
                using (var connection = CreateConnection())
                    isOpen = connection.State == ConnectionState.Open;
            }
            catch
            {
                return false;
            }

            return isOpen;
        }
        /// <summary>
        /// 国资处经费申请内容
        /// </summary>
        /// <param name="request"></param>
        /// <param name="user"></param>
        /// <param name="database"></param>
        /// <returns></returns>
        public static AssetFundApply GetAssetFundApply(this HttpRequest request, User user, IDatabase database)
        {
            var assetFundApply = request.getAssetFundApply(database);
            assetFundApply.Quantity = request.GetInt("Quantity").Value;
            //assetFundApply.BudgetAmount = request.GetInt("BudgetAmount").Value;
            //assetFundApply.BidControlAmount = request.GetInt("BidControlAmount").Value;
            //assetFundApply.DeviceValue = request.GetInt("DeviceValue").Value;
            //assetFundApply.TradeAgentFee = request.GetInt("TradeAgentFee").Value;
            assetFundApply.ApplyTotalAmount = request.GetInt("ApplyTotalAmount").Value;
            if (request.GetBoolean("IsCommit").Value)
            {
                assetFundApply.State = AssetFundApplyState.Submit;
            }else
            {
                assetFundApply.State = AssetFundApplyState.UnSubmit;
            }
            assetFundApply.Operator = user;
            assetFundApply.ModifyTime = DateTime.Now;
            if (assetFundApply.IsNew)
            {
                assetFundApply.OperateTime = DateTime.Now;
            }

            return assetFundApply;
        }
        public CashFlowTypesViewModel(IShellViewModel shell, IDatabase database, IConfigurationManager configuration, ICachedService cashedService, IEventAggregator eventAggregator)
            : base(shell, database, configuration, cashedService, eventAggregator)
        {
            SuppressEvent = false;
            _cashFlows = new BindableCollectionExt<CashFlow>();
            _cashFlows.PropertyChanged += (s, e) =>
            {
                OnPropertyChanged(s, e);
                CachedService.Clear(CachedServiceKeys.AllCashFlows);
            };

            _cashFlowGroups = new BindableCollectionExt<CashFlowGroup>();
            _cashFlowGroups.PropertyChanged += (s, e) =>
            {
                if (SuppressEvent == true)
                {
                    return;
                }
                OnPropertyChanged(s, e);

                CachedService.Clear(CachedServiceKeys.AllCashFlowGroups);
                CachedService.Clear(CachedServiceKeys.AllCashFlows);
                var cashFlowGroup = s as CashFlowGroup;
                _cashFlows.Where(x => x.CashFlowGroupId == cashFlowGroup.Id)
                    .ForEach(x => x.Group = cashFlowGroup);
                NewCashFlowGroup = null;
                NewCashFlowGroup = CashFlowGroups.First();
            };
        }
Example #27
0
        private static void TestArtist(IDatabase db, DALFactory dalFactory)
        {
            Console.WriteLine("*************************************");
            Console.WriteLine("ARTIST TEST");

            IArtistDAO artistDAO = dalFactory.CreateArtistDAO(db);

            Console.WriteLine("\nAll artists:");
            foreach (var artist in artistDAO.GetAll()) {
                Console.WriteLine(artist);
            }

            Console.WriteLine("\nArtist with ID=1:");
            Console.WriteLine(artistDAO.GetById(1));

            Artist artist1 = new Artist() {
                Name = "Stefan the Rösch",
                CategoryId = 1,
                CountryId = 25
            };
            Artist newArtist = artistDAO.Create(artist1);
            Console.WriteLine("New Artist: " + newArtist);
            Console.WriteLine("Inserted Artist: " + artist1);

            artist1.Name = "Christoph the Wurst";
            artistDAO.Update(artist1);
            Console.WriteLine("Updated artist: " + artist1);

            artistDAO.Delete(artist1);
            Console.WriteLine("\nArtist deleted");
        }
Example #28
0
        internal static TransactionContext EnsureTransaction(ref Transaction transaction, IDatabase database)
        {
            TransactionContext result = null;

            if (transaction != null)
            {
                if (transaction.Aborted)
                {
                    throw new System.Transactions.TransactionAbortedException();
                }

                // Just a mock result
                result = new TransactionContext();
            }
            else
            {
                // Create a local transaction for the current operation

                System.Transactions.CommittableTransaction localTransaction = CreateDefaultTransaction();
                transaction = Create(localTransaction);

                result = new TransactionContext(localTransaction);
            }

            transaction.Subscribe(database.DatabaseEngine.TransactionHandler);
            // database.DatabaseEngine.TransactionHandler.EnsureSubscription(transaction);

            return result;
        }
Example #29
0
        public static void RedisConnectionAndUpload(string connectionString)
        {
            var muxer = ConnectionMultiplexer.Connect(configuration: connectionString);
            
                conn = muxer.GetDatabase();
            muxer.Wait(conn.PingAsync());

            List<City> citys = CityDataSource.CityDataSource.GetCitys();

            if (conn.StringGet("IsValue").IsNull)
            {
                int i = 0;

                citys.Take(1000).ToList().ForEach(c =>
                {
                    i++;
                    conn.HashSetAsync("Citys:Data:" + c.Id.ToString(), c.ToHashEntries());

                    List<string> prefix = GetPrefix(c.Name);

                    prefix.Concat(GetPrefix(c.Code));

                    if (!string.IsNullOrEmpty(c.Name)) 
                        conn.SortedSetAdd(key: "CityName", member: c.Name, score: 0);
                    if (!string.IsNullOrEmpty(c.Code))
                        conn.SortedSetAdd(key: "CityCode", member: c.Code, score: 0);

                    foreach (var p in prefix)
                    {
                        conn.SortedSetAdd("Citys:index:" + p, c.Id, 0);
                    }
                });
                conn.StringSet(key: "IsValue", value: true);
            }
        }
 public LegacySnapshotCreator(IStoreEvents store, IDatabase database)
 {
     Contract.Requires<ArgumentNullException>(store != null, "store");
     Contract.Requires<ArgumentNullException>(database != null, "database");
     _store = store;
     _db = database;
 }
Example #31
0
        public JsonNetResult Sortables()
        {
            var accountNameKey = Common.GetSubDomain(Request.Url);

            List <ProductSearchSortable> sortables = null;

            #region (Plan A) Get data from Redis Cache

            try
            {
                //First we attempt to get tags from the Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string hashKey   = accountNameKey + ":search";
                string hashField = "sortables:products";

                var redisValue = cache.HashGet(hashKey, hashField);

                if (redisValue.HasValue)
                {
                    sortables = JsonConvert.DeserializeObject <List <ProductSearchSortable> >(redisValue);
                }
            }
            catch (Exception e)
            {
                var error = e.Message;
                //Log error message for Redis call
            }

            #endregion

            if (sortables == null)
            {
                #region (Plan B) Get data from WCF

                var applicationSearchServiceClient = new ApplicationSearchService.ApplicationSearchServiceClient();

                try
                {
                    applicationSearchServiceClient.Open();
                    sortables = applicationSearchServiceClient.GetProductSortables(accountNameKey, Common.SharedClientKey).ToList();

                    //Close the connection
                    WCFManager.CloseConnection(applicationSearchServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(applicationSearchServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = sortables;

            return(jsonNetResult);
        }
Example #32
0
        bool ParseClasses(string iFileName)
        {
            int          num = 0;
            StreamReader iStream;

            try
            {
                iStream = new StreamReader(iFileName);
            }
            catch (Exception ex)
            {
                Exception ex3 = ex;
                Interaction.MsgBox(ex3.Message, MsgBoxStyle.Critical, "IO CSV Not Opened");
                return(false);
            }
            int num2 = 0;
            int num3 = 0;
            int num4 = 0;

            try
            {
                string iLine;
                do
                {
                    iLine = FileIO.ReadLineUnlimited(iStream, '\0');
                    if (iLine != null)
                    {
                        if (!iLine.StartsWith("#"))
                        {
                            num4++;
                            if (num4 >= 9)
                            {
                                this.BusyMsg(Strings.Format(num2, "###,##0") + " records parsed.");
                                num4 = 0;
                            }
                            string[] array     = CSV.ToArray(iLine);
                            string   uidEntity = "";
                            if (array.Length > 1)
                            {
                                int index = -2;
                                if (array[0].StartsWith("Pets."))
                                {
                                    uidEntity = "Pets_" + array[1];
                                    index     = DatabaseAPI.NidFromUidEntity(uidEntity);
                                }
                                else if (array[0].StartsWith("Villain_Pets."))
                                {
                                    uidEntity = "Pets_" + array[1];
                                    index     = DatabaseAPI.NidFromUidEntity(uidEntity);
                                }
                                if (index > -2)
                                {
                                    if (index < 0)
                                    {
                                        IDatabase        database            = DatabaseAPI.Database;
                                        SummonedEntity[] summonedEntityArray = (SummonedEntity[])Utils.CopyArray(database.Entities, new SummonedEntity[DatabaseAPI.Database.Entities.Length + 1]);
                                        database.Entities = summonedEntityArray;
                                        DatabaseAPI.Database.Entities[DatabaseAPI.Database.Entities.Length - 1] = new SummonedEntity();
                                        SummonedEntity entity = DatabaseAPI.Database.Entities[DatabaseAPI.Database.Entities.Length - 1];
                                        entity.UID = uidEntity;
                                        entity.nID = DatabaseAPI.Database.Entities.Length - 1;
                                        index      = entity.nID;
                                    }
                                    SummonedEntity entity2 = DatabaseAPI.Database.Entities[index];
                                    entity2.DisplayName          = array[2];
                                    entity2.ClassName            = "Class_Minion_Pets";
                                    entity2.nClassID             = DatabaseAPI.NidFromUidClass(entity2.ClassName);
                                    entity2.EntityType           = Enums.eSummonEntity.Pet;
                                    entity2.PowersetFullName     = new string[1];
                                    entity2.nPowerset            = new int[1];
                                    entity2.PowersetFullName[0]  = array[0];
                                    entity2.nPowerset[0]         = DatabaseAPI.NidFromUidPowerset(entity2.PowersetFullName[0]);
                                    entity2.UpgradePowerFullName = new string[0];
                                    entity2.nUpgradePower        = new int[0];
                                    num++;
                                }
                                else
                                {
                                    num3++;
                                }
                            }
                        }
                        num2++;
                    }
                }while (iLine != null);
            }
            catch (Exception ex2)
            {
                Exception exception = ex2;
                iStream.Close();
                Interaction.MsgBox(exception.Message, MsgBoxStyle.Critical, "Entity CSV Parse Error");
                return(false);
            }
            iStream.Close();
            DatabaseAPI.SaveMainDatabase();
            this.DisplayInfo();
            Interaction.MsgBox(string.Concat(new string[]
            {
                "Parse Completed!\r\nTotal Records: ",
                Conversions.ToString(num2),
                "\r\nGood: ",
                Conversions.ToString(num),
                "\r\nRejected: ",
                Conversions.ToString(num3)
            }), MsgBoxStyle.Information, "File Parsed");
            return(true);
        }
Example #33
0
 public StoryRepository(IDatabase database)
     : base(database)
 {
 }
        internal void Remove(string key)
        {
            IDatabase db = _redis.GetDatabase(_cacheOption.DataBaseIndex);

            db.KeyDelete(key);
        }
Example #35
0
 public static Snapshot <T> StartSnapshot <T>(this IDatabase d, T obj)
 {
     return(new Snapshot <T>(d.PocoDataFactory.ForType(obj.GetType()), obj));
 }
Example #36
0
 public static int Update <T>(this IDatabase d, T obj, Snapshot <T> snapshot)
 {
     return(d.Update(obj, snapshot.UpdatedColumns()));
 }
Example #37
0
 public RoleRepo(IDatabase database) : base(database)
 {
 }
Example #38
0
 public RedisCacheService(IConnectionMultiplexer connectionMultiplexer)
 {
     _db = connectionMultiplexer.GetDatabase();
 }
Example #39
0
 public DynamicViewSet(IDatabase database, Func <DataEventTransaction, Task> asyncListener)
 {
     this.Id            = Guid.NewGuid().ToString();
     this.Database      = database;
     this.asyncListener = asyncListener;
 }
Example #40
0
        public void TestDictionary()
        {
            IDatabase             db   = null;
            ConnectionMultiplexer conn = null;

            try
            {
                var args = ArgumentParser.Parse(CacheConfigurationSettings.Instance.Handlers.FirstOrDefault(x => x.Type.ToLower().Contains("redis")).Arguments);

                conn = StackExchange.Redis.ConnectionMultiplexer.Connect(args[0].ToString());
                db   = conn.GetDatabase(0);
            }
            catch (Exception ex)
            {
                Assert.Inconclusive("Unable to create Redis Connection");
            }

            db.KeyDelete("Test");
            db.KeyDelete("Test2");
            db.KeyDelete("Dictionary:SeTest");
            db.KeyDelete("List:SeTest");
            db.KeyDelete("Set:SeTest");

            Item item = null; // new Item() { ID = 1, Name = "Bill" };

            item = new Item()
            {
                ID = 1, Name = "Bill"
            };
            db.HashSet("Test", new HashEntry[] { new HashEntry(item.ID, JsonConvert.SerializeObject(item)) });
            item = new Item()
            {
                ID = 2, Name = "Two"
            };
            db.HashSet("Test", "2", JsonConvert.SerializeObject(item));
            db.HashSet("Test2", Convert(item));

            var hg    = db.HashGetAll("Test");
            var dict1 = hg.ToDictionary(x => int.Parse(x.Name), y => JsonConvert.DeserializeObject <Item>(y.Value));
            var dict  = new Dictionary <int, Item>();

            //var dict = hg.ToDictionary<HashEntry, int>(x => int.Parse(x.Name));
            db.HashIncrement("Test2", "Count");
            db.HashIncrement("Test2", "Count");
            db.HashIncrement("Test2", "Count");
            db.HashIncrement("Test2", "Count");
            db.HashIncrement("Test2", "Count");

            //RedisValue
            var hashresults = db.HashGetAll("Test2");
            //StackExchange.Redis.ExtensionMethods.ToDictionary()

            var newItem = Convert <Item>(hashresults);

            //var d = new StackExchange.Redis.DataTypes.RedisTypeFactory(conn).GetDictionary<int, Item>("SeTest");
            ////var d = new StackExchange.Redis.DataTypes.Collections.RedisDictionary<int, Item>(db, "SeTest");
            //item = new Item() { ID = 1, Name = "Bill" };
            //d.Add(item.ID, item);
            //item = new Item() { ID = 2, Name = "Two" };
            //d.Add(item.ID, item);

            //var s = new StackExchange.Redis.DataTypes.RedisTypeFactory(conn).GetSet<Item>("SeTest");
            ////var d = new StackExchange.Redis.DataTypes.Collections.RedisDictionary<int, Item>(db, "SeTest");
            //item = new Item() { ID = 1, Name = "Bill" };
            //s.Add(item);
            //item = new Item() { ID = 2, Name = "Two" };
            //s.Add(item);

            //var l = new StackExchange.Redis.DataTypes.RedisTypeFactory(conn).GetList<Item>("SeTest");
            ////var d = new StackExchange.Redis.DataTypes.Collections.RedisDictionary<int, Item>(db, "SeTest");
            //item = new Item() { ID = 1, Name = "Bill" };
            //l.Add(item);
            //item = new Item() { ID = 2, Name = "Two" };
            //l.Add(item);

            //var redis = new RedisCacheHandler();
            //string key = DateTime.UtcNow.ToOADate().ToString();

            //handler.Register<Item>(key, () => , TimeSpan.FromSeconds(30));

            //Assert.AreEqual(true, handler.Exists(key));
            //var val = handler.Retrieve<Item>(key);
            //Assert.IsNotNull(val);
            //Assert.AreEqual(1, val.ID);
            //Assert.AreEqual("Bill", val.Name);
            //handler.Remove(key);
            //Assert.AreEqual(false, handler.Exists(key));
        }
Example #41
0
 internal DatabaseCache(IDatabase database) => this.database = database;
 public AssignXSpringToNode(IDatabase dbctx) : base(dbctx)
 {
 }
        public ListTicketsCommand(IDatabase database)
        {
            Guard.WhenArgument(database, "database").IsNull().Throw();

            this.database = database;
        }
Example #44
0
 public RawSqlStatement(IDatabase database, string sql, object parameters) : base(database)
 {
     Sql        = sql;
     Parameters = parameters;
 }
Example #45
0
        /// <summary>
        /// Update the destination database using data from source database.
        /// </summary>
        /// <param name="project">The project instance.</param>
        /// <param name="destination">The destination database.</param>
        /// <param name="source">The source database.</param>
        public static void UpdateDatabase(this IProjectContainer project, IDatabase destination, IDatabase source)
        {
            if (destination != null && source != null)
            {
                bool isDirty = destination.Update(source, out var records);

                if (isDirty && records != null)
                {
                    var builder = project.Databases.ToBuilder();
                    var index   = builder.IndexOf(destination);
                    destination.Records = records.ToImmutable();
                    builder[index]      = destination;

                    var previous = project.Databases;
                    var next     = builder.ToImmutable();
                    project?.History?.Snapshot(previous, next, (p) => project.Databases = p);
                    project.Databases = next;
                }
            }
        }
Example #46
0
 public static string GetNamespaceDeclaration(string baseNamespace, IDatabase database) => "namespace " + baseNamespace + ".Modification {";
Example #47
0
 public LoginController(IRedisConnectionFactory caching)
 {
     cachingDB = caching.Connection().GetDatabase();
 }
Example #48
0
 public AuditDatabase(IDatabase databaseImplementation, IAuditLog auditLog, string user)
 {
     this.databaseImplementation = databaseImplementation;
     this.auditLog = auditLog;
     this.user     = user;
 }
Example #49
0
 internal Quotes(IDatabase database)
 {
     _database = database ?? throw new ArgumentException("IDatabase object cannot be null.");
 }
Example #50
0
 public SelectController(IDatabase database)
 {
     _database = database;
 }
Example #51
0
        public object getHashs(string hash, IDBTableDesc desc)
        {
            if (_conn == null)
            {
                // error: without _conn
                Debug.logger.log(LogType.LOG_ERR, "DBRedisDB name[" + this.name + "] getHashs hash[" + hash + "] without connection!");
                return(null);
            }

            IDatabase     db  = _conn.GetDatabase();
            ExpandoObject ret = new ExpandoObject();
            IDictionary <string, object> IRet = (IDictionary <string, object>)ret;

            HashEntry[] hashs = db.HashGetAll(hash);
            for (int i = 0; i < hashs.Length; ++i)
            {
                AEDBDataType dt = desc.getDataType(hashs[i].Name);
                switch (dt)
                {
                case AEDBDataType.ADDT_INT:
                    IRet[hashs[i].Name] = (int)hashs[i].Value;
                    break;

                case AEDBDataType.ADDT_UINT:
                    IRet[hashs[i].Name] = (uint)hashs[i].Value;
                    break;

                case AEDBDataType.ADDT_FLOAT:
                    IRet[hashs[i].Name] = (float)hashs[i].Value;
                    break;

                case AEDBDataType.ADDT_LONG:
                    IRet[hashs[i].Name] = (long)hashs[i].Value;
                    break;

                case AEDBDataType.ADDT_ULONG:
                    IRet[hashs[i].Name] = (ulong)hashs[i].Value;
                    break;

                case AEDBDataType.ADDT_DOUBLE:
                    IRet[hashs[i].Name] = (double)hashs[i].Value;
                    break;

                case AEDBDataType.ADDT_BINARY:
                {
                    object o = AEDBHelper.unserializeObject(hashs[i].Value);
                    IRet[hashs[i].Name] = o;
                }
                break;

                //case AEDBDataType.ADDT_STRING: // deault is string
                default:
                    IRet[hashs[i].Name] = (string)hashs[i].Value;
                    break;
                }
            }

            if (_expireTime > 0)
            {
                // update expire time
                db.KeyExpire(hash, TimeSpan.FromSeconds(_expireTime));
            }

            return(ret);
        }
Example #52
0
        private static void AssertDataTypesData(IDatabase korm)
        {
            List <DataTypesData> actualData = korm.Query <DataTypesData>().OrderBy(item => item.Id).ToList();

            actualData.Should().BeEquivalentTo(GetDataTypesData());
        }
        public bool SetValue(string key, byte[] value, TimeSpan timeout)
        {
            IDatabase redisDB = getRedisDB();

            return(redisDB.StringSet(key, value, timeout));
        }
Example #54
0
        public bool setHash(string hash, string field, object val, IDBTableDesc desc)
        {
            if (_conn == null)
            {
                // error: without _conn
                // important: don't log val, or may expose sensitive data!!!
                Debug.logger.log(LogType.LOG_ERR, "DBRedisDB name[" + this.name + "] setHash hash[" + hash + "] field[" + field + "] without connection!");
                return(false);
            }

            IDatabase    db  = _conn.GetDatabase();
            bool         ret = true;
            AEDBDataType dt  = desc.getDataType(field);

            switch (dt)
            {
            case AEDBDataType.ADDT_INT:
                ret = db.HashSet(hash, field, (int)val);
                break;

            case AEDBDataType.ADDT_UINT:
                ret = db.HashSet(hash, field, (uint)val);
                break;

            case AEDBDataType.ADDT_FLOAT:
                ret = db.HashSet(hash, field, (float)val);
                break;

            case AEDBDataType.ADDT_LONG:
                ret = db.HashSet(hash, field, (long)val);
                break;

            case AEDBDataType.ADDT_ULONG:
                ret = db.HashSet(hash, field, (ulong)val);
                break;

            case AEDBDataType.ADDT_DOUBLE:
                ret = db.HashSet(hash, field, (double)val);
                break;

            case AEDBDataType.ADDT_BINARY:
            {
                byte[] objBytes = AEDBHelper.serializeObject(val);
                ret = db.HashSet(hash, field, objBytes);
            }
            break;

            //case AEDBDataType.ADDT_STRING: // deault is string
            default:
                ret = db.HashSet(hash, field, (string)val);
                break;
            }

            if (!ret)
            {
                // error: without _conn
                // important: don't log val, or may expose sensitive data!!!
                Debug.logger.log(LogType.LOG_ERR, "DBRedisDB name[" + this.name + "] setHash hash[" + hash + "] field[" + field + "] failed!");
                return(false);
            }

            if (_expireTime > 0)
            {
                // update expire time
                db.KeyExpire(hash, TimeSpan.FromSeconds(_expireTime));
            }

            return(ret);
        }
Example #55
0
 public RedisCacheExtention()
 {
     _cacheProvider = new RedisCacheDatabaseProvider();
     _db            = _cacheProvider.GetDatabase();
 }
Example #56
0
        public bool setHashs(string hash, List <KeyValuePair <string, object> > par, IDBTableDesc desc)
        {
            if (_conn == null)
            {
                // error: without _conn
                // important: don't log par, or may expose sensitive data!!!
                Debug.logger.log(LogType.LOG_ERR, "DBRedisDB name[" + this.name + "] setHashs hash[" + hash + "] without connection!");
                return(false);
            }

            IDatabase db  = _conn.GetDatabase();
            bool      ret = true;

            HashEntry[] hashs = new HashEntry[par.Count];
            for (int i = 0; i < par.Count; ++i)
            {
                AEDBDataType dt = desc.getDataType(par[i].Key);
                switch (dt)
                {
                case AEDBDataType.ADDT_INT:
                    hashs[i] = new HashEntry(par[i].Key, (int)par[i].Value);
                    break;

                case AEDBDataType.ADDT_UINT:
                    hashs[i] = new HashEntry(par[i].Key, (uint)par[i].Value);
                    break;

                case AEDBDataType.ADDT_FLOAT:
                    hashs[i] = new HashEntry(par[i].Key, (float)par[i].Value);
                    break;

                case AEDBDataType.ADDT_LONG:
                    hashs[i] = new HashEntry(par[i].Key, (long)par[i].Value);
                    break;

                case AEDBDataType.ADDT_ULONG:
                    hashs[i] = new HashEntry(par[i].Key, (ulong)par[i].Value);
                    break;

                case AEDBDataType.ADDT_DOUBLE:
                    hashs[i] = new HashEntry(par[i].Key, (double)par[i].Value);
                    break;

                case AEDBDataType.ADDT_BINARY:
                {
                    byte[] objBytes = AEDBHelper.serializeObject(par[i].Value);
                    hashs[i] = new HashEntry(par[i].Key, objBytes);
                }
                break;

                //case AEDBDataType.ADDT_STRING: // deault is string
                default:
                    hashs[i] = new HashEntry(par[i].Key, (string)par[i].Value);
                    break;
                }
            }

            if (_expireTime > 0)
            {
                db.HashSet(hash, hashs);
                db.KeyExpire(hash, TimeSpan.FromSeconds(_expireTime));
            }
            else
            {
                db.HashSet(hash, hashs);
            }

            return(ret);
        }
        public bool SetValue(string key, string value)
        {
            IDatabase redisDB = getRedisDB();

            return(redisDB.StringSet(key, value));
        }
        public bool SetValue(byte[] key, byte[] value)
        {
            IDatabase redisDB = getRedisDB();

            return(redisDB.StringSet(key, value));
        }
Example #59
0
 public DynamicViewSet(IDatabase database, Action <DataEventTransaction> listener)
 {
     this.Id       = Guid.NewGuid().ToString();
     this.Database = database;
     this.listener = listener;
 }
Example #60
0
 public UserQueryWorker(IDatabase database)
 {
     Contract.Requires <ArgumentNullException>(database != null, "database");
     _database = database;
 }