Exemple #1
0
 public BatchFile(string fileName, DbServer server, string pgDumpPath, string tenant)
 {
     this.FileName = fileName;
     this.Server = server;
     this.PgDumpPath = pgDumpPath;
     this.Tenant = tenant;
 }
Exemple #2
0
 public Process(DbServer server, string fileName, string tenant)
 {
     this.Server = server;
     this.PgDumpPath = Path.Combine(this.Server.BinDirectory, "pg_dump.exe");
     this.FileName = fileName;
     this.Tenant = tenant;
 }
        public void BatchTest(DbServer dbServer)
        {
            ContextUtil.DbServer = dbServer;

            RunDeleteAll(dbServer);
            RunInsert();
            RunBatchUpdate(dbServer);

            int deletedEntities = 1;

            if (dbServer == DbServer.SqlServer)
            {
                RunBatchUpdate_UsingNavigationPropertiesThatTranslateToAnInnerQuery();
                deletedEntities = RunTopBatchDelete();
            }

            RunBatchDelete();
            RunBatchDelete2();
            RunContainsBatchDelete();
            RunContainsBatchDelete2();
            RunContainsBatchDelete3();
            RunAnyBatchDelete();

            UpdateSetting(SettingsEnum.Sett1, "Val1UPDATE");

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var firstItem = context.Items.ToList().FirstOrDefault();
                var lastItem  = context.Items.ToList().LastOrDefault();
                Assert.Equal(1, deletedEntities);
                Assert.Equal(500, lastItem.ItemId);
                Assert.Equal("Updated", lastItem.Description);
                Assert.Equal(1.5m, lastItem.Price);
                Assert.StartsWith("name ", lastItem.Name);
                Assert.EndsWith(" Concatenated", lastItem.Name);

                if (dbServer == DbServer.SqlServer)
                {
                    Assert.EndsWith(" TOP(1)", firstItem.Name);
                }
            }

            if (dbServer == DbServer.SqlServer)
            {
                RunUdttBatch();
            }

            if (dbServer == DbServer.SqlServer)
            {
                // Removing ORDER BY and CTE's are not implemented for SQLite.
                RunOrderByDeletes();
                RunIncludeDelete();
            }
        }
Exemple #4
0
        /// <summary>
        ///  保存 按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDbServerSave_Click(object sender, EventArgs e)
        {
            if (!CheckServerInput())
            {
                return;
            }

            var sName           = txtDbServerName.Text;
            var host            = txtDbServerHost.Text;
            var uName           = txtDbServerUserId.Text;
            var uPwd            = txtDbServerUserPwd.Text;
            var port            = txtDbServerPort.Text;
            var dataBase        = txtDbServerDataBase.Text;
            var sessionTitmeOut = 28800;

            if (rdoDbSessionTimeOutCustom.Checked)
            {
                sessionTitmeOut = Convert.ToInt32(txtDbSessionTimeOutCustom.Text);
            }

            DbServer server = new DbServer(sName, host, uName, uPwd, port, dataBase, sessionTitmeOut);

            if (IsExistedServer(sName))
            {
                if (txtDbServerName.Visible == true)
                {
                    SetStatusMsg(sName + "已经存在");
                }
                else
                {
                    DialogResult dr = MessageBox.Show("确定变更连接么?", "系统提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.Cancel)
                    {
                        return;
                    }
                    DelServer(sName);
                }
            }

            iniFile.SetSectionValue("DbServerList", sName);
            var rst = iniFile.SetSectionValue(sName, StringHelper.ToJSON(server));

            if (rst)
            {
                SetStatusMsg("保存成功");
                lblDbServerName.Visible = false;
                txtDbServerName.Visible = false;
                BindServerList();
            }
            else
            {
                SetStatusMsg("保存失败");
            }
        }
        private void InsertWithDiscriminatorShadow(DbServer databaseType)
        {
            ContextUtil.DbServer = databaseType;
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                context.BulkDelete(context.Students.ToList());
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = new List <Student>();
                for (int i = 1; i <= EntitiesNumber; i++)
                {
                    entities.Add(new Student
                    {
                        Name    = "name " + i,
                        Subject = "Math"
                    });
                }
                context.Students.AddRange(entities); // adding to Context so that Shadow property 'Discriminator' gets set

                context.BulkInsert(entities);
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = new List <Student>();
                for (int i = 1; i <= EntitiesNumber / 2; i += 2)
                {
                    entities.Add(new Student
                    {
                        Name    = "name " + i,
                        Subject = "Math Upd"
                    });
                }
                context.Students.AddRange(entities); // adding to Context so that Shadow property 'Discriminator' gets set

                context.BulkInsertOrUpdate(entities, new BulkConfig
                {
                    UpdateByProperties = new List <string> {
                        nameof(Student.Name)
                    },
                    PropertiesToExclude = new List <string> {
                        nameof(Student.PersonId)
                    },
                });
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = context.Students.ToList();
                Assert.Equal(EntitiesNumber, entities.Count());
            }
        }
Exemple #6
0
        public static async Task OnHttpRequest(Microsoft.AspNetCore.Http.HttpContext e)
        {
            //Authenticate
            DbServer server = await Program.ForceAuthServer(e);

            if (server == null)
            {
                return;
            }

            //Authenticate state
            DbSyncSavedState state = await Program.ForceAuthSessionState(e);

            if (state == null)
            {
                return;
            }

            //Decode
            Dictionary <string, TimeAnalyticsRequestItem> request = Program.DecodeStreamAsJson <Dictionary <string, TimeAnalyticsRequestItem> >(e.Request.Body);

            //Add each analytics option
            List <WriteModel <DbModTimeAnalyticsObject> > actions = new List <WriteModel <DbModTimeAnalyticsObject> >();

            foreach (var r in request.Values)
            {
                //Create
                DbModTimeAnalyticsObject o = new DbModTimeAnalyticsObject
                {
                    action         = r.action,
                    client_session = state._id,
                    client_version = state.mod_version,
                    key            = r.key,
                    server_id      = server._id,
                    time           = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(r.time),
                    payload        = new DbModTimeAnalyticsObject.DbModTimeAnalyticsObject_Payload
                    {
                        duration = r.durationms,
                        extras   = r.extras,
                        length   = r.resultlength
                    }
                };

                //Add
                actions.Add(new InsertOneModel <DbModTimeAnalyticsObject>(o));
            }

            //Apply
            if (actions.Count > 0)
            {
                await Program.conn.system_analytics_time.BulkWriteAsync(actions);
            }
        }
        private void InsertWithValueConversion(DbServer databaseType)
        {
            ContextUtil.DbServer = databaseType;
            var dateTime = DateTime.Today;

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                context.BulkDelete(context.Infos.ToList());
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = new List <Info>();
                for (int i = 1; i <= EntitiesNumber; i++)
                {
                    entities.Add(new Info
                    {
                        Message       = "Msg " + i,
                        ConvertedTime = dateTime,
                        InfoType      = InfoType.InfoTypeA
                    });
                }
                context.BulkInsert(entities);
            }

            if (databaseType == DbServer.SqlServer)
            {
                using (var context = new TestContext(ContextUtil.GetOptions()))
                {
                    var entities = context.Infos.ToList();
                    var entity   = entities.FirstOrDefault();

                    Assert.Equal(entity.ConvertedTime, dateTime);

                    var conn = context.Database.GetDbConnection();
                    if (conn.State != ConnectionState.Open)
                    {
                        conn.Open();
                    }
                    using (var command = conn.CreateCommand())
                    {
                        command.CommandText = $"SELECT TOP 1 * FROM {nameof(Info)} ORDER BY {nameof(Info.InfoId)} DESC";
                        var reader = command.ExecuteReader();
                        reader.Read();
                        var row = new Info()
                        {
                            ConvertedTime = reader.Field <DateTime>(nameof(Info.ConvertedTime))
                        };
                        Assert.Equal(row.ConvertedTime, dateTime.AddDays(1));
                    }
                }
            }
        }
Exemple #8
0
        private async Task RunInsertOrUpdateAsync(bool isBulkOperation, DbServer databaseType)
        {
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities    = new List <Item>();
                var dateTimeNow = DateTime.Now;
                for (int i = 2; i <= EntitiesNumber; i += 2)
                {
                    entities.Add(new Item
                    {
                        ItemId      = i,
                        Name        = "name InsertOrUpdate " + i,
                        Description = "info",
                        Quantity    = i,
                        Price       = i / (i % 5 + 1),
                        TimeUpdated = dateTimeNow
                    });
                }
                if (isBulkOperation)
                {
                    var bulkConfig = new BulkConfig()
                    {
                        SetOutputIdentity = true, CalculateStats = true
                    };
                    await context.BulkInsertOrUpdateAsync(entities, bulkConfig);

                    if (databaseType == DbServer.SqlServer)
                    {
                        Assert.Equal(1, bulkConfig.StatsInfo.StatsNumberInserted);
                        Assert.Equal(EntitiesNumber / 2 - 1, bulkConfig.StatsInfo.StatsNumberUpdated);
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted);
                    }
                }
                else
                {
                    await context.Items.AddRangeAsync(entities);

                    await context.SaveChangesAsync();
                }
            }
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                //int entitiesCount = ItemsCountQuery(context);
                int entitiesCount = await context.Items.CountAsync();

                //Item lastEntity = LastItemQuery(context);
                Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();

                Assert.Equal(EntitiesNumber, entitiesCount);
                Assert.NotNull(lastEntity);
                Assert.Equal("name InsertOrUpdate " + EntitiesNumber, lastEntity.Name);
            }
        }
Exemple #9
0
        public async Task SaveChangesTestAsync(DbServer dbServer)
        {
            ContextUtil.DbServer = dbServer;

            await new EFCoreBatchTestAsync().RunDeleteAllAsync(dbServer);
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                await context.ItemHistories.BatchDeleteAsync();
            }

            await RunSaveChangesOnInsertAsync();
            await RunSaveChangesOnInsertAndUpdateAsync();
        }
        /// <summary>
        /// Returns a user by their user ID. Returns null if not found.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <DbServer> GetServerByIdAsync(ObjectId id)
        {
            //Fetch
            DbServer u = await GetDocumentById <DbServer>(system_servers, id);

            //If not found, return null
            if (u == null)
            {
                return(null);
            }

            return(u);
        }
Exemple #11
0
 public Project(int id, string name, DbServer serverType, string connstringWeb, string connstringIS, int version)
 {
     this.Id            = id;
     this.Name          = name;
     this.ServerType    = serverType;
     this.ConnstringWeb = connstringWeb;
     this.ConnstringIS  = connstringIS;
     this.Version       = version;
     if (connstringWeb != null && Regex.IsMatch(ConnstringWeb, ".*[Dd]atabase=\"?([^\";]+)\"?.*"))
     {
         this.WebDbName = Regex.Match(ConnstringWeb, ".*[Dd]atabase=\"?([^\";]+)\"?.*").Groups[1].Value;
     }
 }
Exemple #12
0
        public void SaveChangesTest(DbServer dbServer)
        {
            ContextUtil.DbServer = dbServer;

            new EFCoreBatchTest().RunDeleteAll(dbServer);
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                context.ItemHistories.BatchDelete();
            }

            RunSaveChangesOnInsert();
            RunSaveChangesOnInsertAndUpdate();
        }
        /// <summary>
        /// Notifies a player that their access to a server has changed. Tells a user if they have access to a server, if they're admin, and their tribe ID
        /// </summary>
        public async Task OnUserServerAccessChangedAsync(DbServer server, DbUser user)
        {
            //Fetch the player profile
            var playerProfile = await server.GetUserPlayerProfile(conn, user);

            //Check if they are admin
            bool isAdmin = server.CheckIsUserAdmin(user);

            //Get payload and send
            RPCPayloadServerAccessChanged payload = new RPCPayloadServerAccessChanged(isAdmin, playerProfile);

            RPCMessageTool.SendRPCMsgToUserID(conn, RPC.RPCOpcode.SERVER_ACCESS_CHANGED, payload, user._id, server._id);
        }
        public static FilterDefinition <T> CreateTribeFilter <T>(DbServer server, int?tribeId)
        {
            var filterBuilder = Builders <T> .Filter;

            if (tribeId.HasValue)
            {
                return(filterBuilder.Eq("server_id", server._id) & filterBuilder.Eq("tribe_id", tribeId));
            }
            else
            {
                return(filterBuilder.Eq("server_id", server._id));
            }
        }
        public static string ToQuerySql <TEntity>(this IQueryable <TEntity> query, DbServer dbType) where TEntity : class
        {
            var(sql, paramters) = query.ToParametrizedSql(dbType);

            foreach (var parm in paramters)
            {
                var placeHolder = parm.ParameterName;
                var actualValue = GetActualValue(parm.Value);
                sql = sql.Replace(placeHolder, actualValue);
            }

            return(sql);
        }
Exemple #16
0
        private async Task RunDeleteAsync(bool isBulkOperation, DbServer databaseType)
        {
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = AllItemsQuery(context).ToList();
                // ItemHistories will also be deleted because of Relationship - ItemId (Delete Rule: Cascade)
                if (isBulkOperation)
                {
                    var bulkConfig = new BulkConfig()
                    {
                        CalculateStats = true
                    };
                    await context.BulkDeleteAsync(entities, bulkConfig);

                    if (databaseType == DbServer.SqlServer)
                    {
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted);
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberUpdated);
                        Assert.Equal(EntitiesNumber / 2, bulkConfig.StatsInfo.StatsNumberDeleted);
                    }
                }
                else
                {
                    context.Items.RemoveRange(entities);
                    await context.SaveChangesAsync();
                }
            }
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                //int entitiesCount = ItemsCountQuery(context);
                int entitiesCount = await context.Items.CountAsync();

                //Item lastEntity = LastItemQuery(context);
                Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();

                Assert.Equal(0, entitiesCount);
                Assert.Null(lastEntity);
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                if (databaseType == DbServer.SqlServer)
                {
                    await context.Database.ExecuteSqlRawAsync("DBCC CHECKIDENT('[dbo].[Item]', RESEED, 0);").ConfigureAwait(false);
                }
                if (databaseType == DbServer.Sqlite)
                {
                    await context.Database.ExecuteSqlRawAsync("DELETE FROM sqlite_sequence WHERE name = 'Item';").ConfigureAwait(false);
                }
            }
        }
Exemple #17
0
        private void RunInsertOrUpdate(bool isBulk, DbServer dbServer)
        {
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities    = new List <Item>();
                var dateTimeNow = DateTime.Now;
                for (int i = 2; i <= EntitiesNumber; i += 2)
                {
                    entities.Add(new Item
                    {
                        ItemId      = isBulk ? i : 0,
                        Name        = "name InsertOrUpdate " + i,
                        Description = "info",
                        Quantity    = i + 100,
                        Price       = i / (i % 5 + 1),
                        TimeUpdated = dateTimeNow
                    });
                }
                if (isBulk)
                {
                    var bulkConfig = new BulkConfig()
                    {
                        SetOutputIdentity = true, CalculateStats = true
                    };
                    context.BulkInsertOrUpdate(entities, bulkConfig, (a) => WriteProgress(a));
                    if (dbServer == DbServer.SqlServer)
                    {
                        Assert.Equal(1, bulkConfig.StatsInfo.StatsNumberInserted);
                        Assert.Equal(EntitiesNumber / 2 - 1, bulkConfig.StatsInfo.StatsNumberUpdated);
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted);
                    }
                }
                else
                {
                    context.Items.Add(entities[entities.Count - 1]);
                    context.SaveChanges();
                }
            }
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                //int entitiesCount = ItemsCountQuery(context);
                int entitiesCount = context.Items.Count();
                //Item lastEntity = LastItemQuery(context);
                Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();

                Assert.Equal(EntitiesNumber, entitiesCount);
                Assert.NotNull(lastEntity);
                Assert.Equal("name InsertOrUpdate " + EntitiesNumber, lastEntity.Name);
            }
        }
Exemple #18
0
        /// <summary>
        /// 根据名称获取连接信息
        /// </summary>
        /// <param name="serverName"></param>
        /// <returns></returns>
        private DbServer GetDbServer(string serverName)
        {
            DbServer dbServerModel = null;

            string[] dataArr = iniFile.GetSectionValues(serverName);
            if (dataArr == null)
            {
                return(dbServerModel);
            }
            string jsonStr = string.Join("", dataArr);

            dbServerModel = StringHelper.ToObject <DbServer>(jsonStr);
            return(dbServerModel);
        }
Exemple #19
0
        private void RunDelete(bool isBulk, DbServer dbServer)
        {
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = AllItemsQuery(context).ToList();
                // ItemHistories will also be deleted because of Relationship - ItemId (Delete Rule: Cascade)
                if (isBulk)
                {
                    var bulkConfig = new BulkConfig()
                    {
                        CalculateStats = true
                    };
                    context.BulkDelete(entities, bulkConfig);
                    if (dbServer == DbServer.SqlServer)
                    {
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted);
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberUpdated);
                        Assert.Equal(entities.Count, bulkConfig.StatsInfo.StatsNumberDeleted);
                    }
                }
                else
                {
                    context.Items.RemoveRange(entities);
                    context.SaveChanges();
                }
            }
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                //int entitiesCount = ItemsCountQuery(context);
                int entitiesCount = context.Items.Count();
                //Item lastEntity = LastItemQuery(context);
                Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();

                Assert.Equal(0, entitiesCount);
                Assert.Null(lastEntity);
            }

            // Resets AutoIncrement
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                if (dbServer == DbServer.SqlServer)
                {
                    context.Database.ExecuteSqlRaw("DBCC CHECKIDENT ('dbo.[" + nameof(Item) + "]', RESEED, 0);"); // can NOT use $"...{nameof(Item)..." because it gets parameterized
                }
                else if (dbServer == DbServer.Sqlite)
                {
                    context.Database.ExecuteSqlRaw("DELETE FROM sqlite_sequence WHERE name = 'Item';");
                }
            }
        }
        public static UsersMeReply_Server MakeServer(DbServer s, DbPlayerProfile ps, DbUser user)
        {
            //If this server has never sent a status, skip
            UsersMeReply_Server reply = new UsersMeReply_Server();

            reply.display_name         = s.display_name;
            reply.image_url            = s.image_url;
            reply.owner_uid            = s.owner_uid;
            reply.id                   = s.id;
            reply.has_ever_gone_online = true;
            reply.cluster_id           = s.cluster_id;

            if (ps != null)
            {
                reply.tribeId   = ps.tribe_id;
                reply.tribeName = s.GetTribeAsync(Program.connection, ps.tribe_id).GetAwaiter().GetResult().tribe_name;
                reply.arkName   = ps.name;
            }

            string base_endpoint = Program.connection.config.hosts.master + "/api" + $"/servers/{s.id}/";

            reply.endpoint_createsession = Program.config.endpoint_echo + $"/{s.id}/" + "create_session";

            reply.map_id   = s.latest_server_map;
            reply.map_name = reply.map_id;

            //Get the user prefs, if they exist. If they don't, generate one on the fly
            {
                var filterBuilder = Builders <DbSavedUserServerPrefs> .Filter;
                var filter        = filterBuilder.Eq("server_id", s.id) & filterBuilder.Eq("user_id", user.id);
                var results       = Program.connection.system_saved_user_server_prefs.Find(filter).FirstOrDefault();
                if (results != null)
                {
                    reply.user_prefs = results.payload;
                }
                else
                {
                    reply.user_prefs = new LibDeltaSystem.Db.System.Entities.SavedUserServerPrefs
                    {
                        x            = 128,
                        y            = -128,
                        z            = 2,
                        map          = 0,
                        drawable_map = null
                    };
                }
            }

            return(reply);
        }
Exemple #21
0
        /// <summary>
        /// Gets the data
        /// </summary>
        /// <returns></returns>
        public async Task <DbServer> GetServerData()
        {
            //Check if it is new enough (5 minutes)
            if (DateTime.UtcNow < last_server_refresh.AddMinutes(5))
            {
                return(target_server_data);
            }

            //Refresh
            target_server_data = await Program.conn.GetServerByIdAsync(target_server.ToString());

            last_server_refresh = DateTime.UtcNow;
            return(target_server_data);
        }
Exemple #22
0
        public static async Task OnHttpRequest(Microsoft.AspNetCore.Http.HttpContext e)
        {
            //Authenticate
            DbServer server = await Program.ForceAuthServer(e);

            if (server == null)
            {
                return;
            }
            return; //TODO

            using (StreamReader sr = new StreamReader(e.Request.Body))
                Console.WriteLine(await sr.ReadToEndAsync());
        }
Exemple #23
0
        private void RunUpdate(bool isBulk, DbServer dbServer)
        {
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                int counter  = 1;
                var entities = context.Items.AsNoTracking().ToList();
                foreach (var entity in entities)
                {
                    entity.Description = "Desc Update " + counter++;
                    entity.Quantity   += 1000; // will not be changed since Quantity property is not in config PropertiesToInclude
                }
                if (isBulk)
                {
                    var bulkConfig = new BulkConfig
                    {
                        PropertiesToInclude = new List <string> {
                            nameof(Item.Description)
                        },
                        UpdateByProperties = dbServer == DbServer.SqlServer ? new List <string> {
                            nameof(Item.Name)
                        } : null,
                        CalculateStats = true
                    };
                    context.BulkUpdate(entities, bulkConfig);
                    if (dbServer == DbServer.SqlServer)
                    {
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted);
                        Assert.Equal(EntitiesNumber, bulkConfig.StatsInfo.StatsNumberUpdated);
                        Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted);
                    }
                }
                else
                {
                    context.Items.UpdateRange(entities);
                    context.SaveChanges();
                }
            }
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                //int entitiesCount = ItemsCountQuery(context);
                int entitiesCount = context.Items.Count();
                //Item lastEntity = LastItemQuery(context);
                Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();

                Assert.Equal(EntitiesNumber, entitiesCount);
                Assert.NotNull(lastEntity);
                Assert.Equal("name InsertOrUpdate " + EntitiesNumber, lastEntity.Name);
            }
        }
Exemple #24
0
        private void UpsertWithOutputSortTest(DbServer dbServer)
        {
            ContextUtil.DbServer = dbServer;
            using var context    = new TestContext(ContextUtil.GetOptions());

            new EFCoreBatchTest().RunDeleteAll(dbServer);

            var entitiesInitial = new List <Item>();

            for (int i = 1; i <= 10; ++i)
            {
                var entity = new Item {
                    Name = "name " + i
                };
                entitiesInitial.Add(entity);
            }
            context.Items.AddRange(entitiesInitial);
            context.SaveChanges();

            var entities = new List <Item>()
            {
                new Item {
                    ItemId = 0, Name = "name " + 11 + " New"
                },
                new Item {
                    ItemId = 6, Name = "name " + 6 + " Updated"
                },
                new Item {
                    ItemId = 5, Name = "name " + 5 + " Updated"
                },
                new Item {
                    ItemId = 0, Name = "name " + 12 + " New"
                }
            };

            context.BulkInsertOrUpdate(entities, new BulkConfig()
            {
                SetOutputIdentity = true
            });

            Assert.Equal(11, entities[0].ItemId);
            Assert.Equal(6, entities[1].ItemId);
            Assert.Equal(5, entities[2].ItemId);
            Assert.Equal(12, entities[3].ItemId);
            Assert.Equal("name " + 11 + " New", entities[0].Name);
            Assert.Equal("name " + 6 + " Updated", entities[1].Name);
            Assert.Equal("name " + 5 + " Updated", entities[2].Name);
            Assert.Equal("name " + 12 + " New", entities[3].Name);
        }
Exemple #25
0
 protected List <dynamic> Query(string sql, object param, DbServer dbName = DbServer.MainDb)
 {
     try
     {
         using (IDbConnection conn = GetConnection())
         {
             return(conn.Query(sql, param).ToList());
         }
     }
     catch (Exception ex)
     {
         LogError(sql, param, ex);
         throw ex;
     }
 }
Exemple #26
0
 protected async Task <int> ExecuteAsync(string sql, object param, DbServer dbName = DbServer.MainDb)
 {
     try
     {
         using (IDbConnection conn = GetConnection())
         {
             return(await conn.ExecuteAsync(sql, param));
         }
     }
     catch (Exception ex)
     {
         LogError(sql, param, ex);
         throw ex;
     }
 }
Exemple #27
0
 public void SetServerData(DbServer server)
 {
     //Set
     name     = server.display_name;
     icon_url = server.image_url;
     id       = server.id;
     map_id   = server.latest_server_map;
     last_secure_mode_toggled = server.last_secure_mode_toggled;
     permission_flags         = server.permission_flags;
     permissions_template     = server.permissions_template;
     mods = server.mods;
     content_server_hostname = server.game_content_server_hostname;
     is_locked       = server.CheckFlag(DbServer.FLAG_INDEX_LOCKED);
     is_unconfigured = server.CheckFlag(DbServer.FLAG_INDEX_SETUP);
     is_secure       = server.CheckFlag(DbServer.FLAG_INDEX_SECURE);
 }
        public async Task RunBatchDeleteAllAsync(DbServer databaseType)
        {
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                await context.Items.BatchDeleteAsync();

                if (databaseType == DbServer.SqlServer)
                {
                    await context.Database.ExecuteSqlCommandAsync("DBCC CHECKIDENT('[dbo].[Item]', RESEED, 0);").ConfigureAwait(false);
                }
                if (databaseType == DbServer.Sqlite)
                {
                    await context.Database.ExecuteSqlCommandAsync("DELETE FROM sqlite_sequence WHERE name = 'Item';").ConfigureAwait(false);
                }
            }
        }
Exemple #29
0
        public void BatchDelete_UsingWhereExpressionWithValueConverter_Deletes(DbServer dbServer)
        {
            ContextUtil.DbServer = dbServer;

            using var db = new VcDbContext(ContextUtil.GetOptions <VcDbContext>(databaseName: $"{nameof(EFCoreBulkTest)}_ValueConverters"));

            db.BulkInsertOrUpdate(this.GetTestData().ToList());

            var date = new LocalDate(2020, 3, 21);

            db.VcModels.Where(x => x.LocalDate > date).BatchDelete();

            var models = db.VcModels.Count();

            Assert.Equal(0, models);
        }
        public void RunBatchDeleteAll(DbServer databaseType)
        {
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                context.Items.BatchDelete();

                if (databaseType == DbServer.SqlServer)
                {
                    context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('[dbo].[Item]', RESEED, 0);");
                }
                if (databaseType == DbServer.Sqlite)
                {
                    context.Database.ExecuteSqlCommand("DELETE FROM sqlite_sequence WHERE name = 'Item';");
                }
            }
        }
Exemple #31
0
        /// <summary>
        /// 服务器列表下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboDbServerList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboDbServerList.SelectedItem == null)
            {
                return;
            }
            string   serverName    = cboDbServerList.SelectedItem.ToString();
            DbServer dbServerModel = GetDbServer(serverName);

            txtDbServerName.Text     = dbServerModel.DbServerName;
            txtDbServerHost.Text     = dbServerModel.DbServerHost;
            txtDbServerUserId.Text   = dbServerModel.DbServerUserName;
            txtDbServerUserPwd.Text  = dbServerModel.DbServerUserPwd;
            txtDbServerPort.Text     = dbServerModel.DbServerPort;
            txtDbServerDataBase.Text = dbServerModel.DbServerDataBase;
        }
Exemple #32
0
        //[InlineData(DatabaseType.SqlServer, false)] // for speed comparison with Regular EF CUD operations
        public async Task OperationsTestAsync(DbServer databaseType, bool isBulkOperation)
        {
            ContextUtil.DbServer = databaseType;

            await new EFCoreBatchTestAsync().RunDeleteAllAsync(databaseType); // TODO

            // Test can be run individually by commenting others and running each separately in order one after another
            await RunInsertAsync(isBulkOperation);
            await RunInsertOrUpdateAsync(isBulkOperation);
            await RunUpdateAsync(isBulkOperation);

            if (databaseType == DbServer.SqlServer)
            {
                await RunReadAsync(isBulkOperation); // Not Yet supported for Sqlite
            }
            await RunDeleteAsync(isBulkOperation, databaseType);
        }
Exemple #33
0
        /// <summary>
        /// The main entry point of the application - initializes database drivers, checks access rights, detects the current page type and does more setting accordingly.
        /// </summary>
        protected void Page_Init(object sender, EventArgs e)
        {
            DbServer = (DbServer)Enum.Parse(typeof(DbServer), System.Configuration.ConfigurationManager.AppSettings["ServerType"] as string);

            bool isFirstRun = System.Configuration.ConfigurationManager.AppSettings["FirstRun"] as string == "True";

            // detect the site type based on the beginning of the URL
            string lp = Request.Url.LocalPath;

            if (lp.StartsWith("/architect")){
                Common.Environment.GlobalState = GlobalState.Architect;
            }
            else if (lp.StartsWith("/admin")) {
                Common.Environment.GlobalState = GlobalState.Administer;
            }
            else if(lp == "/sys/users"){
                Common.Environment.GlobalState = GlobalState.UsersManagement;
            }
            else if(lp == "/sys/projects"){
                Common.Environment.GlobalState = GlobalState.ProjectsManagement;
            }
            else if(lp.StartsWith("/account")){
                Common.Environment.GlobalState = GlobalState.Account;
            }
            else if(lp.StartsWith("/FirstRun")){
                Common.Environment.GlobalState = GlobalState.FirstRun;
            }
            else
                Common.Environment.GlobalState = GlobalState.Error;

            bool firstRunMono = System.Configuration.ConfigurationManager.AppSettings["FirstRunMono"] == "True";

            if(isFirstRun && Common.Environment.GlobalState != GlobalState.FirstRun && !firstRunMono)
            {
                Response.Redirect("~/FirstRun/FirstRun.aspx");
            }
            if(!isFirstRun && Common.Environment.GlobalState == GlobalState.FirstRun)
            {
                Response.RedirectToRoute("DefaultRoute");
            }

            // set the warning only for logged in users
            System.Configuration.ConfigurationManager.AppSettings["SessionWarning"] =
                (user is MembershipUser) ? (Session.Timeout - 5).ToString() : "-1";

            if (isFirstRun)
            {
                return;
            }

            user = Membership.GetUser();

            // session expiry means logout, even if the provider would keep the user logged in
            if ((Session.IsNewSession || user == null)
                && CE.GlobalState != GlobalState.Account && CE.GlobalState != GlobalState.Error)
            {
                FormsAuthentication.SignOut();
                Response.RedirectToRoute("LockoutRoute", new { message = 7 });
            }

            IBaseDriver systemBaseDriver = null;

            // initialize the system driver based on the server type read from the configuration
            switch (DbServer)
            {
                case DbServer.MySql:
                    systemBaseDriver = new BaseDriverMySql(ConfigurationManager.ConnectionStrings["MySqlServer"].ConnectionString);
                    break;
                case DbServer.MsSql:
                    systemBaseDriver = new BaseDriverMsSql(ConfigurationManager.ConnectionStrings["MsSqlServer"].ConnectionString);
                    break;
                default:
                    break;
            }

            SysDriver = new SystemDriver(systemBaseDriver);

            if (firstRunMono && CE.GlobalState != GlobalState.FirstRun)
            {
                Response.Redirect("~/FirstRun/FirstRunMono.aspx");
            }
            if (!firstRunMono && CE.GlobalState == GlobalState.FirstRun)
            {
                Response.RedirectToRoute("DefaultRoute");
            }

            if (firstRunMono)
            {
                return;
            }

            // global service

            // is there a need for a reload of the project architecture?
            bool NewProjectLoad = false;

            // get current project and init drivers and architect
            if (Page.RouteData.Values.ContainsKey("projectName"))
            {
                ProjectName = Page.RouteData.Values["projectName"] as string;
                CE.Project actProject = SysDriver.GetProject(ProjectName);

                if (CE.project == null || actProject.Id != CE.project.Id || actProject.Version != CE.project.Version)
                {
                    Session.Clear();    // may not be neccessary in all cases, but better be safe
                    NewProjectLoad = true;
                }

                CE.project = SysDriver.GetProject(ProjectName);

                IBaseDriver statsBaseDriver = null;
                IBaseDriver webBaseDriver = null;

                switch (CE.project.ServerType)
                {
                    case DbServer.MySql:
                        statsBaseDriver = new BaseDriverMySql(CE.project.ConnstringIS);
                        Stats = new StatsMySql((BaseDriverMySql)statsBaseDriver, CE.project.WebDbName);
                        webBaseDriver = new BaseDriverMySql(CE._project.ConnstringWeb);
                        break;
                    case DbServer.MsSql:
                        statsBaseDriver = new BaseDriverMsSql(CE.project.ConnstringIS);
                        Stats = new StatsMsSql((BaseDriverMsSql)statsBaseDriver);
                        webBaseDriver = new BaseDriverMsSql(CE._project.ConnstringWeb);
                        break;
                    default:
                        break;
                }
                WebDriver = new WebDriver(webBaseDriver);

                Architect = new _min.Models.Architect(SysDriver, Stats);

                if ((!Page.IsPostBack || NewProjectLoad) && CE.GlobalState != GlobalState.Error)
                    // new version or differnet page ~ othervise access must have remained
                    // at least "allowable", if not allowed
                {
                    LockingAccess();    // just check
                }
                // check whether there is something to load at all
                if (Page.RouteData.Route != RouteTable.Routes["ArchitectInitRoute"])
                {
                    if (!SysDriver.ProposalExists())
                    {
                        if (CE.GlobalState == GlobalState.Architect)
                        {
                            Response.RedirectToRoute("ArchitectInitRoute", new { projectName = Page.RouteData.Values["projectName"] });
                            Response.End();
                        }
                        else
                        {
                            // change to some kind of "Not found" page
                            Response.RedirectToRoute("DefaultRoute", new { projectName = Page.RouteData.Values["projectName"] });
                            Response.End();
                        }
                    }

                    // get the current architecture - either extract from Session or directry from the DB, if project version has changed
                    int actVersion = CE.project.Version;
                    if (Session[CC.SESSION_ARCHITECTURE] is _min.Models.Panel
                        && Session[CC.SESSION_ARCHITECTURE_VERSION] is int
                        && (int)Session[CC.SESSION_ARCHITECTURE_VERSION] == actVersion)
                    {
                        SysDriver.SetArchitecture((MPanel)Session[CC.SESSION_ARCHITECTURE]);
                    }
                    else
                    {
                        SysDriver.FullProjectLoad();
                        Session[CC.SESSION_ARCHITECTURE] = SysDriver.MainPanel;
                        Session[CC.SESSION_ARCHITECTURE_VERSION] = CE.project.Version;
                    }
                }
            }

            // local issues

            if (!Page.IsPostBack)
            {

                if (user != null)
                {

                    List<string> adminOf;
                    List<string> architectOf;
                    List<CE.Project> allProjects = SysDriver.GetProjectObjects();
                    List<string> allNames = (from CE.Project p in allProjects select p.Name).ToList<string>();

                    object userId = user.ProviderUserKey;
                    int globalRights = SysDriver.GetUserRights(userId, null);
                    // by default, fetch only the sites to which the access rights are set explicitly,
                    // if global rights are sufficient, replace them with the complete lists
                    SysDriver.UserMenuOptions(userId, out adminOf, out architectOf);
                    if (globalRights % 100 >= 10) adminOf = allNames;
                    if (globalRights % 1000 >= 100) architectOf = allNames;

                    // decide on the upper menu content

                    MenuItem administerItem = new MenuItem("Administer", "admin");
                    foreach (string site in adminOf)
                    {
                        administerItem.ChildItems.Add(new MenuItem(site, site, null, "/admin/" + site));
                    }
                    if (adminOf.Count > 0)
                        NavigationMenu.Items.AddAt(0, administerItem);

                    // architect menu
                    MenuItem architectItem = new MenuItem("Architect", "architect");
                    foreach (string site in architectOf)
                    {
                        architectItem.ChildItems.Add(new MenuItem(site, site, null, "/architect/show/" + Server.UrlEncode(site)));
                    }
                    if (architectOf.Count > 0)
                        NavigationMenu.Items.AddAt(1, architectItem);

                    // user & projects management

                    NavigationMenu.Items.Add(new MenuItem("Manage users", "users", null, "/sys/users"));

                    if (globalRights >= 10000)   // this is the one and only project manager for this application instance
                        NavigationMenu.Items.Add(new MenuItem("Manage projects", "projects", null, "/sys/projects"));

                    // account settings for logged in users
                    MenuItem accountItem = new MenuItem("Account", "account");
                    accountItem.ChildItems.Add(new MenuItem("Change password", null, null, "/account/change-password"));
                    accountItem.ChildItems.Add(new MenuItem("Logout", null, null, "/account/logout"));
                    NavigationMenu.Items.Add(accountItem);
                }
                else {
                    MenuItem accountItem = new MenuItem("Account", "account");
                    accountItem.ChildItems.Add(new MenuItem("Login", null, null, "/account/login"));
                    accountItem.ChildItems.Add(new MenuItem("Register", null, null, "/account/register"));

                    NavigationMenu.Items.Add(accountItem);
                }
                NavigationMenu.RenderingMode = MenuRenderingMode.Table;
            }
        }
Exemple #34
0
 public Project(int id, string name, DbServer serverType, string connstringWeb, string connstringIS, int version)
 {
     this.Id = id;
     this.Name = name;
     this.ServerType = serverType;
     this.ConnstringWeb = connstringWeb;
     this.ConnstringIS = connstringIS;
     this.Version = version;
     if(connstringWeb != null && Regex.IsMatch(ConnstringWeb, ".*[Dd]atabase=\"?([^\";]+)\"?.*"))
         this.WebDbName = Regex.Match(ConnstringWeb, ".*[Dd]atabase=\"?([^\";]+)\"?.*").Groups[1].Value;
 }