Ejemplo n.º 1
0
        /// <summary>
        /// Gets the color of the tree type.
        /// </summary>
        /// <returns>The tree type color.</returns>
        /// <param name="id">TreeType ID</param>
        public static Color GetTreeTypeColor(int id)
        {
            var connection = new TreeWatchDatabase();
            TreeType type = new DBQuery<TreeType>(connection).GetByID(id);

            return type.ColorProp;
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Creates the specified db.
 /// </summary>
 /// <param name="db">The db.</param>
 /// <param name="collectionName">Name of the collection.</param>
 /// <param name="options">The options.</param>
 public static void create(this IDatabase db, string collectionName, IDBObject options)
 {
     DBQuery createCmd = new DBQuery("create", collectionName);
     createCmd.PutAll(options);
     IDBObject result = db.ExecuteCommand(createCmd);
     result.ThrowIfResponseNotOK("create failed");
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Evaluates the specified expression (and optional parameters).
 /// </summary>
 /// <param name="db">The db.</param>
 /// <param name="code">The code.</param>
 /// <param name="args">The args.</param>
 /// <returns></returns>
 public static object eval(this IDatabase db, string code, params object[] args)
 {
     DBQuery cmd = new DBQuery() { { "$eval", code }, { "args", args } };
     IDBObject res = db.ExecuteCommand(cmd);
     res.ThrowIfResponseNotOK("eval failed");
     return res["retval"];
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Gets/Sets the diagnostic logging level
 /// </summary>
 /// <param name="db">The db.</param>
 /// <param name="logLevel">The log level.</param>
 public static void diagLogging(this IAdminOperations db, ref DiagnosticLoggingLevel logLevel)
 {
     DBQuery query = new DBQuery("diagLogging", (int)logLevel);
     IDBObject response = db.ExecuteCommand(query);
     response.ThrowIfResponseNotOK("diagLogging failed");
     logLevel = (DiagnosticLoggingLevel)response.GetAsInt("yada");
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Sets up mock data.
        /// </summary>
        public static void SetUpMockData()
        {
            var connection = new TreeWatchDatabase();
            connection.ClearDataBase();

            var fieldQuery = new DBQuery<Field>(connection);
            var treetypeQuery = new DBQuery<TreeType>(connection);
            var blockQuery = new DBQuery<Block>(connection);
            var heatmapQuery = new DBQuery<HeatMap>(connection);
            var treetypes = treetypeQuery.GetAllWithChildren();

            var field = KMLParser.GetField(KMLParser.LoadFile("KML.Fields.perceelscanKarwei.kml"));
            field.Name = "Karwei";
            fieldQuery.InsertWithChildren(field);

            field = KMLParser.GetField(KMLParser.LoadFile("KML.Fields.perceelscanPraxis.kml"));
            field.Name = "Praxis";
            fieldQuery.InsertWithChildren(field);

            field = KMLParser.GetField(KMLParser.LoadFile("KML.Fields.perceelscanSligro.kml"));
            field.Name = "Sligro";
            fieldQuery.InsertWithChildren(field);

            field = KMLParser.GetField(KMLParser.LoadFile("KML.Fields.perceelscanGrutto.kml"));
            field.Name = "Grutto";
            field.Blocks = KMLParser.GetBlocks(KMLParser.LoadFile("KML.Blocks.rassenmapGrutto.kml"), treetypes);
            blockQuery.InsertAllWithChildren(field.Blocks);
            fieldQuery.InsertWithChildren(field, false);

            treetypes = treetypeQuery.GetAllWithChildren();
            field = KMLParser.GetField(KMLParser.LoadFile("KML.Fields.perceelscanHema.kml"));
            field.Name = "Hema";
            field.Blocks = KMLParser.GetBlocks(KMLParser.LoadFile("KML.Blocks.rassenmapHema.kml"), treetypes);
            blockQuery.InsertAllWithChildren(field.Blocks);
            fieldQuery.InsertWithChildren(field, false);

            /* SQLite on android can not handle this many entitys at once.
             * Therefore we can not add this field, also heatmaps dont work at all in android.
             */

            if (TargetPlatform.iOS == Device.OS)
            {
                var heatmap = KMLParser.GetHeatmap(KMLParser.LoadFile("KML.Heatmaps.Biomassa.kml"));
                heatmap.Name = "Biomassa";
                heatmapQuery.InsertWithChildren(heatmap);

                treetypes = treetypeQuery.GetAllWithChildren();
                field = KMLParser.GetField(KMLParser.LoadFile("KML.Fields.perceelscanIkea.kml"));
                field.Name = "Ikea";
                field.Blocks = KMLParser.GetBlocks(KMLParser.LoadFile("KML.Blocks.rassenmapIkea.kml"), treetypes);
                blockQuery.InsertAllWithChildren(field.Blocks);
                fieldQuery.InsertWithChildren(field, false);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// The fsync command allows us to flush all pending writes to datafiles.  More importantly, it also provides a lock option that makes backups easier.
        /// </summary>
        /// <param name="db">The db.</param>
        /// <param name="asynchronous">if set to <c>true</c> return immediately, regardless of completion status.</param>
        /// <param name="shouldLock">if set to <c>true</c> will lock the database until it is subsequently unlocked.</param>
        /// <returns></returns>
        public static int fsync(this IAdminOperations db, bool asynchronous, bool shouldLock)
        {
            DBQuery query = new DBQuery()
            {
                {"fsync", 1},
            };
            if (asynchronous)
                query.Add("async", true);
            if (shouldLock)
                query.Add("lock", true);
            IDBObject res = db.ExecuteCommand(query);

            res.ThrowIfResponseNotOK("fsync failed");
            return res.GetAsInt("numFiles");
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Copy an entire database from one name on one server to another name on another server.
        /// </summary>
        /// <param name="db">The db.</param>
        /// <param name="fromDatabase">From database.</param>
        /// <param name="toDatabase">To database.</param>
        public static void copydb(this IAdminOperations db, IDatabase fromDatabase, IDatabase toDatabase)
        {
            DBQuery query = new DBQuery()
            {
                {"copydb", 1},
                {"fromdb", fromDatabase.Name},
                {"todb", toDatabase.Name },
            };

            if (!fromDatabase.Server.Equals(db.Server))
                query.Add("fromhost", fromDatabase.Server.Uri.Authority);

            IDBObject response = db.ExecuteCommand(query);
            response.ThrowIfResponseNotOK("copydb failed");
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Deletes the specified indexes.
        /// </summary>
        /// <remarks>Specifying "*" will delete all indexes on the specified collection.</remarks>
        /// <param name="db">The db.</param>
        /// <param name="collection">The collection.</param>
        /// <param name="indexName">Name of the index.</param>
        public static void deleteIndexes(this IDatabase db, IDBCollection collection, string indexName)
        {
            DBQuery cmd = new DBQuery
            {
                {"deleteIndexes", collection.Name},
                {"index", string.IsNullOrWhiteSpace(indexName)? "*" : indexName}
            };

            IDBObject res = db.ExecuteCommand(cmd);
            DBError error;
            if (res.WasError(out error))
            {
                if (error.NamespaceWasNotFound)
                    return;
                error.Throw("deleteIndexes failed");
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Groups data on the server
        /// </summary>
        /// <param name="db">The db.</param>
        /// <param name="collection">The collection.</param>
        /// <param name="key">The key.</param>
        /// <param name="cond">The cond.</param>
        /// <param name="initial">The initial.</param>
        /// <param name="reduce">The reduce.</param>
        /// <returns></returns>
        public static IDBObject group(this IDatabase db, IDBCollection collection, DBFieldSet key, DBQuery cond, IDocument initial, string reduce)
        {
            DBObject group = new DBObject()
            {
                  {"ns", collection.Name},
                  {"$reduce", reduce},
            };

            if (key != null)
                group["key"] = key;

            if (cond != null)
                group["cond"] = cond;

            if (initial != null)
                group["initial"] = initial;

            IDBObject ret = db.ExecuteCommand(new DBQuery("group", group));
            ret.ThrowIfResponseNotOK("group failed");
            return ret.GetAsIDBObject("retval");
        }
Ejemplo n.º 10
0
        public void Explain()
        {
            IDBCollection c = Mongo.DefaultDatabase.GetCollection("explain1");
            c.Drop();

            for (int test = 0; test < 100; test++)
                c.Save(new Document("test", test));

            DBQuery q = new DBQuery("test", new DBQuery("$gt", 50));

            Assert.AreEqual(49, c.Find(q).Count());
            Assert.AreEqual(20, c.Find(q, limit:20).Count());

            c.EnsureIndex(new DBFieldSet("test"));

            Assert.AreEqual(49, c.Find(q).Count());
            Assert.AreEqual(20, c.Find(q, limit:20).Count());

            //Assert.AreEqual(49, c.Find(q, explain:true)["n"]);

            //// these 2 are 'reversed' b/c we want the user case to make sense
            //Assert.AreEqual(20, c.Find(q).limit(20).explain()["n"]);
            //Assert.AreEqual(49, c.Find(q).limit(-20).explain()["n"]);
        }
Ejemplo n.º 11
0
        public static void ScanLastGroup(DBManager dbMgr)
        {
            long nowTicks = DateTime.Now.Ticks / 10000L;

            if (nowTicks - GiftCodeNewManager.LastScanTicks >= 10000L)
            {
                GiftCodeNewManager.LastScanTicks = nowTicks;
                List <LineItem> itemList = LineManager.GetLineItemList();
                if (itemList != null && itemList.Count != 0)
                {
                    bool bExistLocalServer = false;
                    for (int i = 0; i < itemList.Count; i++)
                    {
                        if (itemList[i].LineID > 0 && (itemList[i].LineID < 9000 || itemList[i].LineID == GameDBManager.ZoneID))
                        {
                            bExistLocalServer = true;
                            break;
                        }
                    }
                    if (bExistLocalServer)
                    {
                        List <GiftCodeAwardData> groupList = DBQuery.ScanNewGiftCodeFromTable(dbMgr);
                        if (groupList != null && groupList.Count != 0)
                        {
                            string        nowtime  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            List <string> GiftData = new List <string>();
                            foreach (GiftCodeAwardData item in groupList)
                            {
                                if (item.RoleID > 0 && !string.IsNullOrEmpty(item.UserId) && !string.IsNullOrEmpty(item.GiftId) && !string.IsNullOrEmpty(item.CodeNo))
                                {
                                    bool isSucc = DBWriter.UpdateGiftCodeState(dbMgr, item.Dbid, 1, nowtime);
                                    if (isSucc)
                                    {
                                        string szCmd = string.Format("{0},{1},{2},{3}", new object[]
                                        {
                                            item.UserId,
                                            item.RoleID,
                                            item.GiftId,
                                            item.CodeNo
                                        });
                                        GiftData.Add(szCmd);
                                    }
                                }
                                else
                                {
                                    LogManager.WriteLog(LogTypes.Error, string.Format("[GiftCodeNew]数据表t_giftcode相关配置DBID:{0},RoleId:{1},UserId:{2}错误!", item.Dbid, item.RoleID, item.UserId), null, true);
                                }
                            }
                            if (GiftData.Count > 0)
                            {
                                string szCmds    = string.Join("#", GiftData);
                                string gmCmdData = string.Format("-giftcodecmd {0}", szCmds);
                                ChatMsgManager.AddGMCmdChatMsgToOneClient(gmCmdData);
                            }
                            groupList.Clear();
                            GiftData.Clear();
                        }
                    }
                }
            }
        }
        public void processCmd(GameServerClient client, int nID, byte[] cmdParams, int count)
        {
            string cmdData = null;

            try
            {
                cmdData = new UTF8Encoding().GetString(cmdParams, 0, count);
            }
            catch (Exception)
            {
                LogManager.WriteLog(LogTypes.Error, string.Format("解析指令字符串错误, CMD={0}", (TCPGameServerCmds)nID), null, true);
                client.sendCmd(30767, "0");
                return;
            }
            string[] fields = cmdData.Split(new char[]
            {
                ':'
            });
            if (fields.Length != 5)
            {
                LogManager.WriteLog(LogTypes.Error, string.Format("指令参数个数错误, CMD={0}, Recv={1}, CmdData={2}", (TCPGameServerCmds)nID, fields.Length, cmdData), null, true);
                client.sendCmd(30767, "0");
            }
            else
            {
                int        roleID      = Convert.ToInt32(fields[0]);
                int        bhid        = Convert.ToInt32(fields[1]);
                int        buildType   = Convert.ToInt32(fields[2]);
                int        convertCost = Convert.ToInt32(fields[3]);
                int        toLevel     = Convert.ToInt32(fields[4]);
                DBManager  dbMgr       = DBManager.getInstance();
                DBRoleInfo dbRoleInfo  = dbMgr.GetDBRoleInfo(ref roleID);
                if (null == dbRoleInfo)
                {
                    LogManager.WriteLog(LogTypes.Error, string.Format("发起请求的角色不存在,CMD={0}, RoleID={1}", (TCPGameServerCmds)nID, roleID), null, true);
                    client.sendCmd(30767, "0");
                }
                else
                {
                    BangHuiDetailData bangHuiDetailData = DBQuery.QueryBangHuiInfoByID(dbMgr, bhid);
                    if (null == bangHuiDetailData)
                    {
                        string strcmd = string.Format("{0}", -1000);
                        client.sendCmd(nID, strcmd);
                    }
                    else
                    {
                        switch (buildType)
                        {
                        case 1:
                            if (toLevel > bangHuiDetailData.QiLevel)
                            {
                                toLevel = -1;
                            }
                            break;

                        case 2:
                            if (toLevel > bangHuiDetailData.JiTan)
                            {
                                toLevel = -1;
                            }
                            break;

                        case 3:
                            if (toLevel > bangHuiDetailData.JunXie)
                            {
                                toLevel = -1;
                            }
                            break;

                        case 4:
                            if (toLevel > bangHuiDetailData.GuangHuan)
                            {
                                toLevel = -1;
                            }
                            break;

                        default:
                            toLevel = -1;
                            break;
                        }
                        if (toLevel < 0)
                        {
                            string strcmd = string.Format("{0}", -1110);
                            client.sendCmd(nID, strcmd);
                        }
                        else if (dbRoleInfo.BangGong < Math.Abs(convertCost))
                        {
                            string strcmd = string.Format("{0}", -1110);
                            client.sendCmd(nID, strcmd);
                        }
                        else if (!DBWriter.UpdateRoleBangGong(dbMgr, roleID, dbRoleInfo.BGDayID1, dbRoleInfo.BGMoney, dbRoleInfo.BGDayID2, dbRoleInfo.BGGoods, dbRoleInfo.BangGong - convertCost))
                        {
                            string strcmd = string.Format("{0}", -1110);
                            client.sendCmd(nID, strcmd);
                        }
                        else
                        {
                            dbRoleInfo.BangGong -= Math.Abs(convertCost);
                            string strcmd = string.Format("{0}", 1);
                            client.sendCmd(nID, strcmd);
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Populates the specified DataSet with the results of the query using the specified load option.
 /// Multiple results sets from the query will be populated in the order of the tables in the DataSet.
 /// </summary>
 /// <param name="ds">The DataSet to Populate</param>
 /// <param name="tables">The array of table names that are to be populated by the results of the query</param>
 /// <param name="query">The Query to use to populate the data</param>
 public void PopulateDataSet(DataSet ds, DBQuery query, params string[] tables)
 {
     PopulateDataSet(ds, query, LoadOption.OverwriteChanges, tables);
 }
Ejemplo n.º 14
0
        //
        // PopulateDataSet with DBQuery
        //

        #region public void PopulateDataSet(DataSet ds, DBQuery query)

        /// <summary>
        /// Populates the specified DataSet with the results of the query, overwriting any changes.
        /// Multiple results sets from the query will be populated in the order of the tables in the DataSet.
        /// </summary>
        /// <param name="ds">The DataSet to Populate</param>
        /// <param name="query">The Query to use to populate the data</param>
        public void PopulateDataSet(DataSet ds, DBQuery query)
        {
            this.PopulateDataSet(ds, query, LoadOption.OverwriteChanges);
        }
Ejemplo n.º 15
0
        private int _saveContact()
        {
            int res = Validator.ValidateContact(Contact);

            if (res != 0)
            {
                return(res);
            }
            else
            {
                //Beginn Speicher-Vorgang...
                try
                {
                    var insertContactParameter = DBQuery.CreateSqlParameterSaveContact(Contact);
                    var cnt = DatabaseHelper.InsertDatabase(insertContactParameter);

                    var getLastContactParamter = DBQuery.CreateSqlParameterLastContact();
                    var id = DatabaseHelper.CheckDatabase(getLastContactParamter);

                    int contactId = 0;
                    int.TryParse(id.Rows[0][0].ToString(), out contactId);

                    var toInsert = new List <TitleModel>();
                    //Alle noch nicht in der Datenbank vorhandene Titel ermitteln
                    var newTitles = Contact.TitelList.FindAll(x => x.Title_ID == 0);
                    foreach (var entry in newTitles)
                    {
                        //Insert neuen Titel
                        var insertTitleCommand = DBQuery.CreateSqlParameterTitle(entry.Title, true);
                        int resCount           = DatabaseHelper.InsertDatabase(insertTitleCommand);

                        //Hinzugefügten Titel aus der Datenbank ermitteln
                        var selectCommand = DBQuery.CreateSqlParameterTitle(entry.Title, false);
                        var currentTitles = DatabaseHelper.CheckDatabase(selectCommand);

                        //Neu hinzugfügten Titel in Liste schreiben
                        toInsert.Add(new TitleModel
                        {
                            Title_ID = int.Parse(currentTitles.Rows[0][0].ToString()),
                            Title    = currentTitles.Rows[0][1].ToString()
                        });
                    }

                    //Alle bereits in der Datenbank vorhandenen Titel ermitteln
                    var existingTitles = Contact.TitelList.FindAll(x => x.Title_ID != 0);
                    toInsert.AddRange(existingTitles);

                    //Über alle dem Kontakt zugeordneten Titel loopen und diese in die Datenbank schreiben
                    foreach (var entry in toInsert)
                    {
                        var insertTitleContactParameter = DBQuery.CreateSqlParameterSaveTitle(contactId, entry.Title_ID);
                        var resTitleContact             = DatabaseHelper.InsertDatabase(insertTitleContactParameter);
                    }
                }
                catch (Exception ex)
                {
                    //Fehler während der Verarbeitung
                    return(10);
                }

                return(11);
            }
        }
Ejemplo n.º 16
0
        public System.Data.DataTable Get()
        {
            DBQuery getcount = DBQuery.SelectAll().From(Tech.DataAccess.DataBase.Schema, Tables.Schools.Table);

            return((System.Data.DataTable)(Database.GetDatatable(getcount)));
        }
Ejemplo n.º 17
0
        static void FindRecordsFields(DBCollection dbc)
        {
            DBQuery query = new DBQuery();
            try
            {
                BsonDocument condition = new BsonDocument
                {
                    {"Id",
                        new BsonDocument
                        {
                            {"$gte", 50},
                            {"$lte", 70}
                        }
                    }
                };

                query.Matcher = condition;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create query condition");
                Console.WriteLine(e.Message);
                return;
            }

            try
            {
                BsonDocument selector = new BsonDocument 
                { 
                    {"id", ""},
                    {"FirstName", ""},
                    {"LastName", ""},
                    {"PhoneNumber", ""}
                };

                query.Selector = selector;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create fields selector");
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("Find specific fields from Collection");
            Common.FindRecord(dbc, query);
        }
Ejemplo n.º 18
0
        public static void UpdateUsersMoney(DBManager dbMgr)
        {
            long nowTicks = DateTime.Now.Ticks / 10000L;

            if (nowTicks - UserMoneyMgr.LastUpdateUserMoneyTicks >= 2000L)
            {
                UserMoneyMgr.LastUpdateUserMoneyTicks = nowTicks;
                SingleChargeData chargeData = CFirstChargeMgr.ChargeData;
                if (chargeData == null)
                {
                    if (!UserMoneyMgr.ChargeDataLogState)
                    {
                        UserMoneyMgr.ChargeDataLogState = true;
                        LogManager.WriteLog(LogTypes.Error, "处理充值时找不到ChargeData, " + DateTime.Now.ToString(), null, true);
                    }
                }
                else
                {
                    if (UserMoneyMgr.ChargeDataLogState)
                    {
                        UserMoneyMgr.ChargeDataLogState = false;
                        LogManager.WriteLog(LogTypes.Error, "处理充值时已经获取到了ChargeData, " + DateTime.Now.ToString(), null, true);
                    }
                    List <TempMoneyInfo> tempMoneyInfoList = new List <TempMoneyInfo>();
                    DBQuery.QueryTempMoney(dbMgr, tempMoneyInfoList);
                    if (tempMoneyInfoList.Count > 0)
                    {
                        for (int i = 0; i < tempMoneyInfoList.Count; i++)
                        {
                            string userID       = tempMoneyInfoList[i].userID;
                            int    chargeRoleID = tempMoneyInfoList[i].chargeRoleID;
                            int    addUserMoney = tempMoneyInfoList[i].addUserMoney;
                            int    zhigouID     = tempMoneyInfoList[i].addUserItem;
                            string chargeTm     = tempMoneyInfoList[i].chargeTm;
                            LogManager.WriteLog(LogTypes.Error, string.Format("正在处理充值 UID={0},money={1},itemid={2}", userID, addUserMoney, zhigouID), null, true);
                            DBUserInfo dbUserInfo = dbMgr.GetDBUserInfo(userID);
                            if (dbUserInfo == null)
                            {
                                LogManager.WriteLog(LogTypes.Error, string.Format("处理充值时找不到user, UID={0},money={1},itemid={2}", userID, addUserMoney, zhigouID), null, true);
                            }
                            else if (zhigouID != 0 && !dbUserInfo.ListRoleIDs.Contains(chargeRoleID))
                            {
                                LogManager.WriteLog(LogTypes.Error, string.Format("处理充值直购时user内找不到rid, UID={0},rid={1},money={2},itemid={3}", new object[]
                                {
                                    userID,
                                    chargeRoleID,
                                    addUserMoney,
                                    zhigouID
                                }), null, true);
                            }
                            else
                            {
                                UserMoneyMgr._ProcessCharge(dbMgr, dbUserInfo, chargeRoleID, addUserMoney, zhigouID, chargeTm, chargeData, false);
                                if (zhigouID == 0 && addUserMoney == chargeData.YueKaMoney && chargeData.YueKaMoney > 0)
                                {
                                    UserMoneyMgr._ProcessBuyYueKa(dbMgr, dbUserInfo);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        public void _07_SimpleDeleteXmlTest()
        {
            DBQuery q = DBQuery.DeleteFrom("Customers").WhereField("customer_id", Compare.Equals, DBConst.Int32(2));

            q = SerializeAndDeserialzeQueryToMatch(q, "Simple Delete");
        }
Ejemplo n.º 20
0
        public void _01_SimpleXmlTest()
        {
            DBQuery q = DBQuery.SelectAll().From("Categories");

            q = SerializeAndDeserialzeQueryToMatch(q, "Simple Test");
        }
Ejemplo n.º 21
0
        private void AddParameterToQuery(string name, string parameter, DBQuery query)
        {
            const string ParameterTypeString   = "string";
            const string ParameterTypeNumber   = "number";
            const string ParameterTypeDateTime = "date";
            const string ParameterTypeObjectId = "objectid";
            const string ParameterTypeNull     = "null";
            const string ParameterTypeBool     = "bool";

            int split = parameter.IndexOf(":");

            if (split == -1)
            {
                return;
            }

            string type  = parameter.Substring(0, split);
            string value = parameter.Substring(split + 1);

            if (type == ParameterTypeString)
            {
                query.AddParameter(name, value);
            }
            else if (type == ParameterTypeNumber)
            {
                double number = 0;
                try
                {
                    number = Convert.ToDouble(value, CultureInfo.InvariantCulture);
                }
                catch (Exception)
                {
                    throw new RuntimeException("Invalid number value", new string[] { parameter });
                }

                query.AddParameter(name, number);
            }
            else if (type == ParameterTypeDateTime)
            {
                MC2DateTimeValue dateTime = null;

                try
                {
                    dateTime = (MC2DateTimeValue)MC2DateTimeValue.TryConvertValueFromString(value);
                }
                catch (Exception)
                {
                    throw new RuntimeException("Invalid date time value", new string[] { parameter });
                }

                query.AddParameter(name, dateTime);
            }
            else if (type == ParameterTypeObjectId)
            {
                if (string.IsNullOrEmpty(value))
                {
                    // Add empty object id if value is empty
                    query.AddParameter(name, new ObjectId());
                }
                else
                {
                    ObjectId objectId = new ObjectId();

                    try
                    {
                        objectId = new ObjectId(value);
                    }
                    catch (Exception)
                    {
                        throw new RuntimeException("Invalid object id value", new string[] { parameter });
                    }

                    query.AddParameter(name, objectId);
                }
            }
            else if (type == ParameterTypeNull)
            {
                query.AddNullParameter(name);
            }
            else if (type == ParameterTypeBool)
            {
                if (value == "true")
                {
                    query.AddParameter(name, true);
                }
                else if (value == "false")
                {
                    query.AddParameter(name, false);
                }
                else
                {
                    throw new RuntimeException("Invalid value for boolean parameter", new string[] { name, value });
                }
            }
        }
Ejemplo n.º 22
0
 public static void ScanGMMsgToGameServer(DBManager dbMgr)
 {
     try
     {
         long nowTicks = DateTime.Now.Ticks / 10000L;
         if (nowTicks - ChatMsgManager.LastScanInputGMMsgTicks >= 10000L)
         {
             ChatMsgManager.LastScanInputGMMsgTicks = nowTicks;
             List <string> msgList = new List <string>();
             DBQuery.ScanGMMsgFromTable(dbMgr, msgList);
             bool reloadConfig             = false;
             bool reloadGameserverLineList = false;
             bool reloadGMail = false;
             for (int i = 0; i < msgList.Count; i++)
             {
                 string msg = msgList[i].Replace(":", ":");
                 if (msg.IndexOf("-config ") >= 0)
                 {
                     reloadConfig = true;
                     string[] fields = msg.Trim().Split(new char[]
                     {
                         ' '
                     });
                     if (fields.Count <string>() == 3)
                     {
                         string paramName  = fields[1];
                         string paramValue = fields[2];
                         DBWriter.UpdateGameConfig(dbMgr, paramName, paramValue);
                     }
                 }
                 else if (msg == "-reload kuafu")
                 {
                     reloadGameserverLineList = true;
                 }
                 else if (msg == "-reloadall")
                 {
                     try
                     {
                         AssemblyPatchManager.getInstance().InitConfig();
                     }
                     catch (Exception ex)
                     {
                         LogManager.WriteException(ex.ToString());
                     }
                 }
                 if (msg.IndexOf("-resetgmail") >= 0)
                 {
                     reloadGMail = true;
                 }
                 if (msg.IndexOf("-outrank") >= 0)
                 {
                     GameDBManager.RankCacheMgr.PrintfRankData();
                 }
                 ChatMsgManager.AddGMCmdChatMsg(-1, msg);
             }
             if (reloadConfig)
             {
                 GameDBManager.GameConfigMgr.LoadGameConfigFromDB(dbMgr);
             }
             if (reloadGameserverLineList)
             {
                 LineManager.LoadConfig();
             }
             if (reloadGMail)
             {
                 GroupMailManager.ResetData();
             }
         }
     }
     catch (Exception)
     {
         LogManager.WriteLog(LogTypes.Error, string.Format("扫描GM命令表时发生了错误", new object[0]), null, true);
     }
 }
Ejemplo n.º 23
0
        public static int SendAward(DBManager dbMgr, string userID, int roleID, int awardID)
        {
            TenAwardData awardData = TenManager.getTenAward(awardID);
            int          result;

            if (awardData == null)
            {
                result = -6;
            }
            else
            {
                DateTime now = DateTime.Now;
                if (now < awardData.BeginTime || now > awardData.EndTime)
                {
                    result = -9;
                }
                else
                {
                    DBRoleInfo roleData = DBManager.getInstance().GetDBRoleInfo(ref roleID);
                    if (roleData == null)
                    {
                        result = -3;
                    }
                    else if (roleData.ChangeLifeCount * 100 + roleData.Level < awardData.RoleLevel)
                    {
                        result = -10;
                    }
                    else
                    {
                        if (awardData.OnlyNum > 0)
                        {
                            int totalNum = DBQuery.TenOnlyNum(dbMgr, userID, awardID);
                            if (totalNum > 0)
                            {
                                return(-5);
                            }
                        }
                        if (awardData.DayMaxNum > 0)
                        {
                            int totalNum = DBQuery.TenDayNum(dbMgr, userID, awardID);
                            if (totalNum >= awardData.DayMaxNum)
                            {
                                return(-5);
                            }
                        }
                        string mailGoodsString = "";
                        if (null != awardData.AwardGoods)
                        {
                            foreach (GoodsData goods in awardData.AwardGoods)
                            {
                                int useCount = goods.GCount;
                                mailGoodsString += string.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_{9}_{10}_{11}_{12}_{13}_{14}_{15}", new object[]
                                {
                                    goods.GoodsID,
                                    goods.Forge_level,
                                    goods.Quality,
                                    goods.Props,
                                    useCount,
                                    0,
                                    0,
                                    goods.Jewellist,
                                    goods.AddPropIndex,
                                    goods.Binding,
                                    goods.BornIndex,
                                    goods.Lucky,
                                    goods.Strong,
                                    goods.ExcellenceInfo,
                                    goods.AppendPropLev,
                                    goods.ChangeLifeLevForEquip
                                });
                                if (mailGoodsString.Length > 0)
                                {
                                    mailGoodsString += "|";
                                }
                            }
                        }
                        string[] fields = new string[]
                        {
                            "-1",
                            awardData.MailUser,
                            roleID.ToString(),
                            "",
                            awardData.MailTitle.ToString(),
                            awardData.MailContent.ToString(),
                            "0",
                            "0",
                            "0",
                            mailGoodsString
                        };
                        int addGoodsCount = 0;
                        int mailID        = Global.AddMail(dbMgr, fields, out addGoodsCount);
                        if (mailID > 0)
                        {
                            string gmCmd     = string.Format("{0}|{1}", roleID.ToString(), mailID);
                            string gmCmdData = string.Format("-notifymail {0}", gmCmd);
                            ChatMsgManager.AddGMCmdChatMsg(-1, gmCmdData);
                            result = mailID;
                        }
                        else
                        {
                            result = -8;
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 24
0
        private static void _ProcessCharge(DBManager dbMgr, DBUserInfo dbUserInfo, int chargeRoleID, int addUserMoney, int zhigouID, string chargeTm, SingleChargeData chargeData, bool bZhiGouFail = false)
        {
            int currentGiftID  = GameDBManager.GameConfigMgr.GetGameConfigItemInt("big_award_id", 0);
            int moneyToYuanBao = GameDBManager.GameConfigMgr.GetGameConfigItemInt("money-to-yuanbao", 10);
            int moneyToJiFen   = GameDBManager.GameConfigMgr.GetGameConfigItemInt("money-to-jifen", 1);
            int ChargeID       = 0;

            chargeData.MoneyVsChargeIDDict.TryGetValue(addUserMoney, out ChargeID);
            bool bWillGiveZuanShi     = zhigouID == 0 && (chargeData.ChargePlatType == 1 || addUserMoney != chargeData.YueKaMoney);
            bool bSystemProcessCharge = chargeRoleID == -1;
            bool bProcessBuyItem      = zhigouID != 0 && chargeRoleID > 0;

            lock (dbUserInfo)
            {
                if (bWillGiveZuanShi)
                {
                    dbUserInfo.Money += addUserMoney * moneyToYuanBao;
                    if (dbUserInfo.Money < 0)
                    {
                        LogManager.WriteLog(LogTypes.Error, string.Format("充值后玩家元宝变负数修正为0, UserID={0}, Money={1}, AddMoney={2}", dbUserInfo.UserID, dbUserInfo.Money, addUserMoney), null, true);
                        dbUserInfo.Money = 0;
                    }
                }
                if (!bSystemProcessCharge && !bZhiGouFail)
                {
                    dbUserInfo.RealMoney += addUserMoney;
                    if (dbUserInfo.RealMoney < 0)
                    {
                        LogManager.WriteLog(LogTypes.Error, string.Format("充值后玩家realmoney变负数修正为0, UserID={0}, Money={1}, AddMoney={2}", dbUserInfo.UserID, dbUserInfo.RealMoney, addUserMoney), null, true);
                        dbUserInfo.RealMoney = 0;
                    }
                    if (currentGiftID != dbUserInfo.GiftID)
                    {
                        dbUserInfo.GiftJiFen = 0;
                        dbUserInfo.GiftID    = currentGiftID;
                    }
                    if (dbUserInfo.GiftID > 0)
                    {
                        dbUserInfo.GiftJiFen += addUserMoney * moneyToJiFen;
                    }
                }
                int userMoney = dbUserInfo.Money;
                int realMoney = dbUserInfo.RealMoney;
                int giftID    = dbUserInfo.GiftID;
                int giftJiFen = dbUserInfo.GiftJiFen;
                DBWriter.UpdateUserInfo(dbMgr, dbUserInfo);
            }
            DBRoleInfo dbRoleInfo = Global.FindOnlineRoleInfoByUserInfo(dbMgr, dbUserInfo);

            if (dbRoleInfo != null && !bZhiGouFail)
            {
                DBWriter.UpdateCityInfoItem(dbMgr, dbRoleInfo.LastIP, dbRoleInfo.UserID, "inputmoney", addUserMoney * moneyToYuanBao);
            }
            int rid = chargeRoleID;

            if (!bSystemProcessCharge && !bProcessBuyItem)
            {
                rid = DBQuery.LastLoginRole(dbMgr, dbUserInfo.UserID);
            }
            int addUserYuanBao = Global.TransMoneyToYuanBao(addUserMoney);

            if (bProcessBuyItem)
            {
                UserMoneyMgr._ProcessBuyItem(dbMgr, dbUserInfo, chargeRoleID, addUserMoney, zhigouID, chargeTm);
            }
            int superInputFanLi = 0;

            if (!bProcessBuyItem && addUserMoney != chargeData.YueKaMoney && !bZhiGouFail)
            {
                superInputFanLi = UserMoneyMgr._ProcessSuperInputFanLi(dbMgr, dbUserInfo, chargeData, addUserMoney, ChargeID, chargeTm);
            }
            if (!bSystemProcessCharge && bWillGiveZuanShi)
            {
                CFirstChargeMgr.SendToRolebindgold(dbMgr, dbUserInfo.UserID, rid, addUserMoney, chargeData);
            }
            if (!bSystemProcessCharge && !bZhiGouFail)
            {
                SingletonTemplate <FundManager> .Instance().FundAddMoney(dbUserInfo.UserID, addUserYuanBao, rid, 0);

                GameDBManager.RankCacheMgr.OnUserDoSomething(rid, RankType.Charge, addUserYuanBao);
            }
            string gmCmdData = string.Format("-updateyb {0} {1} {2} {3} {4}", new object[]
            {
                dbUserInfo.UserID,
                rid,
                addUserMoney,
                superInputFanLi,
                zhigouID
            });

            ChatMsgManager.AddGMCmdChatMsg(-1, gmCmdData);
            LogManager.WriteLog(LogTypes.Error, string.Format("处理充值成功 UID={0},money={1},itemid={2}", dbUserInfo.UserID, addUserMoney, zhigouID), null, true);
        }
        private void LoadExistStudents_Click(object sender, EventArgs e)
        {
            StudentData.Enabled = false;
            studentDataBindSourc.Clear();
            DBQuery ClassQuery = new DBQuery();

            ClassQuery.WhereEqualTo("objectId", CurrentUser.ClassList[0]);
            DBQueryStatus resultCode = DataBaseOperation.QueryMultipleData <ClassObject>(ClassQuery, out List <ClassObject> result);

            if (resultCode <= 0)
            {
                MessageBox.Show("没找到你想要的班级,这,,不应该吧。", "很失望?");
                return;
            }
            CurrentClass  = result[0];
            ClsID.Text    = CurrentClass.ObjectId;
            ClsDpt.Text   = CurrentClass.CDepartment;
            ClsGrade.Text = CurrentClass.CGrade;
            ClsNum.Text   = CurrentClass.CNumber;
            ClsTID.Text   = CurrentClass.TeacherID;
            if (string.IsNullOrEmpty(CurrentClass.TeacherID))
            {
                MessageBox.Show("嗯,找到了匹配的班级,但好像没有老师绑定这个班。" +
                                "\r\n" +
                                "~快去叫他使用小板凳吧。" +
                                "\r\n\r\n" +
                                "如果你是这个班的老师的话,先去\"设置\"页绑定一下你的班级!", "孤儿班级");
                ClsTName.Text     = "";
                ClsTPhoneNum.Text = "";
            }
            else
            {
                DBQuery TeacherDataQuery = new DBQuery();
                TeacherDataQuery.WhereEqualTo("objectId", CurrentClass.TeacherID);
                if (DataBaseOperation.QueryMultipleData(TeacherDataQuery, out List <UserObject> teacherresult) <= 0)
                {
                    MessageBox.Show("这不应该,这个班级有老师管理,但是查不到老师的任何信息。", "班主任溜了?");
                    ClsTName.Text     = "";
                    ClsTPhoneNum.Text = "";
                }
                else
                {
                    ClsTName.Text     = teacherresult[0].RealName;
                    ClsTPhoneNum.Text = teacherresult[0].PhoneNumber;
                }
            }
            Application.DoEvents();

            //if (MessageBox.Show("找到了班级,是否继续列出班里坐校车的学生?", "要继续吗", MessageBoxButtons.YesNo) == DialogResult.No)
            //    return;
            DBQuery StudentsQuery = new DBQuery();

            StudentsQuery.WhereEqualTo("ClassID", CurrentClass.ObjectId);
            if (DataBaseOperation.QueryMultipleData(StudentsQuery, out List <StudentObject> results) <= 0)
            {
                MessageBox.Show("把数据库翻了个底朝天,还是没有这个班的学生", "学生去哪了?");
            }
            else
            {
                for (int i = 0; i < results.Count; i++)
                {
                    studentDataBindSourc.Add(results[i]);
                    if (!BusDataPair.ContainsValue(results[i].BusID))
                    {
                        MessageBox.Show("这就奇怪了,为啥校车列表里面没有这个学生的记录??" +
                                        $"\r\n 学生姓名:{results[i].StudentName }" +
                                        $" 奇怪的ID:{ results[i].BusID }");
                        StudentData.Rows[i].Cells[2].Value = "";
                    }
                    else
                    {
                        StudentData.Rows[i].Cells[2].Value = BusDataPair.ElementAt(BusDataPair.Values.ToList().IndexOf(results[i].BusID)).Key;
                    }
                }
            }
            DoLog($"成功加载了 {results.Count} 条数据");
            StudentData.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            StudentData.Enabled = true;
        }
Ejemplo n.º 26
0
 public static void QueryTotalUserMoney()
 {
     if (GameDBManager.Flag_Query_Total_UserMoney_Minute >= 5)
     {
         DateTime now                 = DateTime.Now;
         bool     bInCheckTime        = false;
         long     elapsedMilliseconds = (now.Ticks - UserMoneyMgr.LastLastQueryServerTotalUserMoneyTime.Ticks) / 10000L;
         if (elapsedMilliseconds >= (long)(GameDBManager.Flag_Query_Total_UserMoney_Minute * 60 * 1000))
         {
             bInCheckTime = true;
         }
         else if (now.Day != UserMoneyMgr.LastLastQueryServerTotalUserMoneyTime.Day)
         {
             bInCheckTime = true;
         }
         if (bInCheckTime)
         {
             UserMoneyMgr.LastLastQueryServerTotalUserMoneyTime = now;
             LogManager.WriteLog(LogTypes.TotalUserMoney, string.Format("{0}\t{1}\t{2}", 10000, GameDBManager.ZoneID, DBQuery.QueryServerTotalUserMoney()), null, true);
         }
     }
 }
Ejemplo n.º 27
0
 private void FreepassEffect(Account player, Slot slot, Room room, bool isBotMode)
 {
     using (DBQuery query = new DBQuery())
     {
         if (player.bonus.freepass == 0 || player.bonus.freepass == 1 && room.channelType == 4)
         {
             if (isBotMode || slot.state < SlotStateEnum.BATTLE_READY)
             {
                 return;
             }
             if (player.gold >= 200)
             {
                 player.gold -= 200;
                 query.AddQuery("gold", player.gold);
             }
             query.AddQuery("fights_escapes", ++player.statistics.escapes);
         }
         else// if (ch._type != 4)
         {
             if (room.state != RoomStateEnum.Battle)
             {
                 return;
             }
             int xp = 0, gold = 0;
             if (isBotMode)
             {
                 int level = room.IngameAiLevel * (150 + slot.allDeaths);
                 if (level == 0)
                 {
                     level++;
                 }
                 int reward = slot.score / level;
                 gold += reward;
                 xp   += reward;
             }
             else
             {
                 int timePlayed = slot.allKills == 0 && slot.allDeaths == 0 ? 0 : (int)slot.InBattleTime(DateTime.Now);
                 if (room.mode == RoomTypeEnum.Destruction || room.mode == RoomTypeEnum.Suppression)
                 {
                     xp   = (int)(slot.score + (timePlayed / 2.5) + (slot.allDeaths * 2.2) + (slot.objetivos * 20));
                     gold = (int)(slot.score + (timePlayed / 3.0) + (slot.allDeaths * 2.2) + (slot.objetivos * 20));
                 }
                 else
                 {
                     xp   = (int)(slot.score + (timePlayed / 2.5) + (slot.allDeaths * 1.8) + (slot.objetivos * 20));
                     gold = (int)(slot.score + (timePlayed / 3.0) + (slot.allDeaths * 1.8) + (slot.objetivos * 20));
                 }
             }
             xp   = xp > Settings.MaxBattleExp ? Settings.MaxBattleExp : xp;
             gold = gold > Settings.MaxBattleGold ? Settings.MaxBattleGold : gold;
             if ((player.exp + xp) <= 999999999)
             {
                 player.exp += xp;
             }
             if ((player.gold + gold) <= 999999999)
             {
                 player.gold += gold;
             }
             if (xp > 0)
             {
                 query.AddQuery("exp", player.exp);
             }
             if (gold > 0)
             {
                 query.AddQuery("gold", player.gold);
             }
         }
         Utilities.UpdateDB("accounts", "id", player.playerId, query.GetTables(), query.GetValues());
     }
 }
Ejemplo n.º 28
0
        public static TCPProcessCmdResults ProcessDelChargeItemData(DBManager dbMgr, TCPOutPacketPool pool, int nID, byte[] data, int count, out TCPOutPacket tcpOutPacket)
        {
            tcpOutPacket = null;
            string cmdData = null;

            try
            {
                cmdData = new UTF8Encoding().GetString(data, 0, count);
            }
            catch (Exception)
            {
                LogManager.WriteLog(LogTypes.Error, string.Format("解析指令字符串错误, CMD={0}", (TCPGameServerCmds)nID), null, true);
                tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                return(TCPProcessCmdResults.RESULT_DATA);
            }
            try
            {
                string[] fields = cmdData.Split(new char[]
                {
                    ':'
                });
                if (fields.Length != 3)
                {
                    LogManager.WriteLog(LogTypes.Error, string.Format("指令参数个数错误, CMD={0}, Recv={1}, CmdData={2}", (TCPGameServerCmds)nID, fields.Length, cmdData), null, true);
                    tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                    return(TCPProcessCmdResults.RESULT_DATA);
                }
                int SerialID                = Convert.ToInt32(fields[0]);
                int ChargeMoney             = Convert.ToInt32(fields[1]);
                int ReturnUserMoney         = Convert.ToInt32(fields[2]);
                SingleChargeData chargeData = CFirstChargeMgr.ChargeData;
                if (chargeData == null)
                {
                    tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                    return(TCPProcessCmdResults.RESULT_DATA);
                }
                List <TempItemChargeInfo> tempItemInfoList = DBQuery.QueryTempItemChargeInfo(dbMgr, 0, SerialID, 0);
                if (tempItemInfoList.Count == 0)
                {
                    tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                    return(TCPProcessCmdResults.RESULT_DATA);
                }
                string     userID       = tempItemInfoList[0].userID;
                int        chargeRoleID = tempItemInfoList[0].chargeRoleID;
                int        addUserMoney = tempItemInfoList[0].addUserMoney;
                int        zhigouID     = tempItemInfoList[0].zhigouID;
                DBUserInfo dbUserInfo   = dbMgr.GetDBUserInfo(userID);
                if (dbUserInfo == null)
                {
                    tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                    return(TCPProcessCmdResults.RESULT_DATA);
                }
                byte DelState = (byte)((ChargeMoney == 1) ? 2 : 1);
                if (!DBWriter.DeleteChargeItemInfo(dbMgr, SerialID, DelState))
                {
                    tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                    return(TCPProcessCmdResults.RESULT_DATA);
                }
                if (ChargeMoney == 1)
                {
                    UserMoneyMgr._ProcessCharge(dbMgr, dbUserInfo, chargeRoleID, addUserMoney, 0, "", chargeData, true);
                }
                else if (ReturnUserMoney > 0)
                {
                    UserMoneyMgr._ProcessCharge(dbMgr, dbUserInfo, chargeRoleID, ReturnUserMoney, 0, "", chargeData, true);
                }
                tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", nID);
                return(TCPProcessCmdResults.RESULT_DATA);
            }
            catch (Exception e)
            {
                LogManager.WriteException("ProcessDelChargeItemData:" + e.ToString());
            }
            tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
            return(TCPProcessCmdResults.RESULT_DATA);
        }
Ejemplo n.º 29
0
        public void GetDatatable(Tech.QScript.Syntax.SQuery sQuery)
        {
            DBSelectQuery select  = DBQuery.Select();
            bool          isAdded = false;

            foreach (Syntax.Query.Table t in sQuery.tables)
            {
                foreach (Syntax.Query.TableField tf in t.Fields)
                {
                    if (t.TableAlias != "")
                    {
                        select.Field(t.TableAlias.Trim(), tf.FieldName.Trim()).As(tf.FieldName.Trim());
                    }
                    else
                    {
                        select.Field(t.TableName.Trim(), tf.FieldName.Trim()).As(tf.FieldName.Trim());
                    }
                }
            }
            foreach (Syntax.Query.Table t in sQuery.tables)
            {
                if (t.Relations.Count == 0)
                {
                    if (isAdded == false)
                    {
                        select.From(t.TableName.Trim()).As(t.TableAlias.Trim());
                        isAdded = true;
                    }
                }
                isAdded = false;
                int indx = 0;
                foreach (Syntax.Query.Relation r in t.Relations)
                {
                    if (indx == 0)
                    {
                        select.InnerJoin(t.TableName.Trim()).As(t.TableAlias.Trim()).On(r.lefttable.Trim(), r.LeftField.Trim(), GetCompare(r.Operator), r.RightTable.Trim(), r.RightField.Trim());
                    }
                    else if (t.Relations.Count > 1)
                    {
                        select.And(r.lefttable.Trim(), r.LeftField.Trim(), GetCompare(r.Operator), r.RightTable.Trim(), r.RightField.Trim());
                    }
                    indx = indx + 1;
                }
            }
            //foreach (Syntax.Query.Table t in sQuery.from.Tables )
            //{
            //    select.From(t.TableName ).As(t.TableName );
            //}
            int index = 0;

            foreach (Syntax.Query.Where where in sQuery.Conditions)
            {
                if (where.Type == Syntax.Query.ConditionType.filter)
                {
                    if (where.JoinType == Syntax.Query.JoinType.And)
                    {
                        if (index == 0)
                        {
                            select.WhereField(where.lefttable.Trim(), where.LeftField.Trim(), GetCompare(where.Operator), DBConst.String(getValue(where.Operator, where.Value.Trim())));
                        }
                        else
                        {
                            select.AndWhere(where.lefttable.Trim(), where.LeftField.Trim(), GetCompare(where.Operator), DBConst.String(getValue(where.Operator, where.Value.Trim())));
                        }
                    }
                    else if (where.JoinType == Syntax.Query.JoinType.or)
                    {
                        DBField      lff = DBField.Field(where.lefttable, where.LeftField.Trim());
                        DBField      rff = DBField.Field(where.RightTable, where.RightField.Trim());
                        DBComparison d   = DBComparison.Equal(lff, DBConst.String(where.Value.Trim()));

                        select.OrWhere(d);
                    }
                    else if (where.JoinType == Syntax.Query.JoinType.None)
                    {
                        DBField      lff = DBField.Field(where.lefttable, where.LeftField.Trim());
                        DBField      rff = DBField.Field(where.RightTable, where.RightField.Trim());
                        DBComparison d   = DBComparison.Equal(lff, DBConst.String(where.Value.Trim()));
                        select.OrWhereNone(d);
                    }
                    index = index + 1;
                }
            }
            var data = Database.GetDatatable(select);

            query = select.ToSQLString(Database);
            dataTable
                = (System.Data.DataTable)data;
        }
Ejemplo n.º 30
0
        public string Save(string clientName,
                           string clientNo,
                           string address,
                           string state,
                           string country,
                           string email,
                           string phone,
                           string orgName,
                           bool status,
                           string host)
        {
            DBDatabase db;

            db = base.Database;
            string  a            = Shared.generateID();
            DBConst dbClientID   = DBConst.String(a);
            DBConst dbClientName = DBConst.String(clientName);
            DBConst dbClientNo   = DBConst.String(clientNo);
            DBConst dbAddress    = DBConst.String(address);
            DBConst dbState      = DBConst.String(state);
            DBConst dbCountry    = DBConst.String(country);
            DBConst dbstatus     = DBConst.Const(DbType.Boolean, status);
            DBConst dbEmail      = DBConst.String(email);
            DBConst dbPhone      = DBConst.String(phone);
            DBConst dbHost       = DBConst.String(host);
            DBConst dbOrgName    = DBConst.String(orgName);

            DBQuery insert = DBQuery.InsertInto(TzAccount.Client.Table).Fields(
                TzAccount.Client.ClientID.Name,
                TzAccount.Client.ClientName.Name,
                TzAccount.Client.ClientNo.Name,
                TzAccount.Client.Country.Name,
                TzAccount.Client.State.Name,
                TzAccount.Client.PhoneNo.Name,
                TzAccount.Client.Email.Name,
                TzAccount.Client.Status.Name,
                TzAccount.Client.OrganizationName.Name,
                TzAccount.Client.Host.Name,
                TzAccount.Client.Address.Name).Values(
                dbClientID,
                dbClientName,
                dbClientNo,
                dbCountry,
                dbState,
                dbPhone,
                dbEmail,
                dbstatus,
                dbOrgName,
                dbHost,
                dbAddress
                );
            int val = 0;

            using (DbTransaction trans = db.BeginTransaction()) {
                val = db.ExecuteNonQuery(trans, insert);
                trans.Commit();
            }
            if (val > 0)
            {
                return(a);
            }
            else
            {
                return("");
            }
        }
Ejemplo n.º 31
0
 public static void LoadPremNamesFromDB(DBManager dbMgr)
 {
     DBQuery.QueryPreNames(dbMgr, PreNamesManager._PreNamesDict, PreNamesManager._MalePreNamesList, PreNamesManager._FemalePreNamesList);
 }
Ejemplo n.º 32
0
        public void ActionMalware(ModIncidentModel model)
        {
            model.Menu = "Malware";
            var menu = WebMenuService.Instance.CreateQuery().Where(o => o.Activity == true && o.Code == model.Menu).ToSingle();

            model.MenuID = menu != null ? menu.ID : 0;

            // sap xep tu dong
            string orderBy  = AutoSort(model.Sort);
            string orderAdd = string.Empty;

            if (model.MalwareState == 1 || model.MalwareState == 3)
            {
                orderAdd += "ChildNum DESC";
            }
            else if (model.MalwareState == 2 || model.MalwareState == 4)
            {
                orderAdd += "ChildNum ASC";
            }

            DateTime?f    = HL.Core.Global.Convert.ToDateTime(model.From, DateTime.MinValue);
            DateTime?t    = HL.Core.Global.Convert.ToDateTime(model.To, DateTime.MaxValue);
            DateTime?from = f != DateTime.MinValue ? f : null;
            DateTime?to   = t != DateTime.MaxValue ? t : null;
            var      all  = ModIncidentService.Instance.CreateQuery()
                            //.Where(!string.IsNullOrEmpty(model.SearchText), o => o.Name.Contains(model.SearchText))
                            .Where(model.State > 0, o => (o.State & model.State) == model.State)
                            .Where(from != null, o => o.AttackOn >= from)
                            .Where(to != null, o => o.AttackOn <= to)
                            .WhereIn(o => o.MenuID, WebMenuService.Instance.GetChildIDForCP("Incident", model.MenuID, model.LangID))
                            .ToList();

            // Tao danh sach cha
            DBQuery <ModIncidentEntity> dbQuery = null;

            if (model.MalwareState == 1 || model.MalwareState == 2)
            {
                dbQuery = ModIncidentService.Instance.CreateQuery()
                          .WhereIn(o => o.MenuID, WebMenuService.Instance.GetChildIDForCP("Incident", model.MenuID, model.LangID))
                          .Select(o => o.MalwareName)
                          .Distinct();
            }
            else
            {
                dbQuery = ModIncidentService.Instance.CreateQuery()
                          .WhereIn(o => o.MenuID, WebMenuService.Instance.GetChildIDForCP("Incident", model.MenuID, model.LangID))
                          .Select(o => o.ISP)
                          .Distinct();
            }
            if (dbQuery.ToList() == null)
            {
                ViewBag.Data      = new List <ModIncidentEntity>();
                ViewBag.All       = new List <ModIncidentEntity>();
                model.TotalRecord = 0;
                ViewBag.Model     = model;
                return;
            }

            var list = new List <ModIncidentEntity>();

            if (model.MalwareState == 1)
            {
                list = dbQuery.ToList().Select(o => new ModIncidentEntity
                {
                    MalwareName = o.MalwareName,
                    ISP         = "",
                    AttackOn    = null,
                    ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.MalwareName == o.MalwareName).ToList().Count
                })
                       .OrderByDescending(o => o.ChildNum)
                       .Take(model.PageSize)
                       .Skip(model.PageIndex * model.PageSize)
                       .ToList();
            }
            else if (model.MalwareState == 2)
            {
                list = dbQuery.ToList().Select(o => new ModIncidentEntity
                {
                    MalwareName = o.MalwareName,
                    ISP         = "",
                    AttackOn    = null,
                    ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.MalwareName == o.MalwareName).ToList().Count
                })
                       .OrderBy(o => o.ChildNum)
                       .Take(model.PageSize)
                       .Skip(model.PageIndex * model.PageSize)
                       .ToList();
            }
            else if (model.MalwareState == 3)
            {
                list = dbQuery.ToList().Select(o => new ModIncidentEntity
                {
                    MalwareName = "",
                    ISP         = o.ISP,
                    AttackOn    = null,
                    ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.ISP == o.ISP).ToList().Count
                })
                       .OrderByDescending(o => o.ChildNum)
                       .Take(model.PageSize)
                       .Skip(model.PageIndex * model.PageSize)
                       .ToList();
            }
            else if (model.MalwareState == 4)
            {
                list = dbQuery.ToList().Select(o => new ModIncidentEntity
                {
                    MalwareName = "",
                    ISP         = o.ISP,
                    AttackOn    = null,
                    ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.ISP == o.ISP).ToList().Count
                })
                       .OrderBy(o => o.ChildNum)
                       .Take(model.PageSize)
                       .Skip(model.PageIndex * model.PageSize)
                       .ToList();
            }
            else
            {
                list = dbQuery.ToList().Select(o => new ModIncidentEntity
                {
                    MalwareName = o.MalwareName,
                    ISP         = "",
                    AttackOn    = null,
                    ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.MalwareName == o.MalwareName).ToList().Count
                })
                       .OrderBy(o => o.MalwareName)
                       .Take(model.PageSize)
                       .Skip(model.PageIndex * model.PageSize)
                       .ToList();
            }

            ViewBag.Data      = list;
            ViewBag.All       = all;
            model.TotalRecord = dbQuery.TotalRecord;
            ViewBag.Model     = model;
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Populates the specified DataSet with the results of the query using the specified load option.
 /// Multiple results sets from the query will be populated in the order of the tables in the DataSet.
 /// </summary>
 /// <param name="ds">The DataSet to Populate</param>
 /// <param name="option">Specifies the manner in which imported rows are handled</param>
 /// <param name="query">The Query to use to populate the data</param>
 public void PopulateDataSet(DataSet ds, DBQuery query, LoadOption option)
 {
     string[] tables = ExtractTableNames(ds);
     this.PopulateDataSet(ds, query, option, tables);
 }
Ejemplo n.º 34
0
        public void ActionExport2(ModIncidentModel model)
        {
            RenderView(model.Menu);

            //lấy danh sách
            // sap xep tu dong
            string orderBy  = AutoSort(model.Sort);
            string orderAdd = string.Empty;

            if (model.Menu == "Phishing" && (model.PhishingState == 1 || model.PhishingState == 3) ||
                model.Menu == "Malware" && (model.MalwareState == 1 || model.MalwareState == 3))
            {
                orderAdd += "ChildNum DESC";
            }
            else if (model.Menu == "Phishing" && (model.PhishingState == 2 || model.PhishingState == 4) ||
                     model.Menu == "Malware" && (model.MalwareState == 2 || model.MalwareState == 4))
            {
                orderAdd += "ChildNum ASC";
            }

            DateTime?f    = HL.Core.Global.Convert.ToDateTime(model.From, DateTime.MinValue);
            DateTime?t    = HL.Core.Global.Convert.ToDateTime(model.To, DateTime.MaxValue);
            DateTime?from = f != DateTime.MinValue ? f : null;
            DateTime?to   = t != DateTime.MaxValue ? t : null;
            var      all  = ModIncidentService.Instance.CreateQuery()
                            .Where(model.State > 0, o => (o.State & model.State) == model.State)
                            .Where(from != null, o => o.AttackOn >= from)
                            .Where(to != null, o => o.AttackOn <= to)
                            .WhereIn(o => o.MenuID, WebMenuService.Instance.GetChildIDForCP("Incident", model.MenuID, model.LangID))
                            .ToList();

            // Tao danh sach cha
            DBQuery <ModIncidentEntity> dbQuery = null;

            if (model.PhishingState == 1 || model.PhishingState == 2 || model.MalwareState == 1 || model.MalwareState == 2)
            {
                if (model.Menu == "Phishing")
                {
                    dbQuery = ModIncidentService.Instance.CreateQuery()
                              .WhereIn(o => o.MenuID, WebMenuService.Instance.GetChildIDForCP("Incident", model.MenuID, model.LangID))
                              .Select(o => o.Path)
                              .Distinct();
                }
                if (model.Menu == "Malware")
                {
                    dbQuery = ModIncidentService.Instance.CreateQuery()
                              .WhereIn(o => o.MenuID, WebMenuService.Instance.GetChildIDForCP("Incident", model.MenuID, model.LangID))
                              .Select(o => o.MalwareName)
                              .Distinct();
                }
            }
            else
            {
                dbQuery = ModIncidentService.Instance.CreateQuery()
                          .WhereIn(o => o.MenuID, WebMenuService.Instance.GetChildIDForCP("Incident", model.MenuID, model.LangID))
                          .Select(o => o.ISP)
                          .Distinct();
            }
            var lst = dbQuery.ToList();

            if (lst == null || all == null)
            {
                CPViewPage.SetMessage("Không có dữ liệu.");
                return;
            }

            var listEntity = new List <ModIncidentEntity>();

            if (model.Menu == "Phishing")
            {
                if (model.PhishingState == 1)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        Path     = o.Path,
                        ISP      = "",
                        AttackOn = null,
                        ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.ParentID == o.ID).ToList().Count
                    })
                                 .OrderByDescending(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else if (model.PhishingState == 2)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        Path     = o.Path,
                        ISP      = "",
                        AttackOn = null,
                        ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.ParentID == o.ID).ToList().Count
                    })
                                 .OrderBy(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else if (model.PhishingState == 3)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        Path     = "",
                        ISP      = o.ISP,
                        AttackOn = null,
                        ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.ISP == o.ISP).ToList().Count
                    })
                                 .OrderByDescending(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else if (model.PhishingState == 4)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        Path     = "",
                        ISP      = o.ISP,
                        AttackOn = null,
                        ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.ISP == o.ISP).ToList().Count
                    })
                                 .OrderBy(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        Path     = o.Path,
                        ISP      = "",
                        AttackOn = null,
                        ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.ParentID == o.ID).ToList().Count
                    })
                                 .OrderBy(o => o.Path)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
            }
            if (model.Menu == "Malware")
            {
                if (model.MalwareState == 1)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        MalwareName = o.MalwareName,
                        ISP         = "",
                        AttackOn    = null,
                        ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.MalwareName == o.MalwareName).ToList().Count
                    })
                                 .OrderByDescending(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else if (model.MalwareState == 2)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        MalwareName = o.MalwareName,
                        ISP         = "",
                        AttackOn    = null,
                        ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.MalwareName == o.MalwareName).ToList().Count
                    })
                                 .OrderBy(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else if (model.MalwareState == 3)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        MalwareName = "",
                        ISP         = o.ISP,
                        AttackOn    = null,
                        ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.ISP == o.ISP).ToList().Count
                    })
                                 .OrderByDescending(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else if (model.MalwareState == 4)
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        MalwareName = "",
                        ISP         = o.ISP,
                        AttackOn    = null,
                        ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.ISP == o.ISP).ToList().Count
                    })
                                 .OrderBy(o => o.ChildNum)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
                else
                {
                    listEntity = dbQuery.ToList().Select(o => new ModIncidentEntity
                    {
                        MalwareName = o.MalwareName,
                        ISP         = "",
                        AttackOn    = null,
                        ChildNum    = ModIncidentService.Instance.CreateQuery().Where(a => a.MalwareName == o.MalwareName).ToList().Count
                    })
                                 .OrderBy(o => o.Path)
                                 .Take(model.PageSize)
                                 .Skip(model.PageIndex * model.PageSize)
                                 .ToList();
                }
            }

            //khai báo tập hợp bản ghi excel
            List <List <object> > list = new List <List <object> >();
            //khai báo 1 dòng excel
            List <object> _list = null;

            for (int i = 0; listEntity != null && listEntity.Count > 0 && i < listEntity.Count; i++)
            {
                _list = new List <object>();
                // _list.Add(i + 1);
                if (model.PhishingState == 1)
                {
                    _list.Add(listEntity[i].Path);
                    var ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.ParentID == listEntity[i].ID).ToList().Count;
                    _list.Add(ChildNum);
                }
                else if (model.MalwareState == 1)
                {
                    _list.Add(listEntity[i].MalwareName);
                    var ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.MalwareName == listEntity[i].MalwareName).ToList().Count;
                    _list.Add(ChildNum);
                }
                else
                {
                    _list.Add(listEntity[i].ISP);
                    var ChildNum = ModIncidentService.Instance.CreateQuery().Where(a => a.ISP == listEntity[i].ISP).ToList().Count;
                    _list.Add(ChildNum);
                }
                list.Add(_list);
            }

            //ghi exel
            string temp_file = CPViewPage.Server.MapPath("~/Data/upload/files/Excel/BaoCaoSuCo_" + model.Menu + "_" +
                                                         string.Format("{0:yyyy_MM_dd}", DateTime.Now) + ".xlsx");
            string filePath = CPViewPage.Server.MapPath("~/TTPortal/Templates/Export_Deface.xlsx");

            Excel.Export(list, 1, filePath, temp_file);

            CPViewPage.Response.Clear();
            CPViewPage.Response.ContentType = "application/excel";
            CPViewPage.Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(temp_file));
            CPViewPage.Response.WriteFile(temp_file);
            CPViewPage.Response.End();
        }
Ejemplo n.º 35
0
        // Function from file: IsBanned.dm
        public static dynamic IsBanned(string key = null, dynamic address = null, string computer_id = null)
        {
            dynamic _default = null;

            bool    admin      = false;
            string  ckey       = null;
            string  ckeytext   = null;
            string  ipquery    = null;
            string  cidquery   = null;
            DBQuery query      = null;
            string  pckey      = null;
            dynamic ackey      = null;
            dynamic reason     = null;
            dynamic expiration = null;
            string  duration   = null;
            dynamic bantime    = null;
            string  bantype    = null;
            string  expires    = null;
            string  desc       = null;


            if (!Lang13.Bool(key) || !Lang13.Bool(address) || !Lang13.Bool(computer_id))
            {
                GlobalFuncs.log_access("Failed Login (invalid data): " + key + " " + address + "-" + computer_id);
                return(new ByTable()
                       .Set("reason", "invalid login data")
                       .Set("desc", "Error: Could not check ban status, Please try again. Error message: Your computer provided invalid or blank information to the server on connection (byond username, IP, and Computer ID.) Provided information for reference: Username:'******' IP:'" + address + "' Computer ID:'" + computer_id + "'. (If you continue to get this error, please restart byond or contact byond support.)")
                       );
            }

            if (String13.ParseNumber(computer_id) == 2147483648)
            {
                GlobalFuncs.log_access("Failed Login (invalid cid): " + key + " " + address + "-" + computer_id);
                return(new ByTable().Set("reason", "invalid login data").Set("desc", "Error: Could not check ban status, Please try again. Error message: Your computer provided an invalid Computer ID.)"));
            }
            admin = false;
            ckey  = String13.CKey(key);

            if (GlobalVars.admin_datums.Contains(ckey) || GlobalVars.deadmins.Contains(ckey))
            {
                admin = true;
            }

            if (GlobalFuncs.IsGuestKey(key))
            {
                if (!GlobalVars.guests_allowed)
                {
                    GlobalFuncs.log_access("Failed Login: "******" - Guests not allowed");
                    return(new ByTable().Set("reason", "guest").Set("desc", "\nReason: Guests not allowed. Please sign in with a byond account."));
                }

                if (GlobalVars.config.panic_bunker && GlobalVars.dbcon != null && GlobalVars.dbcon.IsConnected())
                {
                    GlobalFuncs.log_access("Failed Login: "******" - Guests not allowed during panic bunker");
                    return(new ByTable()
                           .Set("reason", "guest")
                           .Set("desc", "\nReason: Sorry but the server is currently not accepting connections from never before seen players or guests. If you have played on this server with a byond account before, please log in to the byond account you have played from.")
                           );
                }
            }

            if (Lang13.Bool(GlobalVars.config.extreme_popcap) && GlobalFuncs.living_player_count() >= (GlobalVars.config.extreme_popcap ?? 0) && !admin)
            {
                GlobalFuncs.log_access("Failed Login: "******" - Population cap reached");
                return(new ByTable().Set("reason", "popcap").Set("desc", "\nReason: " + GlobalVars.config.extreme_popcap_message));
            }

            if (GlobalVars.config.ban_legacy_system)
            {
                _default = GlobalFuncs.CheckBan(String13.CKey(key), computer_id, address);

                if (Lang13.Bool(_default))
                {
                    if (admin)
                    {
                        GlobalFuncs.log_admin("The admin " + key + " has been allowed to bypass a matching ban on " + _default["key"]);
                        GlobalFuncs.message_admins("<span class='adminnotice'>The admin " + key + " has been allowed to bypass a matching ban on " + _default["key"] + "</span>");
                        GlobalFuncs.addclientmessage(ckey, "<span class='adminnotice'>You have been allowed to bypass a matching ban on " + _default["key"] + "</span>");
                    }
                    else
                    {
                        GlobalFuncs.log_access("Failed Login: "******" " + computer_id + " " + address + " - Banned " + _default["reason"]);
                        return(_default);
                    }
                }
            }
            else
            {
                ckeytext = String13.CKey(key);

                if (!GlobalFuncs.establish_db_connection())
                {
                    Game13.log.WriteMsg("Ban database connection failure. Key " + ckeytext + " not checked");
                    GlobalVars.diary.WriteMsg("Ban database connection failure. Key " + ckeytext + " not checked");
                    return(_default);
                }
                ipquery  = "";
                cidquery = "";

                if (Lang13.Bool(address))
                {
                    ipquery = " OR ip = '" + address + "' ";
                }

                if (Lang13.Bool(computer_id))
                {
                    cidquery = " OR computerid = '" + computer_id + "' ";
                }
                query = GlobalVars.dbcon.NewQuery("SELECT ckey, ip, computerid, a_ckey, reason, expiration_time, duration, bantime, bantype FROM " + GlobalFuncs.format_table_name("ban") + " WHERE (ckey = '" + ckeytext + "' " + ipquery + " " + cidquery + ") AND (bantype = 'PERMABAN' OR bantype = 'ADMIN_PERMABAN' OR ((bantype = 'TEMPBAN' OR bantype = 'ADMIN_TEMPBAN') AND expiration_time > Now())) AND isnull(unbanned)");
                query.Execute();

                while (query.NextRow())
                {
                    pckey      = query.item[1];
                    ackey      = query.item[4];
                    reason     = query.item[5];
                    expiration = query.item[6];
                    duration   = query.item[7];
                    bantime    = query.item[8];
                    bantype    = query.item[9];

                    if (bantype == "ADMIN_PERMABAN" || bantype == "ADMIN_TEMPBAN")
                    {
                        if (pckey != ckey)
                        {
                            continue;
                        }
                    }

                    if (admin)
                    {
                        if (bantype == "ADMIN_PERMABAN" || bantype == "ADMIN_TEMPBAN")
                        {
                            GlobalFuncs.log_admin("The admin " + key + " is admin banned, and has been disallowed access");
                            GlobalFuncs.message_admins("<span class='adminnotice'>The admin " + key + " is admin banned, and has been disallowed access</span>");
                        }
                        else
                        {
                            GlobalFuncs.log_admin("The admin " + key + " has been allowed to bypass a matching ban on " + pckey);
                            GlobalFuncs.message_admins("<span class='adminnotice'>The admin " + key + " has been allowed to bypass a matching ban on " + pckey + "</span>");
                            GlobalFuncs.addclientmessage(ckey, "<span class='adminnotice'>You have been allowed to bypass a matching ban on " + pckey + "</span>");
                            continue;
                        }
                    }
                    expires = "";

                    if ((String13.ParseNumber(duration) ?? 0) > 0)
                    {
                        expires = " The ban is for " + duration + " minutes and expires on " + expiration + " (server time).";
                    }
                    else
                    {
                        expires = " The is a permanent ban.";
                    }
                    desc     = "\nReason: You, or another user of this computer or connection (" + pckey + ") is banned from playing here. The ban reason is:\n" + reason + "\nThis ban was applied by " + ackey + " on " + bantime + ", " + expires;
                    _default = new ByTable().Set("reason", "" + bantype).Set("desc", "" + desc);
                    GlobalFuncs.log_access("Failed Login: "******" " + computer_id + " " + address + " - Banned " + _default["reason"]);
                    return(_default);
                }
            }
            _default = Game13._internal_IsBanned(key, address, computer_id);

            if (Lang13.Bool(_default))
            {
                if (admin)
                {
                    GlobalFuncs.log_admin("The admin " + key + " has been allowed to bypass a matching host/sticky ban");
                    GlobalFuncs.message_admins("<span class='adminnotice'>The admin " + key + " has been allowed to bypass a matching host/sticky ban</span>");
                    GlobalFuncs.addclientmessage(ckey, "<span class='adminnotice'>You have been allowed to bypass a matching host/sticky ban</span>");
                    return(null);
                }
                else
                {
                    GlobalFuncs.log_access("Failed Login: "******" " + computer_id + " " + address + " - Banned " + _default["message"]);
                }
            }
            return(_default);
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Toggles operation logging on or off
 /// </summary>
 /// <param name="db">The db.</param>
 /// <param name="useOpLogging">if set to <c>true</c> [use op logging].</param>
 public static void opLogging(this IAdminOperations db, bool useOpLogging)
 {
     DBQuery query = new DBQuery("opLogging", useOpLogging ? 1 : 0);
     IDBObject response = db.ExecuteCommand(query);
     response.ThrowIfResponseNotOK("opLogging failed");
 }
Ejemplo n.º 37
0
        void AccountInfoProcessHandler(Task t)
        {
            GlobalTask task         = (GlobalTask)t;
            int        accountId    = -1;
            string     displayName  = "";
            int        hardCurrency = 0;
            string     authString   = "";
            int        vip          = 0;

            AccountInfoRequestArgs args = (AccountInfoRequestArgs)task.Args;
            bool sendAccountInfo        = true;

            if (task.Query.Rows.Count > 0)
            {
                // 0: account_id
                // 1: email
                // 2: password
                // 3: display name
                // 4: hard_currency
                // 5: auth_string
                // 6: vip
                // 7: google_id
                // 8: facebook_id

                // Found the account, check the password
                object[] row = task.Query.Rows[0];
                accountId = (int)row[0];
                string pw          = row[2].ToString();
                string google_id   = (row[7] is DBNull) ? null : row[7].ToString();
                string facebook_id = (row[8] is DBNull) ? null : row[8].ToString();
                if (ValidPassword(args.Password, args.OAuthMode, pw, google_id, facebook_id, args.Email))
                {
                    // password match
                    displayName  = row[3].ToString();
                    hardCurrency = (int)row[4];
                    vip          = (int)row[6];

                    if (row[5] is DBNull)
                    {
                        // Auth string doesnt exist, generate it now
                        authString = GenerateAuthString((string)row[1], pw, displayName, accountId);

                        // Store it in the database
                        DBQuery q = AddDBQuery(string.Format("UPDATE accounts SET auth_string=\"{0}\" WHERE account_id={1};", authString, accountId), null);
                    }
                    else
                    {
                        authString = (string)row[5];
                    }
                }
                else
                {
                    if (args.OAuthMode == 1 && google_id == null)
                    {
                        // Trying to sign in with google but this account isn't associated with google.
                        // Add the google id to the database for this user and try again
                        task.Type = (int)GlobalTask.GlobalType.AccountInfoRequest;
                        AddDBQuery(string.Format("UPDATE accounts SET google_id=\"{0}\" WHERE account_id={1};", args.Password, accountId), task);
                        sendAccountInfo = false;
                    }
                    else if (args.OAuthMode == 2 && facebook_id == null)
                    {
                        // Trying to sign in with facebook but this account isn't associated with facebook.
                        // Add the facebook id to the database for this user and try again
                        task.Type = (int)GlobalTask.GlobalType.AccountInfoRequest;
                        AddDBQuery(string.Format("UPDATE accounts SET facebook_id=\"{0}\" WHERE account_id={1};", args.Password, accountId), task);
                        sendAccountInfo = false;
                    }

                    // password mismatch - displayName stays empty but accountId is filled in
                }
            }
            else
            {
                // Account does not exist
                if (args.DisplayName != null)
                {
                    // This is actually a request to create the account.
                    sendAccountInfo = false;

                    task.Type = (int)GlobalTask.GlobalType.AccountInfoRequest;
                    switch (args.OAuthMode)
                    {
                    default:
                        AddDBQuery(string.Format("INSERT INTO accounts SET email=\"{0}\",password=\"{1}\",display_name=\"{2}\",hard_currency={3},vip={4};", args.Email, args.Password, args.DisplayName, 0, 0), task);
                        break;

                    case 1:     // Google
                        AddDBQuery(string.Format("INSERT INTO accounts SET email=\"{0}\",display_name=\"{1}\",hard_currency={2},vip={3},google_id={4};", args.Email, args.DisplayName, 0, 0, args.Password), task);
                        break;

                    case 2:     // Facebook
                        AddDBQuery(string.Format("INSERT INTO accounts SET email=\"{0}\",display_name=\"{1}\",hard_currency={2},vip={3},facebook_id={4};", args.Email, args.DisplayName, 0, 0, args.Password), task);
                        break;
                    }
                }
            }
            if (sendAccountInfo)
            {
                task.Client.SendAccountInfo(args.ClientKey, accountId, displayName, hardCurrency, vip, authString);
            }
        }
Ejemplo n.º 38
0
        static void FindSortedRecords(DBCollection dbc)
        {
            DBQuery query = new DBQuery();
            try
            {
                BsonDocument condition = new BsonDocument
                {
                    {"Id",
                        new BsonDocument
                        {
                            {"$gte", 50},
                            {"$lte", 70}
                        }
                    }
                };

                query.Matcher = condition;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create query condition");
                Console.WriteLine(e.Message);
                return;
            }

            try
            {
                BsonDocument orderBy = new BsonDocument { { "id", -1 } };

                query.OrderBy = orderBy;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create orderBy clause");
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("Find ordered data ( by \"id\" in DESC order ) from Collection");
            Common.FindRecord(dbc, query);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Adds the fields.
        /// </summary>
        private void AddFields()
        {
            foreach (var field in this.myMap.Fields)
            {
                var connection = new TreeWatchDatabase();
                var query = new DBQuery<Field>(connection);
                query.GetChildren(field);
                if (field.Blocks.Count != 0)
                {
                    foreach (var block in field.Blocks)
                    {
                        if (block.BoundingCoordinates.Count != 0 && block.BoundingCoordinates.Count >= 3)
                        {
                            this.Map.AddPolygon(GetPolygon(
                                    FieldMapRenderer.ConvertCoordinates(block.BoundingCoordinates),
                                    block.TreeType.ColorProp.ToAndroid()));
                        }
                    }
                }

                if (field.BoundingCoordinates.Count != 0 && field.BoundingCoordinates.Count >= 3)
                {
                    this.Map.AddPolygon(GetPolygon(
                            FieldMapRenderer.ConvertCoordinates(field.BoundingCoordinates),
                            this.myMap.OverLayColor.ToAndroid(),
                            this.myMap.BoundaryColor.ToAndroid()));
                }
            }
        }
Ejemplo n.º 40
0
 /// <summary>
 /// Queries the trace level.
 /// </summary>
 /// <param name="db">The db.</param>
 /// <param name="traceLevel">The trace level.</param>
 public static void queryTraceLevel(this IAdminOperations db, int traceLevel)
 {
     DBQuery query = new DBQuery("queryTraceLevel", traceLevel);
     IDBObject response = db.ExecuteCommand(query);
     response.ThrowIfResponseNotOK("queryTraceLevel failed");
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Executes the translated Find query.
        /// </summary>
        /// <returns>The result of executing the translated Find query.</returns>
        public override object Execute()
        {
            if (_take.HasValue && _take.Value == 0)
            {
                var type = _ofType ?? DocumentType;

                return typeof(Enumerable).GetMethod("Empty").MakeGenericMethod(type).Invoke(null, null);
            }

            var query = BuildQuery();

            //if (_distinct != null)
            //{
            //    return ExecuteDistinct(query);
            //}
            
            //var cursor = Collection.FindAs(DocumentType, query);

            DBQuery dbQuery = new DBQuery();
            dbQuery.Matcher = query as BsonDocument;

            if (_orderBy != null)
            {
                var sortBy = new SortByDocument();
                foreach (var clause in _orderBy)
                {
                    var keyExpression = clause.Key.Body;
                    var serializationInfo = _serializationInfoHelper.GetSerializationInfo(keyExpression);
                    var direction = (clause.Direction == OrderByDirection.Descending) ? -1 : 1;
                    sortBy.Add(serializationInfo.ElementName, direction);
                }                
                //cursor.SetSortOrder(sortBy);
                dbQuery.OrderBy = sortBy;
            }

            if (_skip != null)
            {
                //cursor.SetSkip(_skip.Value);
                dbQuery.SkipRowsCount = _skip.Value;
            }

            if (_take != null)
            {
                //cursor.SetLimit(_take.Value);
                dbQuery.ReturnRowsCount = _take.Value;
            }

            if (_indexHint != null)
            {
                if (_indexHint.IsString)
                {
                    //cursor.SetHint(_indexHint.AsString);
                }
                else if (_indexHint.IsBsonDocument)
                {
                    //cursor.SetHint(_indexHint.AsBsonDocument);
                    dbQuery.Hint = _indexHint.AsBsonDocument;
                }
                else
                {
                    throw new NotSupportedException("Index hints must be strings or documents");
                }
            }

            var cursor = Collection.Query(dbQuery);
            cursor.DBQuery = dbQuery;

            var projection = _projection;
            if (_ofType != null)
            {
                if (projection == null)
                {
                    var paramExpression = Expression.Parameter(DocumentType, "x");
                    var convertExpression = Expression.Convert(paramExpression, _ofType);
                    projection = Expression.Lambda(convertExpression, paramExpression);
                }
                else
                {
                    var paramExpression = Expression.Parameter(DocumentType, "x");
                    var convertExpression = Expression.Convert(paramExpression, _ofType);
                    var body = ExpressionParameterReplacer.ReplaceParameter(projection.Body, projection.Parameters[0], convertExpression);
                    projection = Expression.Lambda(body, paramExpression);
                }
            }

            IProjector projector;
            if (projection == null)
            {
                var projectorType = typeof(IdentityProjector<>).MakeGenericType(DocumentType);
                projector = (IProjector)Activator.CreateInstance(projectorType, cursor);
            }
            else
            {
                var lambdaType = projection.GetType();
                var delegateType = lambdaType.GetGenericArguments()[0];
                var sourceType = delegateType.GetGenericArguments()[0];
                var resultType = delegateType.GetGenericArguments()[1];
                var projectorType = typeof(Projector<,>).MakeGenericType(sourceType, resultType);
                var compiledProjection = projection.Compile();
                projector = (IProjector)Activator.CreateInstance(projectorType, cursor, compiledProjection);
            }

            if (_elementSelector != null)
            {
                return _elementSelector(projector);
            }
            else
            {
                return projector;
            }
        }
        public void InsertTest_WithId()
        {
            int testTypeSize = 8;

            for (int i = 0; i < testTypeSize; i++)
            {
                // insert
                BsonDocument insertor = new BsonDocument();
                string       date     = DateTime.Now.ToString();
                insertor.Add("operation", "Insert");
                insertor.Add("date", date);
                switch (i)
                {
                case 0:
                    insertor.Add("_id", 3.14);
                    break;

                case 1:
                    insertor.Add("_id", "abcdefg");
                    break;

                case 2:
                    insertor.Add("_id", new BsonDocument("id", "id"));
                    break;

                case 3:
                    insertor.Add("_id", ObjectId.GenerateNewId());
                    break;

                case 4:
                    insertor.Add("_id", true);
                    break;

                case 5:
                    insertor.Add("_id", 1234);
                    break;

                case 6:
                    insertor.Add("_id", 10000L);
                    break;

                case 7:
                    insertor.Add("_id", new BsonTimestamp(1000000000L));
                    break;

                default:
                    continue;
                }
                coll.Delete(null);
                BsonValue value = coll.Insert(insertor);
                Object    id    = null;
                BsonType  type  = value.BsonType;
                if (type == BsonType.Double)
                {
                    id = value.AsDouble;
                }
                else if (type == BsonType.String)
                {
                    id = value.AsString;
                }
                else if (type == BsonType.Document)
                {
                    id = value.AsBsonDocument;
                }
                else if (type == BsonType.Array)
                {
                    id = value.AsBsonArray;
                }
                else if (type == BsonType.Binary)
                {
                    id = value.AsBsonBinaryData;
                }
                else if (type == BsonType.Undefined)
                {
                    id = value.AsBsonUndefined;
                }
                else if (type == BsonType.ObjectId)
                {
                    id = value.AsObjectId;
                }
                else if (type == BsonType.Boolean)
                {
                    id = value.AsBoolean;
                }
                else if (type == BsonType.DateTime)
                {
                    id = value.AsDateTime;
                }
                else if (type == BsonType.Null)
                {
                    ;
                }
                else if (type == BsonType.RegularExpression)
                {
                    id = value.AsRegex;
                }
                else if (type == BsonType.JavaScript)
                {
                    id = value.AsBsonJavaScript;
                }
                else if (type == BsonType.Symbol)
                {
                    id = value.AsBsonSymbol;
                }
                else if (type == BsonType.JavaScriptWithScope)
                {
                    id = value.AsBsonJavaScriptWithScope;
                }
                else if (type == BsonType.Int32)
                {
                    id = value.AsInt32;
                }
                else if (type == BsonType.Timestamp)
                {
                    id = value.AsBsonTimestamp;
                }
                else if (type == BsonType.Int64)
                {
                    id = value.AsInt64;
                }
                else if (type == BsonType.MinKey)
                {
                    id = value.AsBsonMinKey;
                }
                else if (type == BsonType.MaxKey)
                {
                    id = value.AsBsonMaxKey;
                }

                BsonDocument matcher = new BsonDocument();
                DBQuery      query   = new DBQuery();
                matcher.Add("date", date);
                query.Matcher = matcher;
                DBCursor cursor = coll.Query(query);
                Assert.IsNotNull(cursor);
                BsonDocument bson = cursor.Next();
                Assert.IsNotNull(bson);

                BsonValue ret = bson.GetValue("_id");
                type = ret.BsonType;
                if (type == BsonType.Double)
                {
                    Assert.IsTrue(id.Equals(ret.AsDouble));
                }
                else if (type == BsonType.String)
                {
                    Assert.IsTrue(id.Equals(ret.AsString));
                }
                else if (type == BsonType.Document)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonDocument));
                }
                else if (type == BsonType.Array)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonArray));
                }
                else if (type == BsonType.Binary)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonBinaryData));
                }
                else if (type == BsonType.Undefined)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonUndefined));
                }
                else if (type == BsonType.ObjectId)
                {
                    Assert.IsTrue(id.Equals(ret.AsObjectId));
                }
                else if (type == BsonType.Boolean)
                {
                    Assert.IsTrue(id.Equals(ret.AsBoolean));
                }
                else if (type == BsonType.DateTime)
                {
                    Assert.IsTrue(id.Equals(ret.AsDateTime));
                }
                else if (type == BsonType.Null)
                {
                    Assert.IsTrue(id == null);
                }
                else if (type == BsonType.RegularExpression)
                {
                    Assert.IsTrue(id.Equals(ret.AsRegex));
                }
                else if (type == BsonType.JavaScript)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonJavaScript));
                }
                else if (type == BsonType.Symbol)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonSymbol));
                }
                else if (type == BsonType.JavaScriptWithScope)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonJavaScriptWithScope));
                }
                else if (type == BsonType.Int32)
                {
                    Assert.IsTrue(id.Equals(ret.AsInt32));
                }
                else if (type == BsonType.Timestamp)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonTimestamp));
                }
                else if (type == BsonType.Int64)
                {
                    Assert.IsTrue(id.Equals(ret.AsInt64));
                }
                else if (type == BsonType.MinKey)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonMinKey));
                }
                else if (type == BsonType.MaxKey)
                {
                    Assert.IsTrue(id.Equals(ret.AsBsonMaxKey));
                }
            }
        }
Ejemplo n.º 43
0
        static void FindRecordsUsingHintCScan(DBCollection dbc)
        {
            DBQuery query = new DBQuery();
            try
            {
                BsonDocument condition = new BsonDocument
                {
                    {"Id",
                        new BsonDocument
                        {
                            {"$gte", 50},
                            {"$lte", 70}
                        }
                    }
                };

                query.Matcher = condition;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create query condition");
                Console.WriteLine(e.Message);
                return;
            }

            try
            {
                // provide NULL for collection scan
                BsonDocument hint = new BsonDocument { { "", "" } };

                query.Hint = hint;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create hint");
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("Find records using collection scan");
            Common.FindRecord(dbc, query);
        }
Ejemplo n.º 44
0
        static void FindRangeRecords(DBCollection dbc)
        {
            DBQuery query = new DBQuery();
            try 
            {
                BsonDocument condition = new BsonDocument
                {
                    {"Id",
                        new BsonDocument
                        {
                            {"$gte", 25},
                            {"$lte", 30}
                        }
                    }
                };

                query.Matcher = condition;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create range record query condition");
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("Find range records from collection");
            Common.FindRecord(dbc, query);
        }
        public IActionResult RunQuery(DBQuery query)
        {
            var result = this.context.Database.ExecuteSqlRaw(query.Query);

            return(Ok(result));
        }
Ejemplo n.º 46
0
Archivo: M14.cs Proyecto: TPF-TUW/M14
        private void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (slueCode.Text.Trim() == "")
            {
                FUNC.msgWarning("Please input customer.");
                slueCode.Focus();
            }
            else if (txeDes.Text.Trim() == "")
            {
                FUNC.msgWarning("Please input destination code.");
                txeDes.Focus();
            }
            else if (txeShip.Text.Trim() == "")
            {
                FUNC.msgWarning("Please input ship to name.");
                txeShip.Focus();
            }
            else
            {
                if (FUNC.msgQuiz("Confirm save data ?") == true)
                {
                    StringBuilder sbSQL     = new StringBuilder();
                    string        strCREATE = "0";
                    if (txeCREATE.Text.Trim() != "")
                    {
                        strCREATE = txeCREATE.Text.Trim();
                    }

                    string strUPDATE = "0";
                    if (txeUPDATE.Text.Trim() != "")
                    {
                        strUPDATE = txeUPDATE.Text.Trim();
                    }

                    bool chkGMP = chkDuplicate();
                    if (chkGMP == true)
                    {
                        if (lblStatus.Text == "* Add Destination")
                        {
                            sbSQL.Append("  INSERT INTO CustomerAddress(OIDCUST, Code, ShipToName, ShipToAddress1, ShipToAddress2, ShipToAddress3, Country, PostCode, TelephoneNo, FaxNo, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate) ");
                            sbSQL.Append("  VALUES('" + slueCode.EditValue.ToString() + "', N'" + txeDes.Text.Trim().Replace("'", "''") + "', N'" + txeShip.Text.Trim().Replace("'", "''") + "', N'" + txeAddr1.Text.Trim().Replace("'", "''") + "', N'" + txeAddr2.Text.Trim().Replace("'", "''") + "', N'" + txeAddr3.Text.Trim().Replace("'", "''") + "', N'" + txeCountry.Text.Trim() + "', N'" + txePostCode.Text.Trim() + "', N'" + txeTelNo.Text.Trim() + "', ");
                            sbSQL.Append("         N'" + txeFaxNo.Text.Trim() + "', '" + strCREATE + "', GETDATE(), '" + strUPDATE + "', GETDATE()) ");
                        }
                        else if (lblStatus.Text == "* Edit Destination")
                        {
                            sbSQL.Append("  UPDATE CustomerAddress SET ");
                            sbSQL.Append("      OIDCUST='" + slueCode.EditValue.ToString() + "', Code=N'" + txeDes.Text.Trim().Replace("'", "''") + "', ");
                            sbSQL.Append("      ShipToName=N'" + txeShip.Text.Trim().Replace("'", "''") + "', ShipToAddress1=N'" + txeAddr1.Text.Trim().Replace("'", "''") + "', ");
                            sbSQL.Append("      ShipToAddress2=N'" + txeAddr2.Text.Trim().Replace("'", "''") + "', ShipToAddress3=N'" + txeAddr3.Text.Trim().Replace("'", "''") + "', ");
                            sbSQL.Append("      Country=N'" + txeCountry.Text.Trim() + "', PostCode=N'" + txePostCode.Text.Trim() + "', TelephoneNo=N'" + txeTelNo.Text.Trim() + "', ");
                            sbSQL.Append("      FaxNo=N'" + txeFaxNo.Text.Trim() + "', UpdatedBy='" + strUPDATE + "', UpdatedDate=GETDATE() ");
                            sbSQL.Append("  WHERE(OIDCUSTAdd = '" + txeID.Text.Trim() + "') ");
                        }

                        //MessageBox.Show(sbSQL.ToString());
                        if (sbSQL.Length > 0)
                        {
                            try
                            {
                                bool chkSAVE = new DBQuery(sbSQL).runSQL();
                                if (chkSAVE == true)
                                {
                                    FUNC.msgInfo("Save complete.");
                                    bbiNew.PerformClick();
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }
                else
                {
                    txeDes.Text = "";
                    txeDes.Focus();
                    FUNC.msgWarning("Duplicate destination code. !! Please Change.");
                }
            }
        }
Ejemplo n.º 47
0
        public static void FindRecord(DBCollection dbc, DBQuery query)
        {
            try
            {
                // find specific records from collection with DBQuery
                DBCursor cursor = dbc.Query(query);

                Console.WriteLine("Record read:");
                while ( cursor.Next() != null )
                    Console.WriteLine(cursor.Current().ToString());
            }
            catch (BaseException e)
            {
                Console.WriteLine("Failed to find records from collection, ErrorType = {0}", e.ErrorType);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }
        }
Ejemplo n.º 48
0
Archivo: F03.cs Proyecto: TPF-TUW/F03
        private bool chkDuplicate()
        {
            bool   chkDup  = true;
            string Company = "";

            if (glueCompany.Text.Trim() != "")
            {
                Company = glueCompany.EditValue.ToString();
            }

            string Branch = "";

            if (glueBranch.Text.Trim() != "")
            {
                Branch = glueBranch.EditValue.ToString();
            }

            string DPType = "";

            if (glueDPType.Text.Trim() != "")
            {
                DPType = glueDPType.EditValue.ToString();
            }

            if (lblStatus.Text == "* Add Department")
            {
                if (txeCode.Text.Trim() != "" || txeName.Text.Trim() != "")
                {
                    StringBuilder sbSQL = new StringBuilder();
                    if (txeCode.Text.Trim() != "" && chkDup == true)
                    {
                        sbSQL.Clear();
                        sbSQL.Append("SELECT TOP(1) Code FROM " + this.dbDP + " WHERE (OIDCOMPANY = '" + Company + "') AND (OIDBRANCH = '" + Branch + "') AND (DepartmentType = '" + DPType + "') AND (Code = N'" + txeCode.Text.Trim() + "') ");
                        string chkNo = new DBQuery(sbSQL).getString();
                        if (chkNo != "")
                        {
                            txeCode.Text = "";
                            txeCode.Focus();
                            chkDup = false;
                            FUNC.msgWarning("Duplicate department code. !! Please Change.");
                        }
                    }

                    if (txeName.Text.Trim() != "" && chkDup == true)
                    {
                        sbSQL.Clear();
                        sbSQL.Append("SELECT TOP(1) Code FROM " + this.dbDP + " WHERE (OIDCOMPANY = '" + Company + "') AND (OIDBRANCH = '" + Branch + "') AND (DepartmentType = '" + DPType + "') AND (Name = N'" + txeName.Text.Trim() + "') ");
                        string chkNo = new DBQuery(sbSQL).getString();
                        if (chkNo != "")
                        {
                            txeName.Text = "";
                            txeName.Focus();
                            chkDup = false;
                            FUNC.msgWarning("Duplicate department name. !! Please Change.");
                        }
                    }
                }
            }
            else if (lblStatus.Text == "* Edit Department")
            {
                if (txeCode.Text.Trim() != "" || txeName.Text.Trim() != "")
                {
                    StringBuilder sbSQL = new StringBuilder();
                    if (txeCode.Text.Trim() != "" && chkDup == true)
                    {
                        sbSQL.Clear();
                        sbSQL.Append("SELECT TOP(1) OIDDEPT FROM " + this.dbDP + " WHERE (OIDCOMPANY = '" + Company + "') AND (OIDBRANCH = '" + Branch + "') AND (DepartmentType = '" + DPType + "') AND (Code = N'" + txeCode.Text.Trim() + "') ");
                        string chkNo = new DBQuery(sbSQL).getString();
                        if (chkNo != "" && chkNo != txeID.Text.Trim())
                        {
                            txeCode.Text = "";
                            txeCode.Focus();
                            chkDup = false;
                            FUNC.msgWarning("Duplicate department code. !! Please Change.");
                        }
                    }

                    if (txeName.Text.Trim() != "" && chkDup == true)
                    {
                        sbSQL.Clear();
                        sbSQL.Append("SELECT TOP(1) OIDDEPT FROM " + this.dbDP + " WHERE (OIDCOMPANY = '" + Company + "') AND (OIDBRANCH = '" + Branch + "') AND (DepartmentType = '" + DPType + "') AND (Name = N'" + txeName.Text.Trim() + "') ");
                        string chkNo = new DBQuery(sbSQL).getString();
                        if (chkNo != "" && chkNo != txeID.Text.Trim())
                        {
                            txeName.Text = "";
                            txeName.Focus();
                            chkDup = false;
                            FUNC.msgWarning("Duplicate department name. !! Please Change.");
                        }
                    }
                }
            }

            return(chkDup);
        }
Ejemplo n.º 49
0
Archivo: F03.cs Proyecto: TPF-TUW/F03
        private void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (glueCompany.Text.Trim() == "")
            {
                FUNC.msgWarning("Please select company.");
                glueCompany.Focus();
            }
            else if (glueBranch.Text.Trim() == "")
            {
                FUNC.msgWarning("Please select branch.");
                glueBranch.Focus();
            }
            else if (glueDPType.Text.Trim() == "")
            {
                FUNC.msgWarning("Please select department type.");
                glueDPType.Focus();
            }
            else if (txeCode.Text.Trim() == "")
            {
                FUNC.msgWarning("Please input code.");
                txeCode.Focus();
            }
            else if (txeName.Text.Trim() == "")
            {
                FUNC.msgWarning("Please input name.");
                txeName.Focus();
            }
            else
            {
                if (FUNC.msgQuiz("Confirm save data ?") == true)
                {
                    StringBuilder sbSQL     = new StringBuilder();
                    string        strCREATE = "0";
                    if (txeCREATE.Text.Trim() != "")
                    {
                        strCREATE = txeCREATE.Text.Trim();
                    }

                    bool chkGMP = chkDuplicate();
                    if (chkGMP == true)
                    {
                        string Status = "NULL";
                        if (rgStatus.SelectedIndex != -1)
                        {
                            Status = rgStatus.Properties.Items[rgStatus.SelectedIndex].Value.ToString();
                        }

                        if (lblStatus.Text == "* Add Department")
                        {
                            sbSQL.Append("  INSERT INTO " + this.dbDP + "(Code, Name, DepartmentType, OIDCOMPANY, OIDBRANCH, Status, CreatedBy, CreatedDate) ");
                            sbSQL.Append("  VALUES(N'" + txeCode.Text.Trim().Replace("'", "''") + "', N'" + txeName.Text.Trim().Replace("'", "''") + "', '" + glueDPType.EditValue.ToString() + "', '" + glueCompany.EditValue.ToString() + "', '" + glueBranch.EditValue.ToString() + "', " + Status + ", '" + strCREATE + "', GETDATE()) ");
                        }
                        else if (lblStatus.Text == "* Edit Department")
                        {
                            sbSQL.Append("  UPDATE " + this.dbDP + " SET ");
                            sbSQL.Append("      Code=N'" + txeCode.Text.Trim().Replace("'", "''") + "', ");
                            sbSQL.Append("      Name=N'" + txeName.Text.Trim().Replace("'", "''") + "', ");
                            sbSQL.Append("      DepartmentType='" + glueDPType.EditValue.ToString() + "', ");
                            sbSQL.Append("      OIDCOMPANY='" + glueCompany.EditValue.ToString() + "', ");
                            sbSQL.Append("      OIDBRANCH='" + glueBranch.EditValue.ToString() + "', ");
                            sbSQL.Append("      Status=" + Status + " ");
                            sbSQL.Append("  WHERE (OIDDEPT = '" + txeID.Text.Trim() + "') ");
                        }

                        //MessageBox.Show(sbSQL.ToString());
                        if (sbSQL.Length > 0)
                        {
                            try
                            {
                                bool chkSAVE = new DBQuery(sbSQL).runSQL();
                                if (chkSAVE == true)
                                {
                                    FUNC.msgInfo("Save complete.");
                                    bbiNew.PerformClick();
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Adds the fields to the map.
        /// </summary>
        private void AddFields()
        {
            var connection = new TreeWatchDatabase();
            foreach (var field in this.myMap.Fields)
            {
                var query = new DBQuery<Field>(connection);
                var blockPolygons = new List<ColorPolygon>();
                query.GetChildren(field);
                if (field.Blocks.Count != 0)
                {
                    foreach (var block in field.Blocks)
                    {
                        if (block.BoundingCoordinates.Count != 0 && block.BoundingCoordinates.Count >= 3)
                        {
                            var blockPoints = ConvertCoordinates(block.BoundingCoordinates);
                            var blockPolygon = (ColorPolygon)MKPolygon.FromCoordinates(blockPoints);
                            blockPolygon.FillColor = block.TreeType.ColorProp.ToCGColor();
                            blockPolygons.Add(blockPolygon);
                        }
                    }

                    var blockMultiPolygon = new MultiPolygon(blockPolygons);

                    this.mapView.AddOverlay(blockMultiPolygon);
                }

                if (field.BoundingCoordinates.Count != 0 && field.BoundingCoordinates.Count >= 3)
                {
                    var points = ConvertCoordinates(field.BoundingCoordinates);
                    var polygon = MKPolygon.FromCoordinates(points);
                    polygon.Title = "Field";
                    this.mapView.AddOverlay(polygon);
                }
            }

            var query2 = new DBQuery<HeatMap>(connection);
            var heatmaps = query2.GetAllWithChildren();
            var heatmap = heatmaps[0];

            this.AddHeatMap(heatmap.Points);
        }