示例#1
0
文件: Tex.cs 项目: AramisIT/Himtrans
 void Tex_BeforeWriting(DatabaseObject item, ref bool cancel)
 {
     int result = 0;
     cancel = !Int32.TryParse(((CatalogTable)item).Description, out result) || result == 0;
     if (cancel)
     {
         "Наименование текса должно быть числом отличным от нуля!".AlertBox();
     }
 }
示例#2
0
        /// <summary>
        /// Extracts the world from the BigDB database.
        /// </summary>
        /// <param name="obj">The object.</param>
        public static void FromDatabaseObject(DatabaseObject obj)
        {
            int width = obj.GetInt("width", 200);
            int height = obj.GetInt("height", 200);
            if (!obj.Contains("worlddata")) {
                Console.WriteLine("Error: No world data available");
                return;
            }

            UnserializeFromComplexObject(obj.GetArray("worlddata"), width, height);
        }
示例#3
0
 public void SubmitCurrentLevel()
 {
     DatabaseObject DO = new DatabaseObject();
     DO.Set("attempts",0);
     DO.Set("creator",username);
     DO.Set("fail",0);
     DO.Set("pass",0);
     DO.Set("leveldata",DataManager.instance.selectedLevel.levelData);
     string uid = username+"_"+System.DateTime.Now.Ticks;
     client.BigDB.CreateObject("CustomLevels",uid,DO,OnCreateLevelData,FailCreateLevelData);
     DebugConsole.Log("Submitted");
 }
示例#4
0
 public NPCPlayer(BasicRoom ggameLink)
 {
     setRoomLink(ggameLink);
     realID = ggameLink.rand.Next(10000).ToString();
     _spells = new DatabaseObject();
     //TODO: random powerups here
     var splitPowerup = new DatabaseObject();
     splitPowerup.Set(DBProperties.SPELL_SLOT, 1);
     var lightning = new DatabaseObject();
     lightning.Set(DBProperties.SPELL_SLOT, 2);
     _spells.Set(Spells.SPLIT_IN_TWO, splitPowerup); //first panel slot
     _spells.Set(Spells.LIGHTNING_ONE, lightning); //second panel slot
 }
        public void checkIfNewbie(Player player)
        {
            if (!player.PlayerObject.Contains(DBProperties.SPELL_OBJECT)) //new guy
            {
                double expiresDate = Utils.unixSecs() + GameConfig.SPELL_ACTIVATION_TIME * 60 * 60;
                if (player.isGuest)
                    expiresDate = Utils.unixSecs() + (60 * 60 * 24 * 365 * 500L); //for 500 years, should be enough; Adding L solves "The operation overflows at compile time in checked mode" problem

                DatabaseObject spells = new DatabaseObject(); //fill slots
                DatabaseObject freezeSpell = new DatabaseObject();
                freezeSpell.Set(DBProperties.SPELL_SLOT, 1).Set(DBProperties.SPELL_EXPIRES, expiresDate);
                DatabaseObject splitSpell = new DatabaseObject();
                splitSpell.Set(DBProperties.SPELL_SLOT, 2).Set(DBProperties.SPELL_EXPIRES, expiresDate);
                DatabaseObject lightningSpell = new DatabaseObject();
                lightningSpell.Set(DBProperties.SPELL_SLOT, 3).Set(DBProperties.SPELL_EXPIRES, expiresDate);
                DatabaseObject charmSpell = new DatabaseObject();
                charmSpell.Set(DBProperties.SPELL_SLOT, 4).Set(DBProperties.SPELL_EXPIRES, expiresDate);
                DatabaseObject bouncyShield = new DatabaseObject();
                bouncyShield.Set(DBProperties.SPELL_SLOT, 5).Set(DBProperties.SPELL_EXPIRES, expiresDate);
                spells.Set(Spells.FREEZE, freezeSpell);
                spells.Set(Spells.SPLIT_IN_TWO, splitSpell);
                spells.Set(Spells.LIGHTNING_ONE, lightningSpell);
                spells.Set(Spells.LASER_SHOTS, charmSpell);
                spells.Set(Spells.BOUNCY_SHIELD, bouncyShield);

                player.PlayerObject.Set(DBProperties.SPELL_OBJECT, spells);
                player.PlayerObject.Set(DBProperties.ENERGY, GameConfig.ENERGY_MAX);
                player.PlayerObject.Set(DBProperties.ENERGY_LAST_UPDATE, Utils.unixSecs());
                player.PlayerObject.Set(DBProperties.ENERGY_EXPIRES, (double)0);
                player.PlayerObject.Set(DBProperties.RANK_NUMBER, 1);
                player.PlayerObject.Set(DBProperties.RANK_PROGRESS, GameConfig.RANK_PROGRESS_START);
                player.PlayerObject.Set(DBProperties.BOUNCER_ID, ShopItemsInfo.BOUNCER_STANDART_BLUE);
                player.PlayerObject.Set(DBProperties.SOUNDS_ON, true);
                player.PlayerObject.Set(DBProperties.MUSIC_ON, true);

                player.PlayerObject.Save();

                BuyItemInfo bluePanel = new BuyItemInfo(ShopItemsInfo.BOUNCER_STANDART_BLUE);
                player.PayVault.Give(new BuyItemInfo[1]  { bluePanel }, delegate() { }, _roomLink.handleError);
                player.PayVault.Credit(GameConfig.COINS_START_AMOUNT, "Started playing",
                    delegate() { Console.WriteLine("Player got start coins"); }, handleError);
            }
        }
示例#6
0
        /// <summary>
        /// Unserializes the BigDB database world object.
        /// </summary>
        /// <param name="worlddata">The world data.</param>
        /// <param name="width">The width of the world.</param>
        /// <param name="height">The height of the world.</param>
        public static void UnserializeFromComplexObject(DatabaseObject input, int width, int height, string worldID)
        {
            Minimap minimap = new Minimap();
            minimap.width = width;
            minimap.height = height;
            minimap.initialize();

            if (input.Contains("worlddata"))
            {
                foreach (DatabaseObject ct in input.GetArray("worlddata").Reverse())
                {
                    if (ct.Count == 0) continue;
                    uint blockId = ct.GetUInt("type");
                    int layer = ct.GetInt("layer", 0);

                    byte[] x = ct.GetBytes("x", new byte[0]), y = ct.GetBytes("y", new byte[0]),
                           x1 = ct.GetBytes("x1", new byte[0]), y1 = ct.GetBytes("y1", new byte[0]);

                    for (int j = 0; j < x1.Length; j++)
                    {
                        byte nx = x1[j];
                        byte ny = y1[j];

                        minimap.drawBlock(layer, nx, ny, blockId);
                    }
                    for (int k = 0; k < x.Length; k += 2)
                    {
                        uint nx2 = (uint)(((int)x[k] << 8) + (int)x[k + 1]);
                        uint ny2 = (uint)(((int)y[k] << 8) + (int)y[k + 1]);

                        minimap.drawBlock(layer, (int)nx2, (int)ny2, blockId);
                    }
                }
            }
            else if (input.Contains("world"))
            {

            }

            minimap.Save(worldID + "_bigdb.png", histogram);
        }
示例#7
0
        public override void UserJoined(BlockPlayer player)
        {
            this.PlayerIO.BigDB.Load("Invitations", player.JoinData["inviteid"], delegate(DatabaseObject invitation)
            {
                Console.WriteLine("UserJoined. Loaded invitation: " + invitation);
                if (invitation != null)
                {
                    Console.WriteLine("Blocking? " + (player.JoinData["block"] == "true"));
                    if (player.JoinData["block"] == "true")
                    {
                        var email = invitation.GetString("recipientEmail");
                        this.PlayerIO.BigDB.LoadSingle("Ignores", "ignore", new[] { email },
                                                       delegate(DatabaseObject ignore)
                        {
                            var create = ignore == null;
                            if (create)
                            {
                                ignore = new DatabaseObject();
                            }

                            ignore.Set("ignoreEmail", email);
                            ignore.Set("ignoreAll", true);

                            if (create)
                            {
                                this.PlayerIO.BigDB.CreateObject("Ignores", null, ignore,
                                                                 delegate { player.Disconnect(); });
                            }
                            else
                            {
                                ignore.Save(delegate { player.Disconnect(); });
                            }
                        });
                    }
                }
            });
        }
示例#8
0
        public ArchiveEntryTabPage(DatabaseObject table, TableDependencyGraph dependencies)
        {
            InitializeComponent();

            filterConditionsPanel.LoadColumns(table);

            ISet <DependencyNode> dependentTables = dependencies.GetAncestors(table);

            dependentTables.Add(dependencies[table]);
            tableLayoutPanelTablesnames.SuspendLayout();
            int columnOffset = 0;

            foreach (DependencyNode dependentTable in dependentTables)
            {
                int   row            = tableLayoutPanelTablesnames.RowCount;
                Label labelTablename = NewLabelTablename();
                labelTablename.Text = dependentTable.DbObject.NameWithSchema;
                tableLayoutPanelTablesnames.Controls.Add(labelTablename, 0 + columnOffset, row);
                TextBox textBoxTableName = NewTextBoxTablename();
                textBoxTableName.Text = dependentTable.DbObject.NameWithSchema;
                tableLayoutPanelTablesnames.Controls.Add(textBoxTableName, 1 + columnOffset, row);
                if (columnOffset > 0)
                {
                    tableLayoutPanelTablesnames.RowStyles.Add(new RowStyle());
                    tableLayoutPanelTablesnames.RowCount = row + 1;
                    columnOffset = 0;
                }
                else
                {
                    columnOffset += 2;
                }
            }
            tableLayoutPanelTablesnames.ResumeLayout(false);
            tableLayoutPanelTablesnames.PerformLayout();

            Dock = DockStyle.Fill;
        }
        protected override void LoadChildren()
        {
            var auditRepository  = new AuditLogRepository();
            var unclaimedChanges =
                auditRepository.GetObjectsWithUnclimainedChangesByDatabaseAndType(_categoryItem.DatabaseName, _categoryItem.Type, DateTime.Today.AddMonths(-3), null);
            //ToDo: Not consistent with other viewmodel patterns. Store this in private variable field.
            //ToDo: Not consistent with other viewmodel patterns. Store this in private variable field.
            var utility = new UtilityRepository();

            foreach (var child in _repository.GetObjectBasicInformationFromDatabaseAndType(_categoryItem.DatabaseName, _categoryItem.Type))
            {
                var item   = new DatabaseObjectItem(child.ObjectName, child.ObjectSchema, child.DatabaseName, _categoryItem.Type);
                var dbItem = new DatabaseObject
                {
                    DatabaseName = child.DatabaseName,
                    ObjectSchema = child.ObjectSchema,
                    ObjectName   = child.ObjectName,
                    TypeCode     = _categoryItem.Type
                };

                item.HasPendingCheckin = !dbItem.IsUpToDate;

                if (unclaimedChanges.Any(u => u.ObjectInformation.DatabaseName == _categoryItem.DatabaseName &&
                                         u.ObjectInformation.ObjectSchema == child.ObjectSchema && u.ObjectInformation.ObjectName == child.ObjectName))
                {
                    item.HasUnclaimedChanges = true;
                }
                if (_filter == DatabaseCategoryItemFilter.All ||
                    (_filter == DatabaseCategoryItemFilter.OnlyPendingCheckins && item.HasPendingCheckin) ||
                    (_filter == DatabaseCategoryItemFilter.OnlyUnclaimedChanges && item.HasUnclaimedChanges) ||
                    (_filter == DatabaseCategoryItemFilter.OnlyPendingOrUnclaimedChanges && (item.HasPendingCheckin || item.HasUnclaimedChanges))
                    )
                {
                    Children.Add(new DatabaseObjectItemViewModel(item, this));
                }
            }
        }
        public virtual Script Add(DatabaseObject dbObject)
        {
            if (dbObject is TableColumn column)
            {
                return(this.AddTableColumn(new Table()
                {
                    Owner = column.Owner, Name = column.TableName
                }, column));
            }
            else if (dbObject is TablePrimaryKey primaryKey)
            {
                return(this.AddPrimaryKey(primaryKey));
            }
            else if (dbObject is TableForeignKey foreignKey)
            {
                return(this.AddForeignKey(foreignKey));
            }
            else if (dbObject is TableIndex index)
            {
                return(this.AddIndex(index));
            }
            else if (dbObject is TableConstraint constraint)
            {
                return(this.AddCheckConstraint(constraint));
            }
            else if (dbObject is UserDefinedType userDefinedType)
            {
                return(this.AddUserDefinedType(userDefinedType));
            }
            else if (dbObject is ScriptDbObject scriptDbObject)
            {
                return(new CreateDbObjectScript <ScriptDbObject>(scriptDbObject.Definition));
            }

            throw new NotSupportedException($"Not support to add {dbObject.GetType().Name} using this method.");
        }
示例#11
0
        public void EventsArgsBufferedTest()
        {
            using (var temp = TempDirectory.Create())
            {
                ItemCollectionChangedEventArgs <DatabaseObject> itemColArgs    = null;
                ItemUpdatedEventArgs <DatabaseObject>           itemUpdateArgs = null;
                var col = new ItemCollection <DatabaseObject>(temp.TempPath);
                col.ItemUpdated           += (e, args) => itemUpdateArgs = args;
                col.ItemCollectionChanged += (e, args) => itemColArgs = args;
                var item = new DatabaseObject();

                col.BeginBufferUpdate();
                col.Add(item);
                col.Update(item);
                col.Remove(item);
                Assert.IsNull(itemColArgs);
                Assert.IsNull(itemUpdateArgs);

                col.EndBufferUpdate();
                Assert.AreEqual(1, itemColArgs.AddedItems.Count);
                Assert.AreEqual(1, itemColArgs.RemovedItems.Count);
                Assert.AreEqual(1, itemUpdateArgs.UpdatedItems.Count);
            }
        }
示例#12
0
        private void createPreviewObjects()
        {
            Console.WriteLine("Objects of same type were deleted.");
            int currentObjectSize = 0;
            int currentPartID = 1;
            var currentObject = new DatabaseObject();
            var currentFramesSet = new DatabaseArray();

            foreach (byte[] arr in outGoingSnapshots)
            {
                Console.WriteLine("Obj size: " + arr.Length);
                currentObjectSize += arr.Length;
                currentFramesSet.Add(arr);

                if (currentObjectSize > 400000)
                    //start new preview part if currentObject size is > 400kb (Playerio obj limmit size is 500kb)
                {
                    fillObject(currentObject, currentFramesSet);
                    gamelink.PlayerIO.BigDB.CreateObject("Previews", spellName + "_part_" + currentPartID, currentObject,
                        onObjCreated);
                    currentObject = new DatabaseObject();
                    currentFramesSet = new DatabaseArray();
                    currentPartID++;
                    currentObjectSize = 0;
                }
            }

            if (currentFramesSet.Count > 0) //create last object
            {
                fillObject(currentObject, currentFramesSet);
                gamelink.PlayerIO.BigDB.CreateObject("Previews", spellName + "_part_" + currentPartID, currentObject,
                    onObjCreated);
            }

            Console.WriteLine("Will write obhects with total size: " + outGoingSnapshots);
        }
示例#13
0
        internal override void DropObject(DatabaseObject obj)
        {
            throw new NotImplementedException();

            /*
             * if (!IsMutable)
             * {
             *  throw new InvalidOperationException();
             * }
             *
             * var sql = String.Format(
             *  "DROP {0} {1}",
             *  Constants.PostgreSqlObjectTypeNames[obj.ObjectType],
             *  obj.GetFullyResolvedName());
             *
             * using (var cn = OpenConnection())
             * {
             *  using (var cmd = new NpgsqlCommand(sql, cn))
             *  {
             *      cmd.ExecuteNonQuery();
             *  }
             * }
             * */
        }
示例#14
0
        public SerializedDBO(DatabaseObject dbo)
        {
            this.Data = new Dictionary <string, object>();

            if (dbo == null)
            {
                return;
            }

            this.Table = dbo.Table;
            this.Key   = dbo.Key;

            foreach (var i in dbo)
            {
                try {
                    if (dbo.TryGetValue(i.Key, out var v))
                    {
                        if (v is DatabaseObject)
                        {
                            this.Data[i.Key] = new SerializedDBO((DatabaseObject)v).Data;                             //we only need the data portion of it - we don't need the Table KEy e.t.c features of it
                        }
                        else if (v is DatabaseArray)
                        {
                            this.Data[i.Key] = new SerializedDBA((DatabaseArray)v).Data;
                        }
                        else
                        {
                            this.Data[i.Key] = v;
                        }
                    }
                } catch (Exception e) {
                    // this is only because "fb100002099717266" has "crap0" that PlayerIOClient can't handle and throws a NullReferenceException on.
                    Console.WriteLine($"Error while serializing {i.Key} for {dbo.Key}: {e.Message}");
                }
            }
        }
示例#15
0
    // adding panels
    public void addPanel(DatabaseObject databaseObject)                         // FIX UP POSITIONING!!!!!
    {
        if (databaseObject == null || panelContains(databaseObject))
        {
            return;
        }
        Panel newPanel;

        switch (databaseObject.getTypeID())
        {
        case DatabaseObject.DEPARTMENT:
            newPanel = Instantiate(panelPrefabs[DatabaseObject.DEPARTMENT], transform.position, Quaternion.identity) as Panel;
            break;

        case DatabaseObject.DIVISION:
            newPanel = Instantiate(panelPrefabs[DatabaseObject.DIVISION], transform.position, Quaternion.identity) as Panel;
            break;

        case DatabaseObject.ROLE:
            newPanel = Instantiate(panelPrefabs[DatabaseObject.ROLE], transform.position, Quaternion.identity) as Panel;
            break;

        case DatabaseObject.EMPLOYEE:
            newPanel = Instantiate(panelPrefabs[DatabaseObject.EMPLOYEE], transform.position, Quaternion.identity) as Panel;
            break;

        case DatabaseObject.MEDIAGALLERY:
            newPanel = Instantiate(panelPrefabs[DatabaseObject.MEDIAGALLERY], transform.position, Quaternion.identity) as Panel;
            break;

        default:
            return;
        }
        newPanel.setup(this, databaseObject);
        panels.Add(newPanel);
    }
示例#16
0
        private void RestoreCoins(DatabaseObject dbo, bool isBlue)
        {
            var count = dbo.GetInt("Count");

            if (isBlue)
            {
                player.BlueCoins = count;
            }
            else
            {
                player.Coins = count;
            }

            var xs = dbo.GetBytes("PosX");
            var ys = dbo.GetBytes("PosY");

            for (var i = 0; i < xs.Length; i += 2)
            {
                var x = (uint)((xs[i] << 8) + xs[i + 1]);
                var y = (uint)((ys[i] << 8) + ys[i + 1]);

                this.player.Coinmap.Add(new Item(new ForegroundBlock((uint)(isBlue ? 101 : 100)), x, y));
            }
        }
示例#17
0
        private string getCreateScript()
        {
            var sb = new StringBuilder();

            sb.AppendLine(TargetDatabase.DataSource.GetPreTableCreateScript(DatabaseObject));
            var tbl = TargetDatabase.DataSource.GetConvertedObjectName(DatabaseObject.TableName);

            sb.AppendLineFormat("CREATE TABLE {0}(", DatabaseObject.GetObjectNameWithSchema(TargetDatabase.DataSource));

            sb.AppendLine(getColumnCreates().ToString());

            foreach (var kc in DatabaseObject.KeyConstraints)
            {
                var script = TargetDatabase.DataSource.GetKeyConstraintCreateScript(kc);
                if (!string.IsNullOrEmpty(script))
                {
                    sb.AppendLine(", " + TargetDatabase.DataSource.GetKeyConstraintCreateScript(kc));
                }
            }
            sb.AppendLine(");");


            return(sb.ToString());
        }
示例#18
0
 private void RecordStorageEntitySetsAndProperties(StorageEntityContainer sec)
 {
     foreach (var es in sec.EntitySets())
     {
         var ses = es as StorageEntitySet;
         if (null != ses)
         {
             var dbObj = DatabaseObject.CreateFromEntitySet(ses);
             _allTablesAndViews.Add(dbObj, ses.LocalName.Value);
             var et = ses.EntityType.Target;
             if (null == et)
             {
                 Debug.Fail("Null EntityType");
             }
             else
             {
                 foreach (var prop in et.Properties())
                 {
                     AddDbObjToColumnMapping(dbObj, prop);
                 }
             }
         }
     }
 }
示例#19
0
        public void fromDatabaseObject(DatabaseObject dbo)
        {
            this.dbo    = dbo;
            this.width  = dbo.GetInt("width", 200);
            this.height = dbo.GetInt("height", 200);
            this.data   = new Brick[this.height, this.width];
            this.dataBg = new Brick[this.height, this.width];
            var worlddata = dbo.GetArray("worlddata");

            this.reset();
            if (worlddata != null)
            {
                this.unserializeFromComplexObject(worlddata);
            }
            else
            {
                var worldbytes = dbo.GetBytes("world", null);
                if (worldbytes != null)
                {
                    this.unserializeWorldFromBytes(worldbytes);
                }
            }
            this.refresh();
        }
示例#20
0
        public void Reload(Callback callback = null)
        {
            if (!this.isReloading)
            {
                this.isReloading = true;
                this.client.BigDB.LoadOrCreate(POTION_STATUS_TABLE, this.key, delegate(DatabaseObject latest)
                {
                    // Add the potions used in this world to the latest potionstatus object
                    var currentpotions = this.getPotions();
                    for (var i = 0; i < currentpotions.Count; i++)
                    {
                        this.addPotion(currentpotions[i], delegate { }, latest);
                    }

                    this.status = latest;

                    this.isReloading = false;
                    if (callback != null)
                    {
                        callback.Invoke();
                    }
                });
            }
        }
示例#21
0
        /// <summary>
        /// Loads indexes of a database object.
        /// </summary>
        /// <param name="databaseObject"></param>
        /// <returns></returns>
        internal override IEnumerable <KeyValuePair <string, Index> > LoadIndexes(DatabaseObject databaseObject)
        {
            var sql = @"
SELECT i.index_id, i.name, i.type, i.is_unique, i.is_primary_key
FROM sys.indexes i
INNER JOIN sys.objects o ON o.object_id = i.object_id
INNER JOIN sys.schemas s ON s.schema_id = o.schema_id
WHERE i.type IN (1, 2) AND
s.name = @schemaName AND o.name = @objectName";

            using (var cn = OpenConnection())
            {
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.Add("@schemaName", SqlDbType.NVarChar, 128).Value = String.IsNullOrWhiteSpace(databaseObject.SchemaName) ? (object)DBNull.Value : (object)databaseObject.SchemaName;
                    cmd.Parameters.Add("@objectName", SqlDbType.NVarChar, 128).Value = databaseObject.ObjectName;

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var idx = new Index((TableOrView)databaseObject)
                            {
                                IndexId      = dr.GetInt32(0),
                                IndexName    = dr.GetString(1),
                                IsClustered  = (dr.GetByte(2) == 1),
                                IsUnique     = dr.GetBoolean(3),
                                IsPrimaryKey = dr.GetBoolean(4),
                            };

                            yield return(new KeyValuePair <string, Index>(idx.IndexName, idx));
                        }
                    }
                }
            }
        }
示例#22
0
        public override int ExecuteCommand()
        {
            // Find the object database
            DatabaseObject obj = Database.GetObject(Database.ResolveReference(Arguments[0]));

            if (obj == null)
            {
                Console.WriteError("No such object: {0}", Arguments[0]);
            }
            else
            {
                if (Type)
                {
                    Console.WriteLine(obj.Type.ToString().ToLowerInvariant());
                }
                else if (Size)
                {
                    Console.WriteLine(obj.Content.Length);
                }
                else if (Content)
                {
                    if (!String.IsNullOrEmpty(Output))
                    {
                        File.WriteAllBytes(Output, obj.Content);
                    }
                    else
                    {
                        using (StreamReader reader = new StreamReader(new MemoryStream(obj.Content)))
                        {
                            Console.WriteLine(reader.ReadToEnd().Trim());
                        }
                    }
                }
            }
            return(0);
        }
示例#23
0
        protected override void FinalValidation(LetterTable table, DatabaseObject db)
        {
            // Fields 'BaseLetter' and 'Symbol' are validated with a final validation step, since they are based on this same table
            // Also, Combination letters are validated with their BaseLetter and Symbol.
            foreach (var data in table.GetValuesTyped())
            {
                if (data.Kind == LetterDataKind.DiacriticCombo)
                {
                    if (data.BaseLetter == "")
                    {
                        LogValidation(data, "LetterData with id  " + data.Id + " is a Combination but does not have a BaseLetter.");
                    }

                    if (data.Symbol == "")
                    {
                        LogValidation(data, "LetterData with id  " + data.Id + " is a Combination but does not have a Symbol.");
                    }

                    if ((data.Id != data.BaseLetter + "_" + data.Symbol) && (data.Id != "alef_hamza_hi" && data.Id != "alef_hamza_low"))
                    {
                        // alef_hamza_hi and alef_hamza_low are the only exceptions in the name format on Combinations
                        LogValidation(data, "LetterData with id  " + data.Id + " is a Combination, but the BaseLetter and Symbol do not match the Id.");
                    }
                }

                if (data.BaseLetter != "" && table.GetValue(data.BaseLetter) == null)
                {
                    LogValidation(data, "Cannot find id of LetterData for BaseLetter value " + data.BaseLetter + " (found in letter " + data.Id + ")");
                }

                if (data.Symbol != "" && table.GetValue(data.Symbol) == null)
                {
                    LogValidation(data, "Cannot find id of LetterData for Symbol value " + data.Symbol + " (found in letter " + data.Id + ")");
                }
            }
        }
        public override List <SynchronizationItem> GetDropItems(DatabaseObjectBase sourceParent)
        {
            var script = TargetDatabase.DataSource.GetForeignKeyDropScript(DatabaseObject);

            return(getStandardDropItems(string.Format(script,
                                                      DatabaseObject.ChildTable.GetObjectNameWithSchema(TargetDatabase.DataSource), DatabaseObject.GetQueryObjectName(TargetDatabase.DataSource)),
                                        sourceParent));
        }
示例#25
0
        override protected LocalizationData CreateData(Dictionary <string, object> dict, DatabaseObject db,
                                                       LanguageCode language) // TODO: Deprecate "language"
        {
            var data = new LocalizationData();

            data.Id       = ToString(dict["Id"]);
            data.AudioKey = ToString(dict["audio_key"]);

            data._LocalizedDatas = new LocalizedData[Enum.GetNames(typeof(LanguageCode)).Length];

            foreach (LanguageCode lang in Enum.GetValues(typeof(LanguageCode)))
            {
                if (lang == LanguageCode.COUNT || lang == LanguageCode.NONE || lang == LanguageCode.arabic_legacy)
                {
                    continue;
                }
                var langData = new LocalizedData();
                Debug.Log(lang);
                langData.Text = ToString(dict[lang.ToString().ToLower()]);
                if (dict.ContainsKey(lang.ToString().ToLower() + "_F"))
                {
                    langData.TextF = ToString(dict[lang.ToString().ToLower() + "_F"]);
                }
                data._LocalizedDatas[(int)lang - 1] = langData;
            }

            //var engData = new LocalizedData();
            //engData.Text = ToString(dict["english"]);

            //var spanishData = new LocalizedData();
            //spanishData.Text = ToString(dict["spanish"]);

            //var arabicData = new LocalizedData();
            //arabicData.Text = ToString(dict["arabic"]);
            //arabicData.TextF = ToString(dict["arabic_F"]);

            //var itaData = new LocalizedData();
            //itaData.Text = ToString(dict["italian"]);

            //data._LocalizedDatas = new[] { engData, arabicData, spanishData, itaData };
            return(data);
        }
示例#26
0
        private void buttonArchive_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            ArchiveEntryTabPage          tabPage             = (ArchiveEntryTabPage)tabControlTables.SelectedTab.Controls[0];
            IDictionary <string, string> convertorTableNames = new Dictionary <string, string>(tabPage.tableLayoutPanelTablesnames.RowCount * 2);
            bool tableNamesChanged = false;

            for (int i = 0; i <= tabPage.tableLayoutPanelTablesnames.RowCount; i++)
            {
                for (int j = 0; j < tabPage.tableLayoutPanelTablesnames.ColumnCount; j += 2)
                {
                    if (tabPage.tableLayoutPanelTablesnames.GetControlFromPosition(j, i) != null)
                    {
                        string text = tabPage.tableLayoutPanelTablesnames.GetControlFromPosition(j + 1, i).Text;
                        if (text.Trim().Length == 0)
                        {
                            MessageBox.Show(this, $"New tablename of tablename {tabPage.tableLayoutPanelTablesnames.GetControlFromPosition(j, i).Text} cannot be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (!tableNamesChanged && tabPage.tableLayoutPanelTablesnames.GetControlFromPosition(j, i).Text != text)
                        {
                            tableNamesChanged = true;
                        }
                        convertorTableNames.Add(tabPage.tableLayoutPanelTablesnames.GetControlFromPosition(j, i).Text.Replace("[", "").Replace("]", "").ToLower(), text);
                    }
                }
            }
            if (!tableNamesChanged && checkBoxInsertWithSelect.Checked)
            {
                MessageBox.Show(this, $"You have checked \"{checkBoxInsertWithSelect.Text}\", but you do not change any tablename. You cannot Select for Insert from same table. Please rename table or uncheck option {checkBoxInsertWithSelect.Checked}.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DatabaseObject tableToArchive = _tablesLimit.First(t => t.NameWithSchema == tabControlTables.SelectedTab.Text);

            Cursor.Current = Cursors.Default;
            Stream       fileStream   = null;
            StreamWriter streamWriter = null;
            string       filename     = "";
            bool         deleteFile   = false;

            try
            {
                if (checkBoxOnlySave.Checked && saveSQLFileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    fileStream = saveSQLFileDialog.OpenFile();
                    filename   = saveSQLFileDialog.FileName;
                }
                else
                {
                    fileStream = Optimizer.GetTempFileStreamWriter(out filename);
                    deleteFile = true;
                }
                streamWriter   = new StreamWriter(fileStream, Encoding.UTF8);
                Cursor.Current = Cursors.WaitCursor;
                if (!Optimizer.Instance.ArchiveTable(tableToArchive, convertorTableNames, checkBoxCreateTable.Checked, tabPage.Conditions, checkBoxInsertWithSelect.Checked, checkBoxSaveAllEntries.Checked, streamWriter))
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show(this, "No data to archiving", "Archive status", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (checkBoxOnlySave.Checked)
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show(this, "Archived entries were saved.", "Archiving completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBoxWithTextBox messageBox = new MessageBoxWithTextBox(this, "Archive:", "Archiving is ready", "Execute");
                    using (StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8))
                    {
                        fileStream.Seek(0, SeekOrigin.Begin);
                        messageBox.richTextBoxText.Text = streamReader.ReadToEnd();
                        streamWriter = null;
                        fileStream   = null;
                    }
                    Cursor.Current = Cursors.Default;
                    //To option repair query in case of error and execute it again
                    while (true)
                    {
                        if (messageBox.ShowDialog(this) == DialogResult.Yes)
                        {
                            Cursor.Current = Cursors.WaitCursor;
                            try
                            {
                                Database.Instance.ExecuteNonResultQuery(messageBox.richTextBoxText.Text);
                                Cursor.Current = Cursors.Default;
                                MessageBox.Show(this, "Archiving was executed.", "Archiving completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                break;
                            }
                            catch (SqlException exc)
                            {
                                Debug.WriteLine(exc);
                                Cursor.Current = Cursors.Default;
                                MessageBox.Show(this, "Error occured during executing query: " + exc.Message, "Query failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    messageBox.Dispose();
                }
            }
            catch (DatabaseException exc)
            {
                Debug.WriteLine(exc);
                MessageBox.Show(this, $"Error while getting data - {exc.InnerException.Message}", "Cannot get data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            catch (IOException exc)
            {
                Debug.WriteLine(exc);
                MessageBox.Show(this, $"Error with data file - {exc.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            catch (OutOfMemoryException exc)
            {
                Debug.WriteLine(exc);
                MessageBox.Show(this, $"Program is out of memory - processed data are saved at file {filename}", "Fatal error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                deleteFile = false;
                Process.Start("explorer.exe", $"/select, {filename}");
                return;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                if (streamWriter != null)
                {
                    streamWriter.Dispose();
                    fileStream = null;
                }
                fileStream?.Dispose();
                if (deleteFile)
                {
                    File.Delete(filename);
                }
            }
        }
示例#27
0
 public void RecreateDatabase()
 {
     CreateDatabaseAsset.CreateAssets("Assets/Resources/" + DatabaseManager.STATIC_DATABASE_NAME + "/", DatabaseManager.STATIC_DATABASE_NAME);
     this._databaseObject = DatabaseObject.LoadDB(DatabaseManager.STATIC_DATABASE_NAME);
 }
        private void AddDbObjToColumnMapping(DatabaseObject key, Property prop)
        {
            var propName = prop.LocalName.Value;
            if (null == propName)
            {
                Debug.Fail("Null property name in AddDbObjToColumnMapping");
                return;
            }

            HashSet<string> columnsHashSet = null;
            _databaseObjectColumns.TryGetValue(key, out columnsHashSet);
            if (null == columnsHashSet)
            {
                columnsHashSet = _databaseObjectColumns[key] = new HashSet<string>();
            }

            columnsHashSet.Add(propName);
        }
        internal ConceptualEntityType FindClosestAncestorTypeThatMapsToDbObject(ConceptualEntityType et, DatabaseObject dbObj)
        {
            Debug.Assert(
                null != _cEntityTypeNameToEntityTypeIdentity, "requires that _cEntityTypeToEntityTypeIdentity " +
                                                              "is initialized for GetEntityTypeIdentityForEntityType call");

            if (null == et)
            {
                Debug.Fail("Null EntityType");
                return null;
            }

            var baseType = et;
            while ((baseType = baseType.BaseType.Target) != null)
            {
                var baseTypeId =
                    GetEntityTypeIdentityForEntityType(baseType);
                if (null != baseTypeId)
                {
                    foreach (var baseTypeTableOrView in baseTypeId.TablesAndViews)
                    {
                        if (dbObj.Equals(baseTypeTableOrView))
                        {
                            return baseType;
                        }
                    }
                }
            }

            return null;
        }
示例#30
0
 void CreateLevel()
 {
     DatabaseObject DO = new DatabaseObject();
     DO.Set("attempts",0);
     DO.Set("creator",username);
     DO.Set("fail",0);
     DO.Set("pass",0);
     DO.Set("leveldata","222222222");
     client.BigDB.CreateObject("CustomLevels","creator2",DO,OnCreateLevelData,FailCreateLevelData);
 }
 internal HashSet<Property> GetPropertiesForDatabaseObject(DatabaseObject dbObj)
 {
     HashSet<Property> results;
     _databaseObjectColumns.TryGetValue(dbObj, out results);
     return results;
 }
 /// --------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new DatabaseObjects with it's associated parent object.
 /// The Parent property can be used to access the parent variable passed into this constructor.
 /// </summary>
 ///
 /// <param name="objParent">
 /// The parent object that this collection is associated with.
 /// </param>
 /// --------------------------------------------------------------------------------
 protected DatabaseObjectsUsingAttributes(DatabaseObject objParent)
     : base(objParent)
 {
 }
        public static void EnsureSchemaAndLeafNode(
            TreeNode rootNode,
            DatabaseObject dbObj,
            TreeViewImage leafNodeImage,
            EntityStoreSchemaFilterEntry leafNodeTagObject)
        {
            Debug.Assert(rootNode != null, "rootNode must be non-null");
            if (rootNode == null)
            {
                return;
            }
            // find or create schema node
            var schemaName = (dbObj.Schema ?? Resources.SelectTablesPage_NullSchemaDisplayName);
            var schemaNode = FindOrCreateTreeSchemaNode(rootNode, schemaName, TreeViewImage.DbDatabaseSchemaImage);

            Debug.Assert(schemaNode != null, "null schemaNode for rootNode with label " + rootNode.Name + ", schemaName " + schemaName);
            if (schemaNode != null)
            {
                // now add child node to schema node
                var detailNode = CreateTreeNode(dbObj.Name, false, leafNodeTagObject, dbObj.Name, leafNodeImage, null);
                schemaNode.Nodes.Add(detailNode);
            }
        }
示例#34
0
 void OnSearchByName(DatabaseObject[] _databaseObject)
 {
     /*
     foreach (DatabaseObject DO in _databaseObject)
         Debug.Log(DO);
     */
 }
        private void AddDbObjToPropertiesMapping(DatabaseObject key, Property prop)
        {
            HashSet<Property> propsSet = null;
            _databaseObjectColumns.TryGetValue(key, out propsSet);
            if (null == propsSet)
            {
                propsSet = _databaseObjectColumns[key] = new HashSet<Property>();
            }

            propsSet.Add(prop);
        }
        private void AddCEntityTypeToEntityTypeIdentityMapping(
            EntityType key, DatabaseObject dbObj)
        {
            EntityTypeIdentity etId = null;
            _cEntityTypeToEntityTypeIdentity.TryGetValue(key, out etId);
            if (null == etId)
            {
                etId = _cEntityTypeToEntityTypeIdentity[key] = new EntityTypeIdentity();
            }

            etId.AddTableOrView(dbObj);
        }
示例#37
0
        protected void searchButton_Click(object sender, EventArgs e)
        {
            patientFirstNameRegularExpressionValidator.Enabled = false;
            patientLastNameRegularExpressionValidator.Enabled  = false;
            patientIdRegularExpressionValidator.Enabled        = false;
            patientFirstNameValidatorLabel.Visible             = false;
            patientLastNameValidatorLabel.Visible = false;
            patientIdValidatorLabel.Visible       = false;
            noPatientLabel.Visible = false;
            patientPhoneNumberRegularExpressionValidator.Enabled = false;
            DataSet result = null;

            if (patientIdRadioButton.Checked == true)
            {
                DatabaseObject obj = new DatabaseObject();

                ViewPatientHistoryBLL objViewPatientHistoryBLL = new ViewPatientHistoryBLL();

                try
                {
                    patientIdRegularExpressionValidator.Enabled = true;

                    result = objViewPatientHistoryBLL.ViewPatientHistoryBy(int.Parse(patientIdTextBox.Text));

                    //DetailsView.DataSource = result;

                    resultGridView.DataSource = result;

                    resultGridView.Visible = true;
                    patientFirstNameRegularExpressionValidator.Enabled = false;
                    patientLastNameRegularExpressionValidator.Enabled  = false;
                    if (result.Tables[0].Select().Length == 0 && patientIdTextBox.Text != string.Empty)
                    {
                        noPatientLabel.Visible = true;
                    }
                }
                catch
                {
                    if (patientIdTextBox.Text == string.Empty)
                    {
                        patientIdValidatorLabel.Visible = true;
                    }
                }
                resultGridView.DataBind();
                //DetailsView.Visible = true;
            }
            else if (patientNameRadioButton.Checked == true)
            {
                patientFirstNameRegularExpressionValidator.Enabled = true;
                patientLastNameRegularExpressionValidator.Enabled  = true;
                patientIdRegularExpressionValidator.Enabled        = false;
                DatabaseObject obj = new DatabaseObject();

                ViewPatientHistoryBLL objViewPatientHistoryByName = new ViewPatientHistoryBLL();
                if (patientFirstNameTextBox.Text == string.Empty)
                {
                    patientFirstNameValidatorLabel.Visible = true;
                    if (patientFirstNameTextBox.Text != string.Empty)
                    {
                        patientFirstNameValidatorLabel.Visible = false;
                    }
                }
                if (patientLastNameTextBox.Text == string.Empty)
                {
                    patientLastNameValidatorLabel.Visible = true;
                    if (patientLastNameTextBox.Text != string.Empty)
                    {
                        patientLastNameValidatorLabel.Visible = false;
                    }
                }

                result = objViewPatientHistoryByName.ViewPatientHistoryByName(patientFirstNameTextBox.Text, patientLastNameTextBox.Text);

                //DetailsView.DataSource = result;

                resultGridView.DataSource = result;

                resultGridView.Visible = true;

                if (result.Tables[0].Select().Length == 0 && patientFirstNameTextBox.Text != string.Empty && patientLastNameTextBox.Text != string.Empty)
                {
                    noPatientLabel.Visible = true;
                }
                resultGridView.DataBind();
            }
            else if (patientPhoneNumberRadioButton.Checked == true)
            {
                DatabaseObject obj = new DatabaseObject();
                obj.CommandToExecute                               = new SqlCommand(@"uspViewPatientHistoryByPatientPhoneNumber", obj.DatabaseConnection);
                obj.CommandToExecute.CommandType                   = CommandType.StoredProcedure;
                patientIdRegularExpressionValidator.Enabled        = false;
                patientFirstNameRegularExpressionValidator.Enabled = false;
                patientLastNameRegularExpressionValidator.Enabled  = false;
                if (sortByDropDownList.Text == "Select")
                {
                    ViewPatientHistoryBLL objViewPatientHistoryByPhoneNumber = new ViewPatientHistoryBLL();

                    patientPhoneNumberRegularExpressionValidator.Enabled = true;

                    resultGridView.Visible = true;

                    result = objViewPatientHistoryByPhoneNumber.ViewPatientHistoryByPhoneNumber(patientPhoneNumberTextBox.Text);

                    resultGridView.DataSource = result;
                    if (patientPhoneNumberTextBox.Text == string.Empty)
                    {
                        patientPhoneNumberValidatorLabel.Visible = true;
                    }
                    else if (result.Tables[0].Select().Length == 0 && patientPhoneNumberTextBox.Text != string.Empty)
                    {
                        noPatientLabel.Visible = true;
                    }
                    resultGridView.DataBind();
                }
                else if (sortByDropDownList.Text == "First Name")
                {
                    ViewPatientHistoryBLL objViewPatientHistoryByPhoneNumber = new ViewPatientHistoryBLL();

                    patientPhoneNumberRegularExpressionValidator.Enabled = true;

                    resultGridView.Visible = true;

                    result = objViewPatientHistoryByPhoneNumber.ViewPatientHistoryByPhoneNumberSortByFirstName(patientPhoneNumberTextBox.Text);

                    resultGridView.DataSource = result;
                    if (patientPhoneNumberTextBox.Text == string.Empty)
                    {
                        patientPhoneNumberValidatorLabel.Visible = true;
                    }
                    else if (result.Tables[0].Select().Length == 0 && patientPhoneNumberTextBox.Text != string.Empty)
                    {
                        noPatientLabel.Visible = true;
                    }
                    resultGridView.DataBind();
                }
                else if (sortByDropDownList.Text == "Last Name")
                {
                    ViewPatientHistoryBLL objViewPatientHistoryByPhoneNumber = new ViewPatientHistoryBLL();

                    patientPhoneNumberRegularExpressionValidator.Enabled = true;

                    resultGridView.Visible = true;

                    result = objViewPatientHistoryByPhoneNumber.ViewPatientHistoryByPhoneNumberSortByLastName(patientPhoneNumberTextBox.Text);

                    resultGridView.DataSource = result;
                    if (patientPhoneNumberTextBox.Text == string.Empty)
                    {
                        patientPhoneNumberValidatorLabel.Visible = true;
                    }
                    else if (result.Tables[0].Select().Length == 0 && patientPhoneNumberTextBox.Text != string.Empty)
                    {
                        noPatientLabel.Visible = true;
                    }
                    resultGridView.DataBind();
                }
            }
        }
        private void AddCEntityTypeNameToEntityTypeIdentityMapping(
            EntityType key, DatabaseObject dbObj)
        {
            var normalizedName = key.NormalizedName;
            if (normalizedName == null)
            {
                Debug.Fail("null or empty Normalized Name for " + key.ToPrettyString());
                return;
            }

            EntityTypeIdentity etId = null;
            _cEntityTypeNameToEntityTypeIdentity.TryGetValue(normalizedName, out etId);
            if (null == etId)
            {
                etId = _cEntityTypeNameToEntityTypeIdentity[normalizedName] = new EntityTypeIdentity();
            }

            etId.AddTableOrView(dbObj);
        }
示例#39
0
        public void Save(Callback successCallback = null, Callback <PlayerIOError> errorCallback = null)
        {
            if (this.status != null)
            {
                this.status.Set("name", this.Name);
                this.status.Set("currentWorldName", this.CurrentWorldName);
                this.status.Set("currentWorldId", this.CurrentWorldId);
                this.status.Set("smiley", this.Smiley);
                this.status.Set("hasGoldBorder", this.HasGoldBorder);
                this.status.Set("ipAddress", this.IpAddress);
                this.status.Set("lastUpdate", this.LastUpdate);
                this.status.Set("stealth", this.Stealthy);

                this.status.Save(false, true, () =>
                {
                    if (successCallback != null)
                    {
                        successCallback.Invoke();
                    }
                }, error =>
                {
                    if (errorCallback != null)
                    {
                        errorCallback.Invoke(error);
                    }
                });
            }
            else
            {
                this.client.BigDB.LoadOrCreate(OnlineStatusTable, this.key,
                                               delegate(DatabaseObject result)
                {
                    this.status = result;

                    result.Set("name", this.Name);
                    result.Set("currentWorldName", this.CurrentWorldName);
                    result.Set("currentWorldId", this.CurrentWorldId);
                    result.Set("smiley", this.Smiley);
                    result.Set("hasGoldBorder", this.HasGoldBorder);
                    result.Set("ipAddress", this.IpAddress);
                    result.Set("lastUpdate", this.LastUpdate);
                    this.status.Set("stealth", this.Stealthy);

                    result.Save(false, () =>
                    {
                        if (successCallback != null)
                        {
                            successCallback.Invoke();
                        }
                    }, error =>
                    {
                        if (errorCallback != null)
                        {
                            errorCallback.Invoke(error);
                        }
                    });
                }, error =>
                {
                    if (errorCallback != null)
                    {
                        errorCallback.Invoke(error);
                    }
                });
            }
        }
示例#40
0
 void Pallet_AfterWriting(DatabaseObject item)
 {
     if ( !ShipmentDoc.Pallets.IsContain(this.Id, "Pallet") )
         {
         DataRow row = ShipmentDoc.Pallets.GetNewRow(ShipmentDoc);
         ItemFormTuner.SetRowValue(this.Id, row, ShipmentDoc.Pallet, ShipmentDoc);
         row.AddRowToTable(ShipmentDoc);
         ShipmentDoc.Write();
         }
 }
        private void AddTableOrViewToBaseTypeMappings(
            DatabaseObject key, DatabaseObject databaseObjectInAncestor)
        {
            HashSet<DatabaseObject> tablesAndViewsHashSet = null;
            _cAncestorTypeDatabaseObjectMap.TryGetValue(key, out tablesAndViewsHashSet);
            if (null == tablesAndViewsHashSet)
            {
                tablesAndViewsHashSet = _cAncestorTypeDatabaseObjectMap[key] = new HashSet<DatabaseObject>();
            }

            tablesAndViewsHashSet.Add(databaseObjectInAncestor);
        }
示例#42
0
 public PlayerObject(DatabaseObject databaseObject)
 {
     this._databaseObject = databaseObject;
 }
        private void AddDbObjToEntityTypeNameMap(DatabaseObject key, EntityType et)
        {
            var normalizedName = et.NormalizedName;
            if (normalizedName == null)
            {
                Debug.Fail("null or empty Normalized Name for " + et.ToPrettyString());
                return;
            }

            HashSet<Symbol> entityTypeNamesHashSet = null;
            _databaseObjectToCEntityTypeNamesMap.TryGetValue(key, out entityTypeNamesHashSet);
            if (null == entityTypeNamesHashSet)
            {
                entityTypeNamesHashSet = _databaseObjectToCEntityTypeNamesMap[key] = new HashSet<Symbol>();
            }

            entityTypeNamesHashSet.Add(normalizedName);
        }
示例#44
0
 private static void processSpellActivation(Player pl, string spellName)
 {
     var item = new BuyItemInfo(spellName);
     bool needActivationBuffer = pl.roomLink.game != null; //user might be activating not during the game
     if (needActivationBuffer) //user might be activating not during the game
         pl.roomLink.game.spellChecker.putSpellInActivationBuffer(spellName);
             //so it is not blocked from usage while transaction is processed
     pl.PayVault.Buy(false, new BuyItemInfo[1] {item},
         //immediately consume items. Instead PlayerObject is updated (for storage convenience)
         delegate
         {
             Console.WriteLine("PayVault ok...");
             DatabaseObject spells = pl.getSpellsConfig();
             double expiresDate = Utils.unixSecs() + GameConfig.SPELL_ACTIVATION_TIME*60*60;
             var newSpell = new DatabaseObject();
             int prevSlotID = spells.Contains(spellName)
                 ? spells.GetObject(spellName).GetInt(DBProperties.SPELL_SLOT)
                 : -1; //dont lose spell
             newSpell.Set(DBProperties.SPELL_SLOT, prevSlotID);
             newSpell.Set(DBProperties.SPELL_EXPIRES, expiresDate);
             spells.Set(spellName, newSpell);
             pl.PlayerObject.Save();
             pl.sendMessage(MessageTypes.ACTIVATE_SPELL_OK, spellName); //send "ok" back
             pl.roomLink.statisticsManager.onSpellActivated(spellName);
             if (needActivationBuffer) //user might be activating not during the game
                 pl.roomLink.game.spellChecker.removeSpellFromActivationBuffer(spellName);
                     //now checks are made as usual
             foreach (Player play in pl.roomLink.playingUsers)
             {
                 if (!(play is NPCPlayer))
                 {
                     play.sendMessage(MessageTypes.ACTIVATE_SPELL_OPPONENT, pl.realID, spellName);
                 }
             }
         },
         delegate(PlayerIOError err)
         {
             if (needActivationBuffer) //user might be activating not during the game
                 pl.roomLink.game.spellChecker.removeSpellFromActivationBuffer(spellName);
                     //now checks are made as usual
             pl.sendMessage(MessageTypes.PURCHASE_FAILED, "Service error at buying item");
             pl.roomLink.handleError(err);
         });
 }
 internal bool HasAncestorTypeThatMapsToDbObject(ConceptualEntityType et, DatabaseObject dbObj)
 {
     return (FindClosestAncestorTypeThatMapsToDbObject(et, dbObj) == null ? false : true);
 }
示例#46
0
 private CampaignPlayer(DatabaseObject core, DatabaseObject dbo)
 {
     this.dbo            = dbo;
     this.DatabaseObject = core;
 }
        internal EntityType FindRootAncestorTypeThatMapsToDbObject(ConceptualEntityType et, DatabaseObject dbObj)
        {
            ConceptualEntityType rootAncestor = null;
            var nextAncestor = et;
            while ((nextAncestor = FindClosestAncestorTypeThatMapsToDbObject(nextAncestor, dbObj)) != null)
            {
                rootAncestor = nextAncestor;
            }

            return rootAncestor;
        }
示例#48
0
        public void GetSmoObject(DatabaseObject dbObject)
        {
            //if (_server == null)
            //{
            //    _server = new Server();
            //    _server.ConnectionContext.LoginSecure = true;
            //    _server.ConnectionContext.ServerInstance = GetServerNameFromDatabaseName(dbObject.DatabaseName);
            //}

            //if (_database == null)
            //{
            //    //Assume all databases are the same for now....
            //    _database = _server.Databases[dbObject.DatabaseName];
            //}

            //if (_scripter == null)
            //{
            //    _scripter = new Scripter(_server);
            //    _scripter.Options.ScriptDrops = false;
            //    _scripter.Options.ScriptData = false;
            //    _scripter.Options.ScriptSchema = true;
            //    _scripter.Options.WithDependencies = false;
            //    _scripter.Options.DriAllConstraints = false;
            //    _scripter.Options.DriAllKeys = true;
            //    _scripter.Options.DriNonClustered = true;
            //    _scripter.Options.DriUniqueKeys = true;
            //    _scripter.Options.ScriptBatchTerminator = true;
            //    _scripter.Options.NoCommandTerminator = false;
            //    _scripter.Options.Statistics = true;
            //}

            //List<string> script = null;

            //switch (dbObject.TypeCode)
            //{
            //    case DatabaseObjectTypeCode.Table:
            //        if (_database.Tables[dbObject.ObjectName, dbObject.ObjectSchema] != null)
            //        {
            //            script = _scripter.EnumScriptWithList(new[] { _database.Tables[dbObject.ObjectName, dbObject.ObjectSchema].Urn }).ToList();
            //        }
            //        break;
            //    case DatabaseObjectTypeCode.StoredProcedure:
            //        if (_database.StoredProcedures[dbObject.ObjectName, dbObject.ObjectSchema] != null)
            //        {
            //            script = _scripter.EnumScriptWithList(new[] { _database.StoredProcedures[dbObject.ObjectName, dbObject.ObjectSchema].Urn }).ToList();
            //        }
            //        break;
            //    case DatabaseObjectTypeCode.View:
            //        if (_database.Views[dbObject.ObjectName, dbObject.ObjectSchema] != null)
            //        {
            //            script = _scripter.EnumScript(new[] { _database.Views[dbObject.ObjectName, dbObject.ObjectSchema].Urn }).ToList();
            //        }
            //        break;
            //    case DatabaseObjectTypeCode.Function:
            //        if (_database.UserDefinedFunctions[dbObject.ObjectName, dbObject.ObjectSchema] != null)
            //        {
            //            script = _scripter.EnumScript(new[] { _database.UserDefinedFunctions[dbObject.ObjectName, dbObject.ObjectSchema].Urn }).ToList();
            //        }
            //        break;
            //    default:
            //        throw new ArgumentException($"Method GetSmoObject; Invalid category '{dbObject.Category}'");
            //}

            //if (script != null)
            //    dbObject.DbSql = $"{string.Join("\nGO\n", script)}\nGO".Replace(
            //        @"SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO",
            //        @"SET ANSI_NULLS ON\r\nSET QUOTED_IDENTIFIER ON\r\nGO").Replace("\n", "").Replace("SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO",
            //        @"SET ANSI_NULLS ON
            //        SET QUOTED_IDENTIFIER ON
            //        GO
            //        ").Replace("\r\n\r\n", "\r\n");
            throw new NotImplementedException();
        }
示例#49
0
        public ShopItem(DatabaseObject dbo, Sales sales)
        {
            this.Key            = dbo.Key;
            this.PriceGems      = dbo.GetInt("PriceCoins");
            this.PriceEnergy    = dbo.GetInt("PriceEnergy", -1);
            this.EnergyPerClick = dbo.GetInt("EnergyPerClick", 5);
            this.Reusable       = dbo.GetBool("Reusable", false);
            this.MaxPurchases   = dbo.GetInt("MaxPurchases", 0);
            this.BetaOnly       = dbo.GetBool("BetaOnly", false);

            var availableSince = dbo.GetInt("AvailableSince", 0);

            this.IsNew      = dbo.GetBool("IsNew", false) || availableSince == Config.Version;
            this.IsFeatured = dbo.GetBool("IsFeatured", false) || this.IsNew;
            this.Enabled    = dbo.GetBool("Enabled", false) && availableSince <= Config.Version;

            this.IsClassic         = dbo.GetBool("IsClassic", false);
            this.OnSale            = dbo.GetBool("OnSale", false);
            this.Span              = dbo.GetInt("Span", 1);
            this.Header            = dbo.GetString("Header", "");
            this.Body              = dbo.GetString("Body", "");
            this.BitmapSheetId     = dbo.GetString("BitmapSheetId", "");
            this.BitmapSheetOffset = dbo.GetInt("BitmapSheetOffset", 0);
            this.IsPlayerWorldOnly = dbo.GetBool("PWOnly", false);
            this.DevOnly           = dbo.GetBool("DevOnly", false);
            this.IsGridFeatured    = dbo.GetBool("IsGridFeatured", false);
            this.PriceUsd          = dbo.GetInt("PriceUSD", -1);
            this.Label             = dbo.GetString("Label", "");
            this.LabelColor        = dbo.GetString("LabelColor", "#FFAA00");

            if (string.IsNullOrEmpty(this.Header))
            {
                this.Header = this.Key;
            }

            if (this.Key.Contains("smiley"))
            {
                this.Type = "smiley";
            }
            else if (this.Key.Contains("brick"))
            {
                this.Type = "brick";
            }
            else if (this.Key.Contains("world"))
            {
                this.Type = "world";
            }
            else if (this.Key.Contains("aura"))
            {
                this.Type = this.Key.Contains("shape") ? "auraShape" : "auraColor";
            }
            else if (this.Key.Contains("gold"))
            {
                this.Type = "gold";
            }
            else if (this.Key.Contains("crew"))
            {
                this.Type = "crew";
            }
            else if (this.Key == "mixednewyear2010")
            {
                this.Type = "brick";
            }

            if (this.Key == "changeusername" || this.Key == "pro" || this.Key.Contains("gemcode"))
            {
                this.Type = "service";
            }

            // Black Friday
            if (sales.IsBlackFridayItem(this.Key))
            {
                if (this.PriceGems > 0)
                {
                    this.PriceGems = (int)Math.Ceiling((double)this.PriceGems / 2);
                }
                if (this.PriceUsd > 0)
                {
                    this.PriceUsd = (int)Math.Ceiling((double)this.PriceUsd / 2);
                }
                if (this.PriceEnergy > 0)
                {
                    this.PriceEnergy = (int)Math.Ceiling((double)this.PriceEnergy / 2);
                }
                this.EnergyPerClick = sales.FixEnergyPerClick(this.EnergyPerClick, this.PriceEnergy);
                this.Label          = "blackfriday";
            }

            if (!string.IsNullOrEmpty(this.BitmapSheetId))
            {
                return;
            }

            switch (this.Type)
            {
            case "smiley":
                this.BitmapSheetId = "smilies";
                break;

            case "auraColor":
                this.BitmapSheetId = "auraColors";
                break;

            case "auraShape":
                this.BitmapSheetId = "auraShapes";
                break;

            default:
                switch (this.Span)
                {
                case 1:
                    this.BitmapSheetId = "shopitem_131";
                    break;

                case 2:
                    this.BitmapSheetId = "shopitem_227";
                    break;

                case 3:
                    this.BitmapSheetId = "shopitem_323";
                    break;
                }
                break;
            }
        }
示例#50
0
 void Shipment_AfterWriting(DatabaseObject item)
 {
     if ( needWriteToJornal )
         {
         Jornal J = new Jornal();
         J.Date = CreationDate;
         J.Event = Events.ShipmentOpened;
         J.Description = String.Format("Открыта партия №{0}", Number);
         J.Write();
         }
 }
示例#51
0
        public void CopyCurrentDatabaseForTesting()
        {
            this._databaseObject = DatabaseObject.LoadDB(DatabaseManager.STATIC_DATABASE_NAME);

            var test_db = DatabaseObject.LoadDB(DatabaseManager.STATIC_DATABASE_NAME_TEST);

            if (!test_db.HasTables())
            {
                CreateDatabaseAsset.CreateAssets("Assets/Resources/" + DatabaseManager.STATIC_DATABASE_NAME_TEST + "/", DatabaseManager.STATIC_DATABASE_NAME_TEST);
                test_db = DatabaseObject.LoadDB(DatabaseManager.STATIC_DATABASE_NAME_TEST);
            }

            {
                var table = test_db.GetLetterTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetLetterTable().GetValuesTyped());
            }

            {
                var table = test_db.GetWordTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetWordTable().GetValuesTyped());
            }

            {
                var table = test_db.GetPhraseTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetPhraseTable().GetValuesTyped());
            }

            {
                var table = test_db.GetLocalizationTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetLocalizationTable().GetValuesTyped());
            }

            {
                var table = test_db.GetMiniGameTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetMiniGameTable().GetValuesTyped());
            }

            {
                var table = test_db.GetPlaySessionTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetPlaySessionTable().GetValuesTyped());
            }

            {
                var table = test_db.GetLearningBlockTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetLearningBlockTable().GetValuesTyped());
            }

            {
                var table = test_db.GetStageTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetStageTable().GetValuesTyped());
            }

            {
                var table = test_db.GetRewardTable();
                table.Clear();
                table.AddRange(this._databaseObject.GetRewardTable().GetValuesTyped());
            }

            Debug.Log("Database copied");
            AssetDatabase.SaveAssets();
        }
示例#52
0
 void Shipment_BeforeWriting(DatabaseObject item, ref bool cancel)
 {
     if ( IsNew )
         {
         needWriteToJornal = true;
         }
 }
示例#53
0
        public DataManipulation Resolve(ReadOnlySpan <TSQLToken> tokens, ref int fileIndex, CompilerContext context)
        {
            manipulation = new DataManipulation();

            fileIndex++; //skip "merge"

            //skip top expression
            SkipTopExpression(tokens, ref fileIndex, context);

            if (tokens[fileIndex].Text.ToLower().Equals("into"))
            {
                fileIndex++;
            }

            targetObject = StatementResolveHelper.ResolveDatabaseObject(tokens, ref fileIndex, context);

            context.AddDatabaseObjectToCurrentContext(targetObject);

            if (!tokens[fileIndex].Text.ToLower().Equals("using"))
            {
                throw new InvalidSqlException("Trying to resolve a merge-statement without using keyword");
            }

            var source = ResolveUsingStatement(tokens, ref fileIndex, context);

            context.AddDatabaseObjectToCurrentContext(source);

            if (!tokens[fileIndex].Text.Equals("on", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new InvalidSqlException("Expected 'ON' keyword when resolving a 'MERGE'-statement");
            }

            fileIndex++; //skip 'on'

            SearchConditionResolver.Resolve(tokens, ref fileIndex, context);

            while (tokens[fileIndex].Text.Equals("when", StringComparison.InvariantCultureIgnoreCase))
            {
                ResolveWhenExpression(tokens, ref fileIndex, context);
            }

            var beautified = new List <Expression>();

            foreach (var exp in manipulation.Expressions)
            {
                beautified.Add(Beautifier.BeautifyColumns(exp, context));
            }

            manipulation.Expressions = beautified;

            while (!tokens[fileIndex].Text.ToLower().Equals(";"))
            {
                fileIndex++;
                if (fileIndex == tokens.Length)
                {
                    throw new InvalidSqlException("Trying to resolve a merge-statement without proper ';' determination");
                }
            }

            fileIndex++; //skip ';'

            context.CurrentDatabaseObjectContext.Pop();

            return(manipulation);
        }
 internal HashSet<string> GetColumnsForDatabaseObject(DatabaseObject dbObj)
 {
     HashSet<string> results;
     _databaseObjectColumns.TryGetValue(dbObj, out results);
     return results;
 }
示例#55
0
        public void FileUpload(DatabaseObject databaseObject, string backupPath)
        {
            // FTP file location
            string requestUriString = this.FTPFolder + "/" + databaseObject.FolderPath + "/" + databaseObject.FileName + ".gz";

            // kreiramo direktorije i pod-direktorije ukoliko ne postoje
            CreateSubDirectories(databaseObject.FolderPath);

            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(requestUriString);

            ftpRequest.Credentials = new NetworkCredential(this.Username, this.Password);

            // parametri konekcije
            ftpRequest.UseBinary = true;
            ftpRequest.KeepAlive = true;
            ftpRequest.Method    = WebRequestMethods.Ftp.UploadFile;

            FileStream fileStream = File.OpenRead(backupPath + ".gz");
            Stream     ftpStream  = ftpRequest.GetRequestStream();

            // kreiramo konstantu
            //const int BUFFERSIZE = 4096;

            // instanciramo buffer
            byte[] buffer = File.ReadAllBytes(backupPath + ".gz");

            try
            {
                // number of bytes actually read
                ftpStream.Write(buffer, 0, buffer.Length);

                /*
                 * Ovaj dio koda je odjedanput prestao raditi, te je zamjenjen sa retkom prije.
                 * Problem je nastao što je bytesRead konstantno bio na BUFFERSIZE 4096, te se zbog toga vrtila LOOP petlja.
                 * Nisam uspio odgonetnuti gdje je bio problem.
                 * int bytesRead = fileStream.Read(buffer, 0, BUFFERSIZE);
                 *
                 * while (bytesRead != 0)
                 * {
                 *  stream.Write(buffer, 0, bytesRead);
                 *  bytesRead = fileStream.Read(buffer, 0, BUFFERSIZE);
                 * }
                 */
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                if (ftpStream != null)
                {
                    ftpStream.Close();
                }
            }
        }
 internal HashSet<DatabaseObject> GetAncestorTypeTablesAndViews(DatabaseObject tableOrView)
 {
     HashSet<DatabaseObject> results;
     _cAncestorTypeDatabaseObjectMap.TryGetValue(tableOrView, out results);
     return results;
 }
示例#57
0
 public Function(string name, DatabaseObject parent) : base(name, parent)
 {
 }
        // Returns a list of C-side EntityTypes from the current artifact which
        // match the list of EntityType NormalizedNames stored off against the
        // passed in argument tableOrView in this artifact at this 
        // ExistingModelSummary's creation-time
        // (Note: cannot use the actual EntityTypes from the creation-time because 
        // the ReplaceSsdlCommand invokes EFArtifact.ReloadArtifact() which 
        // invalidates them - however the names remain the same and so can be used)
        internal HashSet<ConceptualEntityType> GetConceptualEntityTypesForDatabaseObject(DatabaseObject tableOrView)
        {
            // First try the lazy load map to see if we've already calculated
            // the HashSet for this DatabaseObject
            HashSet<ConceptualEntityType> entityTypesLazyLoad;
            _lazyLoadDatabaseObjectToCEntityTypesMap.TryGetValue(tableOrView, out entityTypesLazyLoad);
            if (null != entityTypesLazyLoad)
            {
                return entityTypesLazyLoad;
            }

            // if not then consult the NormalizedNames map 
            HashSet<Symbol> entityTypeNormalizedNamesForDbObj;
            _databaseObjectToCEntityTypeNamesMap.TryGetValue(tableOrView, out entityTypeNormalizedNamesForDbObj);
            if (null != entityTypeNormalizedNamesForDbObj)
            {
                var artifactSet = Artifact.ArtifactSet;
                var entityTypes = new HashSet<ConceptualEntityType>();
                foreach (var entityTypeName in entityTypeNormalizedNamesForDbObj)
                {
                    var element = artifactSet.LookupSymbol(entityTypeName);
                    if (null == element)
                    {
                        Debug.Fail("no match for symbol " + entityTypeName);
                    }
                    else
                    {
                        var et = element as EntityType;
                        var cet = element as ConceptualEntityType;

                        if (null == cet)
                        {
                            Debug.Assert(
                                et != null, "symbol " + entityTypeName +
                                            " matches non-EntityTypeelement " + element.ToPrettyString());
                            Debug.Assert(et != null ? cet != null : true, "EntityType is not a ConceptualEntityType");
                        }
                        else
                        {
                            entityTypes.Add(cet);
                        }
                    }
                }

                // construct the lazy load map in case we're called again 
                // for the same DatabaseObject
                _lazyLoadDatabaseObjectToCEntityTypesMap.Add(tableOrView, entityTypes);
                return entityTypes;
            }
            else
            {
                return null;
            }
        }
示例#59
0
 public static StaffRoleData[] GetStaffRoles(DatabaseObject obj)
 {
     return(obj.Properties
            .Select(prop => new StaffRoleData(prop, (StaffRole)Enum.Parse(typeof(StaffRole), obj.GetString(prop))))
            .ToArray());
 }
示例#60
0
 void OnSearchLevel(DatabaseObject _databaseObject)
 {
     string leveldata = _databaseObject.GetString("leveldata");
     Debug.Log(leveldata);
 }