コード例 #1
0
ファイル: Utils.cs プロジェクト: wugelis/DDDTaiwan2020.Sample
        /// <summary>
        /// 建立 與 初始化 Create Command Handler for (CQRS)
        /// </summary>
        /// <param name="project"></param>
        /// <param name="currentFolder"></param>
        /// <param name="commandClassName"></param>
        /// <param name="dtoClassName"></param>
        public static void CreateCQRSCreateCommandClassFromSource(Project project, ProjectItem currentFolder, string commandClassName, string dtoClassName)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            SQLStore      store       = new SQLStore();
            StringBuilder sb          = new StringBuilder();
            int           columnOrder = 0;

            string commandHandlerDefined = CreateCommandDef.GetClassTemplate;

            commandHandlerDefined = commandHandlerDefined.Replace("$(NAMESPACE_DEF)$", string.Format("{0}", project.Name));
            commandHandlerDefined = commandHandlerDefined.Replace("$(CREATE_COMMAND_NAME)$", commandClassName);

            ClassDef.GetClassProperties(store.GetNoDataDataTableByName(dtoClassName), new string[] { }, sb, columnOrder);
            commandHandlerDefined = commandHandlerDefined.Replace("$(CLASS_PROPERTIES_DEF)$", sb.ToString());

            string CommandHandlerFileName = $"Create{commandClassName}Command.cs";

            //產生 CQRS Create Command 檔案,並先暫放在 Temp 資料夾下.
            string TempPath = AddFile2ProjectItem(currentFolder, commandHandlerDefined, CommandHandlerFileName);

            //刪除掉暫存檔案
            try
            {
                File.Delete(TempPath);
            }
            catch (Exception ex) { } //刪除暫存檔案若失敗不處理任何訊息.
        }
コード例 #2
0
        public static void HandleQuestPoiQueryResponse(Packet packet)
        {
            var count = packet.ReadInt32("Count");

            for (var i = 0; i < count; i++)
            {
                var questId = packet.ReadEntryWithName <Int32>(StoreNameType.Quest, "Quest ID");

                var counter = packet.ReadInt32("[" + i + "] POI Counter");
                for (var j = 0; j < counter; j++)
                {
                    var idx      = packet.ReadInt32("POI Index", i, j);
                    var objIndex = packet.ReadInt32("Objective Index", i, j);

                    var mapId   = packet.ReadEntryWithName <Int32>(StoreNameType.Map, "Map ID");
                    var wmaId   = packet.ReadInt32("World Map Area", i, j);
                    var floorId = packet.ReadInt32("Floor Id", i, j);
                    var unk2    = packet.ReadInt32("Unk Int32 2", i, j);
                    var unk3    = packet.ReadInt32("Unk Int32 3", i, j);

                    SQLStore.WriteData(SQLStore.QuestPois.GetCommand(questId, idx, objIndex, mapId, wmaId,
                                                                     floorId, unk2, unk3));

                    var pointsSize = packet.ReadInt32("Points counter", i, j);
                    for (var k = 0; k < pointsSize; k++)
                    {
                        var pointX = packet.ReadInt32("Point X", i, j, k);
                        var pointY = packet.ReadInt32("Point Y", i, j, k);
                        SQLStore.WriteData(SQLStore.QuestPoiPoints.GetCommand(questId, idx, objIndex, pointX,
                                                                              pointY));
                    }
                }
            }
        }
コード例 #3
0
        public void TestCreateDeck()
        {
            Controller control = new Controller();
            IStore     store   = new SQLStore();

            control.CreateDeck("Test");
            Assert.AreEqual("Test", control.CurrentDeck.ToString());
            Assert.AreEqual(store.LoadDeck(control.CurrentDeck.ToString()), control.CurrentDeck);
        }
コード例 #4
0
        private void GetAndListColumnsByTable()
        {
            SQLStore  store = new SQLStore();
            DataTable dt    = store.GetNoDataDataTableByName(frmSettings.SelectedTableName);

            lbxColumns.ValueMember   = "ColumnName";
            lbxColumns.DisplayMember = "ColumnName";
            SelectedTableColumns     = dt.Columns.OfType <DataColumn>().AsEnumerable();
            lbxColumns.DataSource    = SelectedTableColumns.ToList();
        }
コード例 #5
0
        public static void FindSQLAndUpdate(string dataStoreName, ReferenceData aRef, string sql, Guid mapId)
        {
            var aSql = aRef.StoreReferences.Where(x => x.DataStoreName.Equals(dataStoreName) && x.GetType().Equals(typeof(SQLStore)) && x.MapID == mapId).FirstOrDefault();

            if (aSql == null)
            {
                SQLStore nSql = new SQLStore();
                nSql.DataStoreName = dataStoreName;
                nSql.SQL           = sql;
                aRef.StoreReferences.Add(nSql);
            }
            else
            {
                ((SQLStore)aSql).SQL = sql;
            }
        }
コード例 #6
0
        private void SQLStoreReadAfterUpdateTest(SQLStore ASQLStore)
        {
            using (SQLStoreConnection LConnection = ASQLStore.Connect())
            {
                List <string> LColumns = new List <string>()
                {
                    "ID", "Name"
                };
                SQLIndex LIndex = new SQLIndex("PK_Test", new[] { new SQLIndexColumn("ID") });

                if (LConnection.HasTable("Test"))
                {
                    LConnection.ExecuteStatement("drop table Test");
                }
                if (!LConnection.HasTable("Test"))
                {
                    LConnection.ExecuteStatement("create table Test ( ID int not null, Name nvarchar(20), constraint PK_Test primary key ( ID ) )");
                }

                LConnection.BeginTransaction(SQLIsolationLevel.ReadCommitted);
                try
                {
                    using (SQLStoreCursor LCursor = LConnection.OpenCursor("Test", LColumns, LIndex, true))
                    {
                        LCursor.Insert(new object[] { 1, "Joe" });
                        LCursor.Insert(new object[] { 2, "Martha" });
                        //LCursor.Insert(new object[] { 3, "Clair" });
                    }
                    LConnection.CommitTransaction();
                }
                catch
                {
                    LConnection.RollbackTransaction();
                    throw;
                }

                LConnection.BeginTransaction(SQLIsolationLevel.ReadCommitted);
                try
                {
                    using (SQLStoreCursor LCursor = LConnection.OpenCursor("Test", LColumns, LIndex, true))
                    {
                        if (!LCursor.Next())
                        {
                            throw new Exception("Expected row");
                        }

                        if ((string)LCursor[1] != "Joe")
                        {
                            throw new Exception("Excepted Joe row");
                        }

                        LCursor[1] = "Joes";
                        LCursor.Update();

                        LCursor.SetRange(null, null);
                        if (!LCursor.Next())
                        {
                            throw new Exception("Expected row");
                        }

                        if ((string)LCursor[1] != "Joes")
                        {
                            throw new Exception(String.Format("Expected Joes row, found '{0}'.", (string)LCursor[1]));
                        }

                        LCursor[1] = "Joe";
                        LCursor.Update();
                    }

                    LConnection.CommitTransaction();
                }
                catch
                {
                    LConnection.RollbackTransaction();
                    throw;
                }
            }
        }
コード例 #7
0
ファイル: Utils.cs プロジェクト: wugelis/DDDTaiwan2020.Sample
        /// <summary>
        /// 產生 Entities 的 Class 定義
        /// </summary>
        /// <param name="project"></param>
        /// <param name="currentFolder"></param>
        /// <param name="entitiesFolder"></param>
        /// <param name="classType">需要產生的類別類型 (DTO 物件/Entity 物件)</param>
        public static void CreateEnitiesFromSourceTables(
            Project project,
            string currentFolder,
            ProjectItem entitiesFolder,
            string classNameOrTableName,
            string commandName,
            bool createKeyAttribute,
            CLASS_TYPE classType)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            string   ClassName       = classNameOrTableName.Replace(" ", "_");
            ClassDef clsDef          = new ClassDef();
            SQLStore store           = new SQLStore();
            string   ClassDefined    = ClassDef.GetClassTemplate;
            string   classEndWord    = classType == CLASS_TYPE.DTO ? "Dto" : "Ent";
            string   usingStatement  = classType == CLASS_TYPE.ENTITY ? $"\nusing {project.Name}.Common;" : "";
            string   commandOrFolder = classType == CLASS_TYPE.ENTITY ? "Entities" : commandName;

            ClassDefined = ClassDefined.Replace("$(USING)$", usingStatement);
            if (string.IsNullOrEmpty(currentFolder))
            {
                ClassDefined = ClassDefined.Replace(".$(FOLDER_NAME)$", currentFolder);
            }
            else
            {
                ClassDefined = ClassDefined.Replace("$(FOLDER_NAME)$", currentFolder);
            }
            ClassDefined = ClassDefined.Replace("$(FOLDER_NAME)$", currentFolder);
            ClassDefined = ClassDefined.Replace("$(NAMESPACE_DEF)$", $"{project.Name}");
            ClassDefined = ClassDefined.Replace("$(QUERY_COMMAND_NAME)$", $"{commandOrFolder}");

            ClassDefined = ClassDefined.Replace(
                "$(CLASS_DEF)$",
                clsDef.GetClassDef(
                    store.GetNoDataDataTableByName(classNameOrTableName),
                    $"{ClassName.ToUpperFirstWord()}{classEndWord}",
                    createKeyAttribute ? store.GetTableKeyByName(string.Format("{0}", ClassName)) : new string[] { },
                    classType));

            //產生等會使用的暫存檔名
            string TempCSPath = Path.Combine(
                Environment.GetEnvironmentVariable("temp"),
                $"{classNameOrTableName.ToUpperFirstWord()}{classEndWord}.cs");

            if (!Directory.Exists(Path.GetDirectoryName(TempCSPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(TempCSPath));
            }
            //建立暫存的 Class 檔案
            CreateModelCSFile(ClassDefined, TempCSPath);
            //加入暫存的 Class 檔案
            entitiesFolder.ProjectItems.AddFromFileCopy(TempCSPath);
            //刪除掉暫存檔案
            try
            {
                File.Delete(TempCSPath);
            }
            catch (Exception ex) { } //刪除暫存檔案若失敗不處理任何訊息.
            //}
        }
コード例 #8
0
ファイル: Utils.cs プロジェクト: wugelis/DDDTaiwan2020.Sample
        /// <summary>
        /// 產生 DbContext 定義
        /// </summary>
        /// <param name="project"></param>
        /// <param name="INTERFACE_FOLDER"></param>
        /// <param name="modelsFolder"></param>
        /// <param name="projectNames"></param>
        public static void CreateDbContextFromSourceTables(
            Project project,
            ProjectItem modelsFolder,
            List <string> projectNames)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            string DbContextDefined = DbContextDef.GetClassTemplate;
            string EntitiesName     = "ApplicationDbContext"; // string.Format("{0}Model", ConnectionServices.ConnectionInfo.Initial_Catalog).ToUpperFirstWord().Replace(" ", "");
            string DbSetDefined     = string.Empty;

            bool   haveRefInfra   = projectNames.Count() > 0; // 是否有參照 Infrastructure 專案
            bool   completeUsing  = false;
            string appProjectName = haveRefInfra ? projectNames[0] : "";

            DbContextDefined = DbContextDefined.Replace("$(NAMESPACE_DEF)$", string.Format("{0}", project.Name));
            DbContextDefined = DbContextDefined.Replace("$(ENTITIES_DEF)$", EntitiesName);
            if (haveRefInfra)
            {
                string domainProjectName = GetProjectNameFromDTE(project)
                                           .Where(c => c != appProjectName)
                                           .FirstOrDefault();

                completeUsing = !string.IsNullOrEmpty(domainProjectName);

                if (completeUsing)
                {
                    // 顯示 Confirm Windows 提示開發人員輸入 Domain Layer 專案名稱 提供 ApplicationDbContext 程式碼內容的 using 參考使用
                    DbContextDefined = DbContextDefined.Replace("$(OTHER_NAMESPACE)$", $"\r\nusing {domainProjectName}.Entities;\r\nusing {appProjectName}.Common.Interfaces;");
                }
                else
                {
                    // 顯示 Confirm Windows 提示開發人員輸入 Domain Layer 專案名稱 提供 ApplicationDbContext 程式碼內容的 using 參考使用
                    DbContextDefined = DbContextDefined.Replace("$(OTHER_NAMESPACE)$", $""); // 若目前方案中無法找到 domain 專案就清空該標籤
                }

                DbContextDefined = DbContextDefined.Replace("$(MARK_CODE)$", "");
            }
            else
            {
                DbContextDefined = DbContextDefined.Replace("$(OTHER_NAMESPACE)$", "");
                DbContextDefined = DbContextDefined.Replace("$(MARK_CODE)$", "//");
            }


            string DbContextFileName = $"{EntitiesName}.cs"; //string.Format("{0}Context.cs", EntitiesName);

            SQLStore store = new SQLStore();

            if (!completeUsing)
            {
                DbSetDefined += "/* 請參考 Domain 專案後再將之取消註解\r\n";
            }

            foreach (string node in frmMyORMappingWindow.SelectedTables)
            {
                DbSetDefined += string.Format("{1}public virtual DbSet<{0}Ent> {0} {{ get; set; }}\r\n", node.ToUpperFirstWord().Replace(" ", "_"), "\t\t");
                //count++;
            }

            if (!completeUsing)
            {
                DbSetDefined += "\t\t*/";
            }

            DbContextDefined = DbContextDefined.Replace("$(DB_SET_DEF)$", DbSetDefined);

            //產生 DbContext 檔案,使用檔名 InitialCalog+Model+Context.cs 並先暫放在 Temp 資料夾下.
            string TempInterfacePath = AddFile2ProjectItem(modelsFolder, DbContextDefined, DbContextFileName);

            //刪除掉暫存檔案
            try
            {
                File.Delete(TempInterfacePath);
            }
            catch (Exception ex) { } //刪除暫存檔案若失敗不處理任何訊息.
        }
コード例 #9
0
        /// <summary>
        /// 當整個專案正在進行 Generator 時所引發的事件.
        /// </summary>
        /// <param name="project">Visual Studio IDE 工具中,目前專案 Projects 集合</param>
        public void ProjectFinishedGenerating(Project project)
        {
            ProjectItem folder     = null;
            ProjectItem viewFolder = null;

            var result = from item in project.ProjectItems.OfType <ProjectItem>().AsEnumerable()
                         where item.Name == "Models"
                         select item;

            if (result.FirstOrDefault() == null)
            {
                folder = project.ProjectItems.AddFolder("Models");
            }
            else
            {
                //若這個目錄已經存在,則直接取得這個目錄.
                folder = result.FirstOrDefault();
            }

            var resultView = folder.ProjectItems.OfType <ProjectItem>().Where(c => c.Name == "ViewModels");

            if (resultView.FirstOrDefault() == null)
            {
                viewFolder = folder.ProjectItems.AddFolder("ViewModels");
            }
            else
            {
                viewFolder = resultView.FirstOrDefault();
            }

            foreach (string node in frmORMappingWindow.SelectedTables)
            {
                //MessageBox.Show(string.Format("node={0}", node));
                string ClassName = node.Replace(" ", "_");
                //MessageBox.Show(string.Format("ClassName={0}", ClassName));
                ClassDef clsDef       = new ClassDef();
                SQLStore store        = new SQLStore();
                string   ClassDefined = ClassDef.GetClassTemplate;
                ClassDefined = ClassDefined.Replace("$(NAMESPACE_DEF)$", string.Format("{0}.Models.ViewModels", project.Name));
                ClassDefined = ClassDefined.Replace("$(CLASS_DEF)$", clsDef.GetClassDef(store.GetNoDataDataTableByName(string.Format("[{0}]", node)), ClassName));
                //產生等會使用的暫存檔名
                string TempCSPath = Path.Combine(
                    Environment.GetEnvironmentVariable("temp"),
                    string.Format("{0}.cs", ClassName));

                //MessageBox.Show(TempCSPath);

                if (!Directory.Exists(Path.GetDirectoryName(TempCSPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(TempCSPath));
                }
                //建立暫存的 Class 檔案
                CreateModelCSFile(ClassDefined, TempCSPath);
                //加入暫存的 Class 檔案
                viewFolder.ProjectItems.AddFromFileCopy(TempCSPath);
                //刪除掉暫存檔案
                try {
                    File.Delete(TempCSPath);
                }
                catch (Exception ex) { } //刪除暫存檔案若失敗不處理任何訊息.
            }

            #region 使用預設Table建立View的資料夾
            ProjectItem defViewFolder = null;

            var result2 = from item in project.ProjectItems.OfType <ProjectItem>().AsEnumerable()
                          where item.Name == "Views"
                          select item;

            if (result2.FirstOrDefault() != null)
            {
                var defualtView = result2.FirstOrDefault();
                defViewFolder = defualtView.ProjectItems.AddFolder(defaultTable);
            }
            #endregion
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: CarlosX/WowPacketParser
        private static void ReadFile(string file, string[] filters, string[] ignoreFilters, int packetNumberLow, int packetNumberHigh, int packetsToRead, DumpFormatType dumpFormat, int threads, bool sqlOutput, bool prompt)
        {
            string fileName = Path.GetFileName(file);

            Console.WriteLine("{0}: Opening file", fileName);
            Console.WriteLine("{0}: Reading packets...", fileName);

            try
            {
                var packets = Reader.Read(file, filters, ignoreFilters, packetNumberLow, packetNumberHigh, packetsToRead, (dumpFormat == DumpFormatType.SummaryHeader));
                if (packets.Count <= 0)
                {
                    Console.WriteLine("{0}: Packet count is 0", fileName);
                    return;
                }

                if (dumpFormat == DumpFormatType.Bin || dumpFormat == DumpFormatType.Pkt)
                {
                    SniffType format        = dumpFormat == DumpFormatType.Bin ? SniffType.Bin : SniffType.Pkt;
                    var       fileExtension = dumpFormat.ToString().ToLower();
                    Console.WriteLine("{0}: Copying {1} packets to .{2} format...", fileName, packets.Count, fileExtension);

                    var dumpFileName = Path.ChangeExtension(file, null) + "_excerpt." + fileExtension;
                    var writer       = new BinaryPacketWriter(format, dumpFileName, Encoding.ASCII);
                    writer.Write(packets);
                }
                else
                {
                    var numberOfThreads = threads != 0 ? threads.ToString() : "a recommended number of";

                    Console.WriteLine("{0}: Assumed version: {1}", fileName, ClientVersion.GetVersionString());
                    Console.WriteLine("{0}: Parsing {1} packets with {2} threads...", fileName, packets.Count, numberOfThreads);

                    Statistics.Total = (uint)packets.Count;

                    Statistics.StartTime = DateTime.Now;
                    var outFileName    = Path.ChangeExtension(file, null) + "_parsed";
                    var outLogFileName = outFileName + ".txt";
                    var outSqlFileName = outFileName + ".sql";

                    SQLStore.Initialize(outSqlFileName, sqlOutput);

                    bool headersOnly = (dumpFormat == DumpFormatType.TextHeader || dumpFormat == DumpFormatType.SummaryHeader);
                    if (threads == 0) // Number of threads is automatically choosen by the Parallel library
                    {
                        packets.AsParallel().SetCulture().ForAll(packet => Handler.Parse(packet, headersOnly));
                    }
                    else
                    {
                        packets.AsParallel().SetCulture().WithDegreeOfParallelism(threads).ForAll(packet => Handler.Parse(packet, headersOnly));
                    }

                    Console.WriteLine("{0}: Writing data to file...", fileName);

                    if (sqlOutput)
                    {
                        // Experimental, will remove
                        SQLStore.WriteData(Builder.QuestTemplate());
                        SQLStore.WriteData(Builder.NpcTrainer());
                        SQLStore.WriteData(Builder.NpcVendor());
                        SQLStore.WriteData(Builder.NpcTemplate());
                        SQLStore.WriteData(Builder.GameObjectTemplate());
                        SQLStore.WriteData(Builder.PageText());
                        SQLStore.WriteData(Builder.NpcText());
                        SQLStore.WriteData(Builder.Gossip());
                        SQLStore.WriteData(Builder.Loot());
                    }

                    SQLStore.WriteToFile();
                    if (dumpFormat != DumpFormatType.None)
                    {
                        Handler.WriteToFile(packets, outLogFileName);
                    }

                    Statistics.EndTime = DateTime.Now;

                    Console.WriteLine(Statistics.Stats(fileName));
                    Console.WriteLine("{0}: Saved file to '{1}'", fileName, outLogFileName);
                    Console.WriteLine();
                    Statistics.Reset();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.GetType());
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                EndPrompt(prompt);
            }
        }
コード例 #11
0
        public static void HandleCharEnum(Packet packet)
        {
            Characters.Clear();

            var count = packet.ReadByte("Count");

            for (var i = 0; i < count; i++)
            {
                var guid = packet.ReadGuid("GUID");
                var name = packet.ReadCString("Name");
                var race = packet.ReadEnum <Race>("Race", TypeCode.Byte);
                var clss = packet.ReadEnum <Class>("Class", TypeCode.Byte);
                packet.ReadEnum <Gender>("Gender", TypeCode.Byte);

                packet.ReadByte("Skin");
                packet.ReadByte("Face");
                packet.ReadByte("Hair Style");
                packet.ReadByte("Hair Color");
                packet.ReadByte("Facial Hair");

                var level = packet.ReadByte("Level");
                var zone  = packet.ReadInt32("Zone Id");
                var mapId = packet.ReadEntryWithName <Int32>(StoreNameType.Map, "Map ID");

                var pos = packet.ReadVector3("Position");
                packet.ReadInt32("Guild Id");
                packet.ReadEnum <CharacterFlag>("Character Flags", TypeCode.Int32);

                if (ClientVersion.AddedInVersion(ClientVersionBuild.V3_0_2_9056))
                {
                    packet.ReadEnum <CustomizationFlag>("Customization Flags", TypeCode.Int32);
                }

                var firstLogin = packet.ReadBoolean("First Login");
                packet.ReadInt32("Pet Display Id");
                packet.ReadInt32("Pet Level");
                packet.ReadEnum <CreatureFamily>("Pet Family", TypeCode.Int32);

                for (var j = 0; j < 19; j++)
                {
                    packet.ReadInt32("Equip Display Id");
                    packet.ReadEnum <InventoryType>("Equip Inventory Type", TypeCode.Byte);
                    packet.ReadInt32("Equip Aura Id");
                }

                int bagCount = ClientVersion.AddedInVersion(ClientVersionBuild.V3_3_3_11685) ? 4 : 1;
                for (var j = 0; j < bagCount; j++)
                {
                    packet.ReadInt32("Bag Display Id");
                    packet.ReadEnum <InventoryType>("Bag Inventory Type", TypeCode.Byte);
                    packet.ReadInt32("Bag Aura Id");
                }

                bool all = true;
                foreach (StartInfo info in StartInfos)
                {
                    if (info.Race == race || info.Class == clss)
                    {
                        all = false;
                        break;
                    }
                }
                if (firstLogin && all)
                {
                    var startInfo = new StartInfo
                    {
                        StartPos = new StartPos
                        {
                            Map      = mapId,
                            Position = pos,
                            Zone     = zone
                        }
                    };

                    Stuffing.StartInformation.TryAdd(new Tuple <Race, Class>(race, clss), startInfo);
                    SQLStore.WriteData(SQLStore.StartPositions.GetCommand(race, clss, mapId, zone, pos));
                }

                var chInfo = new Player
                {
                    Race       = race,
                    Class      = clss,
                    Name       = name,
                    FirstLogin = firstLogin,
                    Level      = level
                };

                Characters.Add(guid, chInfo); // TODO Remove when its usage is converted to Stuffing.Objects
                Stuffing.Objects.TryAdd(guid, chInfo);
            }
        }