コード例 #1
0
ファイル: Form1.cs プロジェクト: RomanToropkin/HomeDB
        /// <summary>
        /// Вызывается при нажатии на пункт меню "Сохранить в JSON"
        /// </summary>
        private void MenuItemSaveJson_Click(object sender, EventArgs e)
        {
            List <Model.Model> coll = null;

            switch (tabControl.SelectedIndex)
            {
            case 0:
                saveJsonFileDialog.FileName = "Person";
                coll = TableConverter.ConvertToModel(_personCollection);
                break;

            case 1:
                saveJsonFileDialog.FileName = "Service";
                coll = TableConverter.ConvertToModel(_serviceCollection);
                break;

            case 2:
                saveJsonFileDialog.FileName = "Household";
                coll = TableConverter.ConvertToModel(_householdsCollection);
                break;
            }

            if (saveJsonFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            // получаем выбранный файл
            string filename = saveJsonFileDialog.FileName;

            DbContext.GetInstance()
            .WriteJsonFile(filename, coll);
            // сохраняем текст в файл
            MessageBox.Show(Resources.FileSaveMessage);
        }
コード例 #2
0
        // 按钮:表转换
        private void m_btnConvert_Click(object sender, EventArgs e)
        {
            bool     isEmptyTable = true;                //是否为空表
            TreeNode nodes        = m_treeView.Nodes[0]; //头

            Log.info("开始转换!");
            int number = -1;                     //表示第几个需要转

            foreach (TreeNode node in nodes.Nodes)
            {
                number++;
                if (node.Checked)
                {
                    TableConverter.startConvert(node.Text, node.Nodes[1].Checked, node.Nodes[0].Checked, number);
                    isEmptyTable = false;
                }
            }
            if (isEmptyTable)
            {
                Log.info("请选择需要转换的表!");
            }
            else
            {
                Log.info("转换完成!");
            }
        }
コード例 #3
0
ファイル: Form1.cs プロジェクト: RomanToropkin/HomeDB
        /// <summary>
        /// Вызывается при закрытии текущей формы
        /// </summary>
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            var db = DbContext.GetInstance();

            if (!_isExternalFile)
            {
                db.WriteFile(DbContext.FILE_NAME.owners, TableConverter.ConvertToModel(_personCollection));
                db.WriteFile(DbContext.FILE_NAME.service, TableConverter.ConvertToModel(_serviceCollection));
                db.WriteFile(DbContext.FILE_NAME.household, TableConverter.ConvertToModel(_householdsCollection));
            }
            else
            {
                switch (_fileType)
                {
                case FileType.person:
                    db.WriteFile(_externaalFileName, TableConverter.ConvertToModel(_personCollection));
                    db.WriteFile(DbContext.FILE_NAME.service, TableConverter.ConvertToModel(_serviceCollection));
                    db.WriteFile(DbContext.FILE_NAME.household, TableConverter.ConvertToModel(_householdsCollection));
                    break;

                case FileType.service:
                    db.WriteFile(_externaalFileName, TableConverter.ConvertToModel(_serviceCollection));
                    db.WriteFile(DbContext.FILE_NAME.owners, TableConverter.ConvertToModel(_personCollection));
                    db.WriteFile(DbContext.FILE_NAME.household, TableConverter.ConvertToModel(_householdsCollection));
                    break;

                case FileType.household:
                    db.WriteFile(_externaalFileName, TableConverter.ConvertToModel(_householdsCollection));
                    db.WriteFile(DbContext.FILE_NAME.service, TableConverter.ConvertToModel(_serviceCollection));
                    db.WriteFile(DbContext.FILE_NAME.household, TableConverter.ConvertToModel(_householdsCollection));
                    break;
                }
            }
            db.WriteMetaInfo(_metaInfo);
        }
コード例 #4
0
 // 点击取消
 private void Cancel_Click(object sender, EventArgs e)
 {
     // 恢复原样
     ConfigObjects.loadDirectories();
     TableConverter.refreshTableTree();
     instance.Hide();
 }
コード例 #5
0
        /// <summary>
        /// Imports the configuration database table.
        /// </summary>
        private void ImportBaseTable(DataTable srcTable, IBaseTable destTable)
        {
            // add primary keys if needed
            if (!srcTable.Columns.Contains(destTable.PrimaryKey))
            {
                srcTable.Columns.Add(destTable.PrimaryKey, typeof(int));
                srcTable.BeginLoadData();
                int colInd = srcTable.Columns.Count - 1;
                var id     = 1;

                foreach (DataRow row in srcTable.Rows)
                {
                    row[colInd] = id++;
                }

                srcTable.EndLoadData();
                srcTable.AcceptChanges();
            }

            // merge data
            destTable.Modified = true;
            var destProps = TypeDescriptor.GetProperties(destTable.ItemType);

            foreach (DataRowView srcRowView in srcTable.DefaultView)
            {
                object destItem = TableConverter.CreateItem(destTable.ItemType, srcRowView.Row, destProps);
                destTable.AddObject(destItem);
            }
        }
コード例 #6
0
 // 点击OK
 private void OK_Click(object sender, EventArgs e)
 {
     // 保存设置
     ConfigObjects.saveDirectories();
     TableConverter.refreshTableTree();
     instance.Hide();
 }
コード例 #7
0
        private BrailleProcessor(ZhuyinReverseConverter zhuyinConverter)
        {
            m_Converters = new List <WordConverter>();

            m_ContextTagConverter = new ContextTagConverter();
            m_ChineseConverter    = new ChineseWordConverter(zhuyinConverter);
            m_EnglishConverter    = new EnglishWordConverter();
            m_MathConverter       = new MathConverter();
            m_CoordConverter      = new CoordinateConverter();
            m_TableConverter      = new TableConverter();
            m_PhoneticConverter   = new PhoneticConverter();

            m_Tags = new Hashtable();
            m_Tags.Add(TextTag.Name, "╴╴");             // key/value = 標籤/替換字元
            m_Tags.Add(TextTag.BookName, "﹏﹏");
            m_Tags.Add(TextTag.NumericItem, "#");
            m_Tags.Add(TextTag.OrgPageNumber, s_DashesForOrgPageNumber); // 原書頁碼
            m_Tags.Add(TextTag.Unit1End, new string('ˍ', 20));           // 大單元結束
            m_Tags.Add(TextTag.Unit2End, new string('﹍', 20));           // 小單元結束
            m_Tags.Add(TextTag.Unit3End, new string('﹋', 20));           // 小題結束
            m_Tags.Add(TextTag.BrailleComment, "★");                     // 點譯者註

            m_ContextTagManager = new ContextTagManager();

            m_InvalidChars   = new List <CharPosition>();
            m_ErrorMsg       = new StringBuilder();
            m_SuppressEvents = false;
        }
コード例 #8
0
        public void JsonToTable_ShouldConvertFromString_EmptyString()
        {
            string         serializedTable = "";
            TableConverter converter       = new TableConverter();
            Table          table           = converter.JsonToTable(serializedTable);

            Assert.That(table.Hashes().Count, Is.EqualTo(0));
        }
コード例 #9
0
        public void JsonToTable_ShouldConvertFromString_HeaderRowOnly()
        {
            string         serializedTable = "[[\"item\",\"count\"]]";
            TableConverter converter       = new TableConverter();
            Table          table           = converter.JsonToTable(serializedTable);

            Assert.That(table.Hashes().Count, Is.EqualTo(0));
        }
コード例 #10
0
        public void JsonToTable_ShouldConvertFromString_HeaderAndDataRows()
        {
            string         serializedTable = "[[\"item\",\"count\"],[\"cucumbers\",\"3\"],[\"bananas\",\"5\"],[\"tomatoes\",\"2\"]]";
            TableConverter converter       = new TableConverter();
            Table          table           = converter.JsonToTable(serializedTable);

            Assert.That(table.Data.Count, Is.EqualTo(4));
        }
コード例 #11
0
        public async Task <ActionResult <TableResponse> > UpdateAsync([FromBody] Table table)
        {
            var updatedTable = await tableService.UpdateAsync(table);

            var tableResponse = TableConverter.GetTableResponse(updatedTable);

            return(Ok(tableResponse));
        }
コード例 #12
0
        public async Task <HATEOASResult> GetByDatabaseAsync(Guid databaseId)
        {
            var tables = await tableService.GetAllAsync(databaseId);

            var tablesResponse = tables.Select(t => TableConverter.GetTableResponse(t)).ToList();

            return(this.HATEOASResult(tablesResponse, (t) => Ok(t)));
        }
コード例 #13
0
        public async Task <HATEOASResult> GetAsync(Guid id)
        {
            var table = await tableService.GetAsync(id);

            var tableResponse = TableConverter.GetTableResponse(table);

            return(this.HATEOASResult(tableResponse, (t) => Ok(t)));
        }
コード例 #14
0
        public void JsonToTable_ShouldThrowForInvalidData_NotAnArray()
        {
            string         serializedTable = "{\"foo\":\"bar\"}";
            TableConverter converter       = new TableConverter();

            Assert.Throws <ArgumentException>(delegate {
                /*Table table =*/ converter.JsonToTable(serializedTable);
            });
        }
コード例 #15
0
        public void TableToJsonString_ShouldConvertFromTable_EmptyTable()
        {
            Table          table = new Table();
            string         expectedJsonString = "[]";
            TableConverter converter          = new TableConverter();
            string         actualJsonString   = converter.TableToJsonString(table);

            Assert.That(actualJsonString, Is.EqualTo(expectedJsonString));
        }
コード例 #16
0
 public long Count(MySqlConnection connection)
 {
     lock (DatabaseManager.SyncRoot)
     {
         using (MySqlCommand cmd = new MySqlCommand(string.Format(TableConverter.GetOperation(DatabaseOperation.COUNT), TableName), connection))
         {
             return((long)cmd.ExecuteScalar());
         }
     }
 }
コード例 #17
0
        public void JsonToTable_ShouldThrowForInvalidData_NoInternalArrays()
        {
            string         serializedTable = "[{\"foo\":\"1\"},{\"bar\":\"2\"}]";
            TableConverter converter       = new TableConverter();

            Assert.Throws <ArgumentException>(delegate
            {
                Table table = converter.JsonToTable(serializedTable);
            });
        }
コード例 #18
0
        public void TableToJsonString_ShouldConvertFromTable_HeaderRowOnly()
        {
            Table table = new Table();

            table.Data.Add(new List <string>(new string[] { "item", "count" }));
            string         expectedJsonString = "[[\"item\",\"count\"]]";
            TableConverter converter          = new TableConverter();
            string         actualJsonString   = converter.TableToJsonString(table);

            Assert.That(actualJsonString, Is.EqualTo(expectedJsonString));
        }
コード例 #19
0
        public void JsonToTable_ShouldThrowForInvalidData_NonStringDataInInternalArray()
        {
            string         serializedTable = "[[2,1],[42,2]]";
            TableConverter converter       = new TableConverter();

            //converter.JsonToTable(serializedTable);
            Assert.Throws <ArgumentException>(delegate
            {
                /*Table table =*/ converter.JsonToTable(serializedTable);
            });
        }
コード例 #20
0
        private void DeleteElements(IEnumerable <IRecord> elements)
        {
            foreach (var element in elements)
            {
                var commandString = string.Format(TableConverter.GetOperation(DatabaseOperation.REMOVE), TableName, PrimaryProperty.Name, PrimaryProperty.GetValue(element));

                using (var command = new MySqlCommand(commandString, ServiceLocator.Provider.GetService <IDatabaseManager>().UseConnection()))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
コード例 #21
0
        public async Task <ActionResult <TableResponse> > CreateAsync([FromBody] Table table)
        {
            if (!tableService.Validate(table))
            {
                return(BadRequest());
            }
            var createdTable = await tableService.CreateAsync(table);

            var tableResponse = TableConverter.GetTableResponse(createdTable);

            return(Ok(tableResponse));
        }
コード例 #22
0
ファイル: Form1.cs プロジェクト: RomanToropkin/HomeDB
        //Внешняя таблица - таблица, находящаяся вне каталога приложения

        /// <summary>
        /// Инициализация формы и скачивания таблиц из внешнего файла.
        /// Инициализация привязок данных к таблицам
        /// </summary>
        public Form1()
        {
            Application.Run(new SplashScreen());
            InitializeComponent();

            var db = DbContext.GetInstance();

            _metaInfo = db.ReadMetaInfo();

            _personSource         = new BindingSource();
            _isPersonFilterActive = false;
            _personCollection     = TableConverter.ConvertToPerson(db.ReadFile(DbContext.FILE_NAME.owners));
            if (_personCollection == null || _personCollection.Count == 0)
            {
                _personCollection = new List <Person>();
            }
            else
            {
                _selectedPerson = _personCollection[0];
            }

            _personSource.DataSource = _personCollection;
            TableHelper.SetupPersonTable(dataGridView1, _personSource);

            _serviceSource     = new BindingSource();
            _serviceCollection = TableConverter.ConvertToService(db.ReadFile(DbContext.FILE_NAME.service));
            if (_serviceCollection == null || _serviceCollection.Count == 0)
            {
                _serviceCollection = new List <Service>();
            }
            else
            {
                _selectedService = _serviceCollection[0];
            }

            _serviceSource.DataSource = _serviceCollection;
            TableHelper.SetupServiceTable(dataGridViewService, _serviceSource);

            _householdSource      = new BindingSource();
            _householdsCollection = TableConverter.ConvertToHousehold(db.ReadFile(DbContext.FILE_NAME.household));
            if (_householdsCollection == null || _householdsCollection.Count == 0)
            {
                _householdsCollection = new List <Household>();
            }
            else
            {
                _selectedHousehold = _householdsCollection[0];
            }

            _householdSource.DataSource = _householdsCollection;
            TableHelper.SetupHouseholdTable(dataGridViewHouse, _householdSource);
        }
コード例 #23
0
        private void button1_Click(object sender, EventArgs e)
        {
            var loot       = DataDownloader.GetItemsFromLootFarm(lootUrl);
            var swap       = DataDownloader.GetItemsFromSwapGG(swapUrl);
            var flag       = sourcesCB1.SelectedIndex == 0 ? false : true;
            var dataSource = new TableConverter().ConvertModels(loot, swap, flag);

            mainData.Init();

            mainData.DataSource = dataSource;

            btnGetData.Enabled = false;
        }
コード例 #24
0
        public void TableToJsonString_ShouldConvertFromTable_HeaderAndDataRows()
        {
            Table table = new Table();

            table.Data.Add(new List <string>(new string[] { "item", "count" }));
            table.Data.Add(new List <string>(new string[] { "cucumbers", "3" }));
            table.Data.Add(new List <string>(new string[] { "bananas", "5" }));
            table.Data.Add(new List <string>(new string[] { "tomatoes", "2" }));
            string         expectedJsonString = "[[\"item\",\"count\"],[\"cucumbers\",\"3\"],[\"bananas\",\"5\"],[\"tomatoes\",\"2\"]]";
            TableConverter converter          = new TableConverter();
            string         actualJsonString   = converter.TableToJsonString(table);

            Assert.That(actualJsonString, Is.EqualTo(expectedJsonString));
        }
コード例 #25
0
        public DataTable ToTable()
        {
            DataTable result = null;

            try
            {
                result = TableConverter.Create(Xml);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(result);
        }
コード例 #26
0
        public static Table AdaptTableFromJson(string Json)
        {
            JToken        JTable   = JToken.Parse(Json);
            Table         table    = TableConverter.ConvertWithName(JTable);
            JToken        JColumns = JTable["Columns"];
            List <Column> columns  = new List <Column>();

            foreach (JToken Jcolumn in JColumns)
            {
                Column column = ColumnConverter.Convert(Jcolumn);
                columns.Add(column);
            }
            table.Columns = new ColumnCollection(columns);
            return(table);
        }
コード例 #27
0
        public DataTable ToTable()
        {
            DataTable result = null;

            try
            {
                result = TableConverter.Create(Xml);
            }
            catch (Exception ex)
            {
                Logger.Log("DeviceConfiguration.ToTable() :: Exception :: " + ex.Message, LogLineType.Warning);
            }

            return(result);
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: cn00/xls2lua
        // 正常模式
        static void modeNormal()
        {
            PROGRAM_TYPE = E_MODE_TYPE.MODE_TYPE_WINFORM;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            TableConverter.refreshTableTree();


            if (Program._isOnlyOne)
            {
                MainWindow.getInstance().DetermineClick();
                Program._isOnlyOne = false;
            }

            Application.Run(MainWindow.getInstance());
        }
コード例 #29
0
        private void UpdateElements(IRecord[] elements)
        {
            if (HasNoUpdateProperties)
            {
                throw new Exception("Unable to update elements. " + TableName + " has no update property.");
            }


            var command = new MySqlCommand(string.Empty, ServiceLocator.Provider.GetService <IDatabaseManager>().UseConnection());

            List <string> final = new List <string>();

            for (int i = 0; i < elements.Length; i++)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var property in UpdateProperties)
                {
                    sb.Append(string.Format("{2} = ?{0}{1},", property.Name, i, property.Name));
                    MySqlParameter mySQLParam = new MySqlParameter("?" + property.Name + i, ConvertObject(property, elements[i]));
                    command.Parameters.Add(mySQLParam);
                }

                sb = sb.Remove(sb.Length - 1, 1);

                final.Add(sb.ToString());

                var finalText = string.Format("{0}", string.Join(",", final));

                string arg1 = TableName;
                string arg2 = finalText;
                command.CommandText = string.Format(TableConverter.GetOperation(DatabaseOperation.UPDATE), arg1, arg2, PrimaryProperty.Name, elements[i].Id.ToString());

                try
                {
                    command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable update database element (" + TableName + ") " +
                                        ex.Message);
                }
            }
        }
コード例 #30
0
        public IRecord ReadFirst(MySqlConnection connection, string where)
        {
            DatabaseManager.SyncRoot.EnterReadLock();

            using var command = new MySqlCommand(string.Format(TableConverter.GetOperation(DatabaseOperation.SELECT_WHERE), TableName, where), connection);
            try
            {
                this.m_reader = command.ExecuteReader();

                if (!m_reader.HasRows)
                {
                    return(null);
                }

                var obj = new object[this.Properties.Length];

                if (m_reader.Read())
                {
                    for (var i = 0; i < this.Properties.Length; i++)
                    {
                        obj[i] = ConvertObject(this.m_reader[i], Properties[i]);
                    }
                }

                var data = (IRecord)Activator.CreateInstance(Type); // expressions?

                for (int i = 0; i < Properties.Length; i++)
                {
                    Properties[i].SetValue(data, obj[i]);
                }
                ServiceLocator.Provider.GetService <IDatabaseManager>().UseConnection().Close();
                return(data);
            }
            catch (Exception ex)
            {
                ServiceLocator.Provider.GetService <ILogger>().LogWarning("Unable to read table " + TableName + " " + ex.Message);
                this.m_reader?.Close();
                return(null);
            }

            finally { DatabaseManager.SyncRoot.ExitReadLock(); }
        }
コード例 #31
0
 public DataSetConverter()
 {
     tableConverter = new TableConverter();
     linkedServiceConverter = new LinkedServiceConverter();
 }
 public ActivityConfigurationConverter()
 {
     tableConverter = new TableConverter();
     linkedServiceConverter = new LinkedServiceConverter();
     pipelineConverter = new PipelineConverter();
 }