예제 #1
0
        internal override void Upgrade(SQLiteTransaction transaction)
        {
            // Create table to save userdata
            transaction.Execute(@"CREATE TABLE IF NOT EXISTS ""AppData"" (
                                 ""Id"" INTEGER PRIMARY KEY AUTOINCREMENT,
                                 ""ShowCompleted"" NUMBER DEFAULT 0)");
            transaction.Execute(@"INSERT OR REPLACE INTO AppData (Id) VALUES (1)");

            // Create table for entries
            transaction.Execute(@"CREATE TABLE IF NOT EXISTS ""Entry"" (
                                 ""Id"" INTEGER PRIMARY KEY AUTOINCREMENT,
                                 ""Title"" TEXT NULL,
                                 ""Completed"" NUMBER DEFAULT 0,
                                 ""CreatedAtUtc"" NUMBER NOT NULL)");
            transaction.Execute(@"CREATE UNIQUE INDEX IxEntry ON Entry (Id)");

            // Create table to store the entries relationship
            transaction.Execute(@"CREATE TABLE IF NOT EXISTS ""EntryRelation"" (
                                 ""ParentId"" NUMBER NOT NULL,
                                 ""ChildId"" NUMBER UNIQUE NOT NULL,
                                 PRIMARY KEY (""ParentId"", ""ChildId""),
                                 FOREIGN KEY(""ParentId"") REFERENCES ""Entry""(""Id""),
                                 FOREIGN KEY(""ChildId"") REFERENCES ""Entry""(""Id""))");
            transaction.Execute(@"CREATE UNIQUE INDEX IxEntryRelation ON EntryRelation (ParentId, ChildId)");

            UpdateDatabaseVersion(transaction);
        }
            private void init(string connString)
            {
                connection = new SQLiteConnection(connString);
                connection.Open();
                //connection.ChangeDatabase(Server.MySQLDatabaseName);

                transaction = connection.BeginTransaction();
            }
예제 #3
0
        internal override void Upgrade(SQLiteTransaction transaction)
        {
            // Create database helper table
            transaction.Execute(@"CREATE TABLE IF NOT EXISTS ""DatabaseInfo"" (
                                 ""Id"" INTEGER PRIMARY KEY AUTOINCREMENT,
                                 ""Version"" TEXT NOT NULL)");

            UpdateDatabaseVersion(transaction);
        }
예제 #4
0
        protected void UpdateDatabaseVersion(SQLiteTransaction transaction)
        {
            const string sql = @"INSERT OR REPLACE INTO ""DatabaseInfo"" (""Id"", ""Version"") VALUES (1, @version);";
            using (var statement = transaction.Prepare(sql))
            {
                statement.Bind("@version", DbVersion.ToString());

                bool success = transaction.Execute(statement);
                if (!success)
                {
                    throw new Exception(string.Format("Failed to update database version to {0}", DbVersion));
                }
            }
        }
예제 #5
0
        private void SaveSettingsImpl()
        {
            using (SQLiteTransaction transaction = Database.Connection.BeginTransaction())
            {
                if (Config.UpdatesEnabled != this.UpdatesEnabledConfig)
                {
                    Config.UpdatesEnabled = this.UpdatesEnabledConfig;
                    this.updater.HandleUpdatedSettings(this.UpdatesEnabledConfig);
                }

                if (Config.InterfaceLanguageCode != this.InterfaceLanguage.CultureCode)
                {
                    Config.InterfaceLanguageCode = this.InterfaceLanguage.CultureCode;
                    Ioc.Get <IMessageBoxService>().Show(this, OptionsRes.NewLanguageRestartDialogMessage);
                }

                Config.AutoNameOutputFolder           = this.DefaultPath;
                Config.AutoNameCustomFormat           = this.CustomFormat;
                Config.AutoNameCustomFormatString     = this.CustomFormatString;
                Config.OutputToSourceDirectory        = this.OutputToSourceDirectory;
                Config.PreserveFolderStructureInBatch = this.PreserveFolderStructureInBatch;
                Config.UseCustomPreviewFolder         = this.UseCustomPreviewFolder;
                Config.PreviewOutputFolder            = this.PreviewOutputFolder;
                CustomConfig.WhenFileExists           = this.WhenFileExists;
                CustomConfig.WhenFileExistsBatch      = this.WhenFileExistsBatch;
                Config.MinimizeToTray              = this.MinimizeToTray;
                Config.UseCustomVideoPlayer        = this.UseCustomVideoPlayer;
                Config.CustomVideoPlayer           = this.CustomVideoPlayer;
                Config.UseBuiltInPlayerForPreviews = this.UseBuiltInPlayerForPreviews;
                Config.PlaySoundOnCompletion       = this.PlaySoundOnCompletion;
                Config.UseCustomCompletionSound    = this.UseCustomCompletionSound;
                Config.CustomCompletionSound       = this.CustomCompletionSound;
                Config.WorkerProcessPriority       = this.WorkerProcessPriority;
                Config.LogVerbosity          = this.LogVerbosity;
                Config.CopyLogToOutputFolder = this.CopyLogToOutputFolder;
                var autoPauseList = new List <string>();
                foreach (string process in this.AutoPauseProcesses)
                {
                    autoPauseList.Add(process);
                }

                CustomConfig.AutoPauseProcesses = autoPauseList;
                Config.PreviewCount             = this.PreviewCount;
                Config.RememberPreviousFiles    = this.RememberPreviousFiles;
                // Clear out any file/folder history when this is disabled.
                if (!this.RememberPreviousFiles)
                {
                    Config.LastCsvFolder          = null;
                    Config.LastInputFileFolder    = null;
                    Config.LastOutputFolder       = null;
                    Config.LastPresetExportFolder = null;
                    Config.LastSrtFolder          = null;
                    Config.LastVideoTSFolder      = null;

                    Config.SourceHistory = null;
                }

                Config.ShowAudioTrackNameField = this.ShowAudioTrackNameField;
                Config.EnableLibDvdNav         = this.EnableLibDvdNav;
                Config.DeleteSourceFilesOnClearingCompleted = this.DeleteSourceFilesOnClearingCompleted;
                Config.PreserveModifyTimeFiles   = this.PreserveModifyTimeFiles;
                Config.ResumeEncodingOnRestart   = this.ResumeEncodingOnRestart;
                Config.UseWorkerProcess          = this.UseWorkerProcess;
                Config.MinimumTitleLengthSeconds = this.MinimumTitleLengthSeconds;
                Config.VideoFileExtensions       = this.VideoFileExtensions;
                Config.CpuThrottlingFraction     = (double)this.CpuThrottlingCores / this.CpuThrottlingMaxCores;

                Config.PreferredPlayer = this.selectedPlayer.Id;

                transaction.Commit();
            }

            this.Accept.Execute(null);
        }
예제 #6
0
 private static void InsertDataForTest(SQLiteConnection conn, SQLiteTransaction tran)
 {
     SqlLiteDatabase.ExecuteNonQuery(
         "insert into TEST_TABLE(TEST_COL1) " +
         "VALUES(@testVal1)",
         new (string, object)[] {
    /// <summary>
    ///     A SQLiteConnection extension method that executes the data table operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="parameters">Options for controlling the operation.</param>
    /// <param name="commandType">Type of the command.</param>
    /// <param name="transaction">The transaction.</param>
    /// <returns>A DataTable.</returns>
    public static DataTable ExecuteDataTable(this SQLiteConnection @this, string cmdText, SQLiteParameter[] parameters, CommandType commandType, SQLiteTransaction transaction)
    {
        using (SQLiteCommand command = @this.CreateCommand())
        {
            command.CommandText = cmdText;
            command.CommandType = commandType;
            command.Transaction = transaction;

            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }

            var ds = new DataSet();
            using (var dataAdapter = new SQLiteDataAdapter(command))
            {
                dataAdapter.Fill(ds);
            }

            return(ds.Tables[0]);
        }
    }
예제 #8
0
파일: GNMKBDAL.cs 프로젝트: fengwenbin/test
        ///
        public bool UpdateList(List <tdps.Model.GNMKB> _list)
        {
            SQLiteConnection  conn = null;
            SQLiteTransaction tran = null;

            try
            {
                if (_list != null && _list.Count > 0)
                {
                    conn = new SQLiteConnection(SQLiteHelper.connectionString);
                    if (conn.State == System.Data.ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    //开启事务
                    tran = conn.BeginTransaction();
                    for (int i = 0; i < _list.Count; i++)
                    {
                        if (_list[i].CZLX.Equals("1"))
                        {
                            StringBuilder _sql = new StringBuilder();
                            _sql.Append("update GNMKB set ");
                            _sql.Append(" SFKY=" + (_list[i].SFKY.Trim().Length > 0 ? _list[i].SFKY.Trim() : "SFKY"));
                            _sql.Append(",SJ=" + (_list[i].SJ.Trim().Length > 0 ? "'" + _list[i].SJ.Trim() + "'" : "SJ"));
                            _sql.Append(",SFBX=" + (_list[i].SFBX.Trim().Length > 0 ? _list[i].SFBX.Trim() : "SFBX"));
                            _sql.Append(",SWJGT=" + (_list[i].SWJGT.Trim().Length > 0 ? _list[i].SWJGT.Trim() : "SWJGT"));
                            _sql.Append(" where GNBH='" + _list[i].GNBH + "' and NSRSBH = '" + _list[i].NSRSBH + "'");;

                            if (SQLiteHelper.ExecuteSqlTran(conn, tran, _sql.ToString()) > 0)
                            {
                                continue;
                            }
                            else
                            {
                                tran.Rollback();
                                return(false);
                            }
                        }
                        else if (_list[i].CZLX.Equals("0"))
                        {
                            string strSql = "insert into GNMKB(GNMC,SJ,GNBH,NSRSBH) VALUES('" + _list[i].GNMC + "','" + _list[i].SJ + "','" + _list[i].GNBH + "','" + _list[i].NSRSBH + "')";

                            if (SQLiteHelper.ExecuteSqlTran(conn, tran, strSql) > 0)
                            {
                                continue;
                            }
                            else
                            {
                                tran.Rollback();
                                return(false);
                            }
                        }
                    }
                }
                else
                {
                    tran.Rollback();
                    return(false);
                }
                tran.Commit();
                return(true);
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return(false);
            }
            finally
            {
                conn.Close();
            }
        }
 /// <summary>
 ///     Enumerates execute entities in this collection.
 /// </summary>
 /// <typeparam name="T">Generic type parameter.</typeparam>
 /// <param name="this">The @this to act on.</param>
 /// <param name="cmdText">The command text.</param>
 /// <param name="transaction">The transaction.</param>
 /// <returns>An enumerator that allows foreach to be used to process execute entities in this collection.</returns>
 public static IEnumerable <T> ExecuteEntities <T>(this SQLiteConnection @this, string cmdText, SQLiteTransaction transaction) where T : new()
 {
     return(@this.ExecuteEntities <T>(cmdText, null, CommandType.Text, transaction));
 }
예제 #10
0
 public void StartTransaction()
 {
     this.transaction = this.connection.BeginTransaction();
 }
예제 #11
0
 /// <summary>
 /// 回滚事务
 /// </summary>
 public void rollBackTransaction()
 {
     trans.Rollback();
     trans = null;
 }
예제 #12
0
 /// <summary>
 /// 开始事务
 /// </summary>
 public void beginTransaction()
 {
     trans = sqlConn.BeginTransaction();
 }
예제 #13
0
        public UnitOfWork(SQLiteTransaction dbTransaction)
        {
            //_repositoryFactory = repositoryFactory ?? throw new ArgumentNullException(nameof(repositoryFactory));

            _dbTransaction = dbTransaction;
        }
예제 #14
0
 /// <summary>
 /// Creates an open data source using the supplied connection and optional transaction.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <param name="transaction">The transaction.</param>
 /// <returns>SQLiteOpenDataSource.</returns>
 public SQLiteOpenDataSource CreateOpenDataSource(SQLiteConnection connection, SQLiteTransaction transaction = null)
 {
     return(new SQLiteOpenDataSource(this, connection, transaction));
 }
예제 #15
0
 internal abstract void Upgrade(SQLiteTransaction transaction);
예제 #16
0
        public bool IsValid(Connection connection, SQLiteTransaction transaction)
        {
            string mensagem;

            return(IsValid(out mensagem, connection, transaction));
        }
 /// <summary>
 /// Actualiza la base de datos bajo la entidad comunicada
 /// </summary>
 /// <param name="pAsunto"></param>
 /// <param name="conn"></param>
 /// <param name="trans"></param>
 public static void ActualizarEstadosPorAsunto(Entidades.Asunto pAsunto, SQLiteConnection conn, SQLiteTransaction trans)
 {
     // Eliminamos los estados de asunto
     EliminarEstadosPorAsunto(pAsunto, conn, trans);
     // Agregamos los estados cargados del asunto
     AddAllFromAsunto(pAsunto, conn, trans);
 }
예제 #18
0
 /// <summary>
 /// 提交事务
 /// </summary>
 public void commitTransaction()
 {
     trans.Commit();
     trans = null;
 }
예제 #19
0
 /// <summary>
 /// Executes  non-query sql Statment with Transaction
 /// </summary>
 /// <param name="transaction">SQLiteTransaction. Transaction consists of Connection, Transaction,   /// and Command, all of which must be created prior to making this method call. </param>
 /// <param name="commandText">Command text.</param>
 /// <param name="paramList">Param list.</param>
 /// <returns>Integer</returns>
 /// <remarks>user must examine Transaction Object and handle transaction.connection .Close, etc.</remarks>
 public static int ExecuteNonQuery(SQLiteTransaction transaction, string commandText, params  object[] paramList)
 {
     if (transaction == null) throw new ArgumentNullException("transaction");
     if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed,                                                        please provide an open transaction.", "transaction");
     IDbCommand cmd = transaction.Connection.CreateCommand();
     cmd.CommandText = commandText;
     AttachParameters((SQLiteCommand)cmd, cmd.CommandText, paramList);
     if (transaction.Connection.State == ConnectionState.Closed)
         transaction.Connection.Open();
     int result = cmd.ExecuteNonQuery();
     cmd.Dispose();
     return result;
 }
예제 #20
0
        void IResultWriter.WriteTableBegin(DataTable schemaTable)
        {
            Trace.WriteLine(schemaTable.ToStringTableString());
            var    sb              = new StringBuilder();
            var    schemaRows      = schemaTable.Rows;
            var    schemaRowCount  = schemaRows.Count;
            string insertStatement = null;
            var    insertValues    = new StringBuilder();

            _insertCommand = new SQLiteCommand();
            var st = new StringTable(3);

            for (var i = 0; i < schemaRowCount; i++)
            {
                var schemaRow      = FoundationDbColumnFactory.Create(schemaRows[i]);
                var stringTableRow = st.NewRow();

                if (i == 0)
                {
                    var tableName = schemaRow.BaseTableName;

                    if (tableName != null)
                    {
                        _tableName = tableName;
                    }

                    _tableName = _tableName.Replace('.', '_');
                    _tableName = _tableName.Replace('[', '_');
                    _tableName = _tableName.Replace(']', '_');

                    sb.AppendFormat("CREATE TABLE {0}\r\n(\r\n", _tableName);
                    insertStatement = "INSERT INTO " + _tableName + '(';
                    insertValues.Append("VALUES(");
                }
                else
                {
                    insertStatement += ',';
                    insertValues.Append(',');
                }

                var columnName = schemaRow.ColumnName;
                stringTableRow[1] = columnName;
                insertStatement  += columnName;
                insertValues.Append('?');
                var    columnSize = (int)schemaRow.ColumnSize;
                var    dataType   = schemaRow.DataType;
                var    typeCode   = Type.GetTypeCode(dataType);
                string typeName;
                DbType dbType;

                switch (typeCode)
                {
                case TypeCode.Boolean:
                    typeName = "BOOLEAN";
                    dbType   = DbType.Boolean;
                    break;

                case TypeCode.DateTime:
                    typeName = "DATETIME";
                    dbType   = DbType.DateTime;
                    break;

                case TypeCode.Decimal:
                    var precision = schemaRow.NumericPrecision.Value;
                    var scale     = schemaRow.NumericPrecision.Value;

                    if (precision <= 28 && scale <= 28)
                    {
                        typeName = $"DECIMAL({precision},{scale})";
                        dbType   = DbType.Decimal;
                    }
                    else
                    {
                        typeName = $"-- DECIMAL({precision},{scale})";
                        dbType   = DbType.Object;
                    }

                    break;

                case TypeCode.Double:
                    typeName = "DOUBLE";
                    dbType   = DbType.Double;
                    break;

                case TypeCode.Int16:
                    typeName = "SMALLINT";
                    dbType   = DbType.Int16;
                    break;

                case TypeCode.Int32:
                    typeName = "INT";
                    dbType   = DbType.Int32;
                    break;

                case TypeCode.Int64:
                    typeName = "BIGINT";
                    dbType   = DbType.Int64;
                    break;

                case TypeCode.String:
                    typeName = $"VARCHAR({columnSize})";
                    dbType   = DbType.String;
                    break;

                default:
                    throw new NotImplementedException();
                }

                stringTableRow[2] = typeName;
                st.Rows.Add(stringTableRow);
                var allowDbNull = schemaRow.AllowDbNull.Value;

                if (!allowDbNull)
                {
                    stringTableRow[2] += " NOT NULL";
                }

                if (i < schemaRowCount - 1)
                {
                    stringTableRow[2] += ',';
                }

                var parameter = new SQLiteParameter(dbType);
                _insertCommand.Parameters.Add(parameter);
            }

            sb.Append(st.ToString(4));
            sb.Append(')');
            insertValues.Append(')');
            insertStatement += ") " + insertValues;
            var commandText = sb.ToString();

            Trace.WriteLine(commandText);
            Trace.WriteLine(insertStatement);
            var executor = _connection.CreateCommandExecutor();

            executor.ExecuteNonQuery(new CreateCommandRequest(commandText));
            _transaction = _connection.BeginTransaction();
            _insertCommand.Connection  = _connection;
            _insertCommand.Transaction = _transaction;
            _insertCommand.CommandText = insertStatement;
        }
    /// <summary>
    ///     Enumerates execute entities in this collection.
    /// </summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="parameters">Options for controlling the operation.</param>
    /// <param name="commandType">Type of the command.</param>
    /// <param name="transaction">The transaction.</param>
    /// <returns>An enumerator that allows foreach to be used to process execute entities in this collection.</returns>
    public static IEnumerable <T> ExecuteEntities <T>(this SQLiteConnection @this, string cmdText, SQLiteParameter[] parameters, CommandType commandType, SQLiteTransaction transaction) where T : new()
    {
        using (SQLiteCommand command = @this.CreateCommand())
        {
            command.CommandText = cmdText;
            command.CommandType = commandType;
            command.Transaction = transaction;

            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }

            using (IDataReader reader = command.ExecuteReader())
            {
                return(reader.ToEntities <T>());
            }
        }
    }
예제 #22
0
        private void DeleteExistingRows(DataTable dataTable, Guid id, SQLiteConnection connection, SQLiteTransaction transaction)
        {
            string        columnName  = dataTable.Columns[0].ColumnName;
            string        commandText = string.Format("DELETE FROM {0} WHERE {1} = '{2}'", dataTable.TableName, columnName, id);
            SQLiteCommand cmd         = new SQLiteCommand(commandText, connection, transaction);

            cmd.ExecuteNonQuery();
        }
예제 #23
0
        public void InstallSet(string filename)
        {
            SQLiteTransaction trans = GamesRepository.DatabaseConnection.BeginTransaction();

            try
            {
                using (Package package = Package.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    PackageRelationship defRelationship =
                        package.GetRelationshipsByType("http://schemas.octgn.org/set/definition").First();
                    PackagePart definition = package.GetPart(defRelationship.TargetUri);

                    var settings = new XmlReaderSettings
                    {
                        ValidationType = ValidationType.Schema, IgnoreWhitespace = true
                    };
                    using (
                        Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(GamesRepository),
                                                                                             "CardSet.xsd"))
                        //CardSet.xsd determines the "attributes" of a card (name, guid, alternate, dependent)
                        if (s != null)
                        {
                            using (XmlReader reader = XmlReader.Create(s))
                                settings.Schemas.Add(null, reader);
                        }

                    // Read the cards
                    using (XmlReader reader = XmlReader.Create(definition.GetStream(), settings))
                    {
                        reader.ReadToFollowing("set"); // <?xml ... ?>

                        var set = new Set(filename, reader, Repository);
                        if (set.Game != this)
                        {
                            throw new ApplicationException(
                                      string.Format("The set '{0}' is not built for the game '{1}'.", set.Name, Name));
                        }
                        if (set.GameVersion.Major != Version.Major || set.GameVersion.Minor != Version.Minor)
                        {
                            throw new ApplicationException(
                                      string.Format(
                                          "The set '{0}' is incompatible with the installed game version.\nGame version: \nSet made for version: {1:2}.",
                                          set.Name, set.GameVersion));
                        }

                        InsertSet(set);

                        if (reader.IsStartElement("packaging"))
                        {
                            reader.ReadStartElement(); // <packaging>
                            while (reader.IsStartElement("pack"))
                            {
                                string xml  = reader.ReadOuterXml();
                                var    pack = new Pack(set, xml);
                                InsertPack(pack, xml, set.Id);
                            }
                            reader.ReadEndElement(); // </packaging>
                        }

                        if (reader.IsStartElement("markers"))
                        {
                            reader.ReadStartElement(); // <markers>
                            while (reader.IsStartElement("marker"))
                            {
                                reader.MoveToAttribute("name");
                                string markerName = reader.Value;
                                reader.MoveToAttribute("id");
                                var    markerId       = new Guid(reader.Value);
                                Uri    markerImageUri = definition.GetRelationship("M" + markerId.ToString("N")).TargetUri;
                                string markerUri      = markerImageUri.OriginalString;
                                if (!package.PartExists(markerImageUri))
                                {
                                    throw new ApplicationException(
                                              string.Format(
                                                  "Image for marker '{0}', with URI '{1}' was not found in the package.",
                                                  markerName, markerUri));
                                }
                                reader.Read(); // <marker />
                                InsertMarker(markerId, markerName, markerUri, set.Id);
                            }
                            reader.ReadEndElement(); // </markers>
                        }

                        if (reader.IsStartElement("cards"))
                        {
                            reader.ReadStartElement(); // <cards>
                            while (reader.IsStartElement("card"))
                            {
                                InsertCard(new CardModel(reader, this, set, definition, package));
                            }
                            // cards are parsed through the CardModel constructor, which are then inserted individually into the database
                            reader.ReadEndElement(); // </cards>
                        }

                        reader.ReadEndElement();
                    }

                    CopyDecks(package);
                    package.Close();

                    // Commit the changes
                    trans.Commit();
                }
            }
            catch (Exception e)
            {
                trans.Rollback();
                throw e;
            }
            if (SimpleDataTableCache.CacheExists())
            {
                SimpleDataTableCache.ClearCache();
            }
        }
예제 #24
0
        static void Main(string[] args)
        {
            String Database;
            String DatabaseMissing;
            String TxtFilename;
            String ScenarioFilename;
            int    FileNumber;
            String GracesJapanese;
            bool   updateGracesEnglish = false;

            if (args.Length < 6)
            {
                Console.WriteLine("Usage: GraceNote_ScenarioDatTxt DBFilename DBMissing TxtFilename ScenarioFilename FileNumber GracesJapanese");
                return;
            }
            Database            = args[0];
            DatabaseMissing     = args[1];
            TxtFilename         = args[2];
            ScenarioFilename    = args[3];
            FileNumber          = Int32.Parse(args[4]);
            GracesJapanese      = args[5];
            updateGracesEnglish = args.Contains("--updateGracesEnglish");

            ScenarioFile[] ScenarioStrings;
            ScenarioFile[] MissingStrings;
            try {
                ScenarioStrings = GetSQL("Data Source=" + Database, -1, "Data Source=" + GracesJapanese);
                MissingStrings  = GetSQL("Data Source=" + DatabaseMissing, FileNumber, "Data Source=" + GracesJapanese);

                List <ScenarioFile> FullStrings = new List <ScenarioFile>(ScenarioStrings);
                FullStrings.AddRange(MissingStrings);
                FullStrings.Sort();

                ScenarioStrings = FullStrings.ToArray();
            } catch (Exception) {
                return;
            }
            ScenarioFile[] ScenarioBlocks = Block(ScenarioStrings);

            byte[] Scenario = System.IO.File.ReadAllBytes(ScenarioFilename);

            byte[] TextStartBytes = { Scenario[0x0F], Scenario[0x0E], Scenario[0x0D], Scenario[0x0C] };
            int    Max            = BitConverter.ToInt32(TextStartBytes, 0);

            for (int i = 0; i < ScenarioBlocks.Length; i++)
            {
                ScenarioBlocks[i].PointerArray = GetLocation(Scenario, Max, ScenarioBlocks[i].Pointer);
            }


            List <byte> bytes = new List <byte>(ScenarioBlocks.Length * 1000);

            byte[] PointerString   = Util.StringToBytes("\0\r\nPOINTER @ 0x");
            byte[] JpnNameString   = Util.StringToBytes("\0\r\nJPN NAME @ 0x0:");
            byte[] JpnTextString   = Util.StringToBytes("\0\r\nJPN TEXT @ 0x0:");
            byte[] EngNameString   = Util.StringToBytes("\0\r\nENG NAME @ 0x0:");
            byte[] EngTextString   = Util.StringToBytes("\0\r\nENG TEXT @ 0x0:");
            byte[] DelimiterString = Util.StringToBytes("\0\r\n----------------");


            List <String> EmptyStuff = new List <string>();


            foreach (ScenarioFile B in ScenarioBlocks)
            {
                if (String.IsNullOrEmpty(B.Text) && String.IsNullOrEmpty(B.Name))
                {
                    continue;
                }

                if (B.PointerArray.Length == 0)
                {
                    EmptyStuff.Add("No Pointer found for: " + B.Name + " / " + B.Text);
                    continue;
                }

                foreach (int point in B.PointerArray)
                {
                    if (point == -1)
                    {
                        continue;
                    }
                    bytes.AddRange(PointerString);
                    bytes.AddRange(Util.StringToBytes(point.ToString("x")));
                    bytes.AddRange(JpnNameString);
                    bytes.AddRange(Util.StringToBytes(B.Name));
                    bytes.AddRange(JpnTextString);
                    bytes.AddRange(Util.StringToBytes(B.Text));
                    bytes.AddRange(EngNameString);
                    bytes.AddRange(Util.StringToBytes(B.Name));
                    bytes.AddRange(EngTextString);
                    bytes.AddRange(Util.StringToBytes(B.Text));
                    bytes.AddRange(DelimiterString);
                }
            }
            bytes.Add(0x00);
            bytes.Add(0x0D);
            bytes.Add(0x0A);

            System.IO.File.WriteAllBytes(TxtFilename, bytes.ToArray());

            if (updateGracesEnglish)
            {
                SQLiteConnection  connectionGracesEnglish  = null;
                SQLiteTransaction transactionGracesEnglish = null;
                connectionGracesEnglish = new SQLiteConnection("Data Source=db/GracesEnglish");
                connectionGracesEnglish.Open();
                transactionGracesEnglish = connectionGracesEnglish.BeginTransaction();

                foreach (ScenarioFile entry in ScenarioBlocks)
                {
                    if (entry.PointerArray.Length == 0)
                    {
                        continue;
                    }

                    ReadOriginalStrings(Scenario, entry);

                    UpdateGracesJapanese(transactionGracesEnglish, entry.StringIdName, entry.OriginalNameEng, 0);
                    UpdateGracesJapanese(transactionGracesEnglish, entry.StringIdText, entry.OriginalTextEng, 0);
                }

                transactionGracesEnglish.Commit();
                connectionGracesEnglish.Close();
            }

            try {
                if (EmptyStuff.Count > 0)
                {
                    StreamWriter sw = new StreamWriter("scenariolog.log", true, Util.ShiftJISEncoding);
                    sw.WriteLine("In File " + FileNumber + " (" + ScenarioFilename + "):");
                    foreach (String s in EmptyStuff)
                    {
                        sw.WriteLine(s);
                    }
                    sw.WriteLine();
                    sw.WriteLine();

                    sw.Close();
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed writing log: " + ex.ToString());
            }

            return;
        }
예제 #25
0
        public void Insert(params object[] objs)
        {
            if (objs == null &&
                objs.Length == 0)
            {
                return;
            }

            this.ExecureCore(() =>
            {
                using (SQLiteConnection connection = ConnectionHelper.GetDbConnection(this.DBKeywords))
                {
                    connection.Open();

                    using (SQLiteTransaction tran = connection.BeginTransaction())
                    {
                        bool flag = false;
                        try
                        {
                            foreach (object item in objs)
                            {
                                if (item == null)
                                {
                                    continue;
                                }

                                flag = true;

                                IEnumerable ienu = item as IEnumerable;
                                if (ienu != null)
                                {
                                    List <object> temp = new List <object>();
                                    foreach (var inner in ienu)
                                    {
                                        if (inner != null)
                                        {
                                            temp.Add(inner);
                                        }
                                    }
                                    if (temp.Count > 0)
                                    {
                                        connection.Execute(StandardSQLGenerate.GetInsertSQL(temp[0]), temp, tran);
                                    }
                                }
                                else
                                {
                                    connection.Execute(StandardSQLGenerate.GetInsertSQL(item), item, tran);
                                }
                            }

                            if (flag)
                            {
                                tran.Commit();
                            }
                        }
                        catch (Exception e)
                        {
                            if (flag)
                            {
                                tran.Rollback();
                            }
                            throw e;
                        }
                    }
                }
            });
        }
예제 #26
0
        public static ScenarioFile[] GetSQL(String ConnectionString, int FileNumber, String GracesJapaneseConnectionString,
                                            bool DumpIdentifyerStrings, bool ForceJapaneseDump, bool DumpDebug, bool SortByPointerRef)
        {
            List <ScenarioFile> ScenarioFiles = new List <ScenarioFile>();

            SQLiteConnection Connection = new SQLiteConnection(ConnectionString);

            Connection.Open();

            using (SQLiteTransaction Transaction = Connection.BeginTransaction())
                using (SQLiteCommand Command = new SQLiteCommand(Connection)) {
                    if (FileNumber == -1)
                    {
                        Command.CommandText = "SELECT english, PointerRef, StringID";
                        if (DumpIdentifyerStrings)
                        {
                            Command.CommandText += ", IdentifyString";
                        }
                        Command.CommandText += " FROM Text"
                                               + (DumpDebug ? "" : " WHERE status != -1")
                                               + " ORDER BY " + (SortByPointerRef ? "PointerRef" : "ID");
                    }
                    else
                    {
                        // for VScenarioMissing
                        Command.CommandText = "SELECT english, PointerRef, StringID FROM Text WHERE"
                                              + (DumpDebug ? "" : " status != -1 AND")
                                              + " OriginalFile = " + FileNumber.ToString()
                                              + " ORDER BY " + (SortByPointerRef ? "PointerRef" : "ID");
                    }


                    SQLiteDataReader r = Command.ExecuteReader();
                    while (r.Read())
                    {
                        String SQLText;

                        try {
                            SQLText = r.GetString(0).Replace("''", "'");
                        } catch (System.InvalidCastException) {
                            SQLText = null;
                        }

                        int PointerRef = r.GetInt32(1);
                        int StringID   = r.GetInt32(2);

                        String IdentifyString = null;

                        if (DumpIdentifyerStrings)
                        {
                            try {
                                IdentifyString = r.GetString(3);
                            } catch (System.InvalidCastException) {
                                IdentifyString = null;
                            }
                        }

                        ScenarioFile sc = new ScenarioFile();

                        if (ForceJapaneseDump || String.IsNullOrEmpty(SQLText))
                        {
                            sc.Text = GetJapanese(GracesJapaneseConnectionString, StringID);
                        }
                        else
                        {
                            sc.Text = SQLText;
                        }

                        sc.Pointer          = PointerRef;
                        sc.IdentifyerString = IdentifyString;

                        ScenarioFiles.Add(sc);
                    }

                    Transaction.Rollback();
                }
            return(ScenarioFiles.ToArray());
        }
 /// <summary>
 ///     A SQLiteConnection extension method that executes the data table operation.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="cmdText">The command text.</param>
 /// <param name="transaction">The transaction.</param>
 /// <returns>A DataTable.</returns>
 public static DataTable ExecuteDataTable(this SQLiteConnection @this, string cmdText, SQLiteTransaction transaction)
 {
     return(@this.ExecuteDataTable(cmdText, null, CommandType.Text, transaction));
 }
예제 #28
0
        public bool ImportCml(string cmlFile, SQLiteTransaction transaction, bool calculateProperties = false)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            bool result = false;

            try
            {
                Model model = null;

                if (cmlFile.StartsWith("<"))
                {
                    model = _cmlConverter.Import(cmlFile);
                }
                if (cmlFile.Contains("M  END"))
                {
                    model = _sdFileConverter.Import(cmlFile);
                }

                if (model != null)
                {
                    var outcome = model.EnsureBondLength(Globals.Chem4WordV3.SystemOptions.BondLength, false);
                    if (Globals.Chem4WordV3.SystemOptions.RemoveExplicitHydrogensOnImportFromLibrary)
                    {
                        model.RemoveExplicitHydrogens();
                    }
                    if (!string.IsNullOrEmpty(outcome))
                    {
                        Globals.Chem4WordV3.Telemetry.Write(module, "Information", outcome);
                    }

                    if (model.TotalAtomsCount > 0)
                    {
                        if (calculateProperties)
                        {
                            var newMolecules = model.GetAllMolecules();
                            ChemistryHelper.CalculateProperties(newMolecules);
                        }

                        model.CustomXmlPartGuid = "";

                        string chemicalName = model.ConciseFormula;
                        var    mol          = model.Molecules.Values.First();
                        if (mol.Names.Count > 0)
                        {
                            foreach (var name in mol.Names)
                            {
                                long temp;
                                if (!long.TryParse(name.Value, out temp))
                                {
                                    chemicalName = name.Value;
                                    break;
                                }
                            }
                        }

                        var conn = transaction.Connection;

                        var id = AddChemistry(conn, model, chemicalName, model.ConciseFormula);
                        foreach (var name in mol.Names)
                        {
                            AddChemicalName(conn, id, name.Value, name.FullType);
                        }

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex))
                {
                    form.ShowDialog();
                }
            }

            return(result);
        }
예제 #29
0
 private static void AssertDataCount(long expectedCount, SQLiteConnection conn, SQLiteTransaction tran)
 {
     Assert.AreEqual(
         SqlLiteDatabase.ExecuteScalar("select count(*) from TEST_TABLE", conn, tran),
         expectedCount);
 }
예제 #30
0
        /// <summary>
        /// 宗教した場合に呼ばれる
        /// </summary>
        /// <param name="win"></param>
        public void OnGameFinished(Result result)
        {
            // sfenファイルへの書き込み
            var sfen = "startpos moves " + string.Join(" ", Moves.Select(x => x.Best)) + "\n";

            lock (WriteResultLock)
            {
                File.AppendAllText(sfenFilePath, sfen);

                // sqlite3ファイルへの書き込み
                int gameId = Interlocked.Increment(ref globalGameId);
                int winner;
                switch (result)
                {
                case Result.Win:
                    winner = Turn;
                    break;

                case Result.Lose:
                    winner = Turn ^ 1;
                    break;

                case Result.Draw:
                    winner = 2;
                    break;

                default:
                    throw new Exception($"Invalid Result type. result={result}");
                }

                var builder = new SQLiteConnectionStringBuilder {
                    DataSource = sqlite3FilePath
                };
                using (var connection = new SQLiteConnection(builder.ToString()))
                {
                    connection.Open();
                    SQLiteTransaction transaction = connection.BeginTransaction();
                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = @"
CREATE TABLE IF NOT EXISTS game (
    id INTEGER PRIMARY KEY ASC,
    winner INTEGER
);
";
                        command.ExecuteNonQuery();
                    }

                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText =
                            @"CREATE TABLE IF NOT EXISTS move (
    game_id INTEGER,
    play INTEGER,
    best TEXT,
    next TEXT,
    value INTEGER,
    depth INTEGER,
    book INTEGER
);
";
                        command.ExecuteNonQuery();
                    }

                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText =
                            @"CREATE INDEX IF NOT EXISTS move_game_id_index ON move (
    game_id
);
";
                        command.ExecuteNonQuery();
                    }

                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText =
                            @"
    INSERT INTO game (id, winner)
    VALUES ($id, $winner)
";
                        command.Parameters.AddWithValue("$id", gameId);
                        command.Parameters.AddWithValue("$winner", winner);
                        command.ExecuteNonQuery();
                    }

                    for (int play = 0; play < Moves.Count; ++play)
                    {
                        var move = Moves[play];

                        using (var command = connection.CreateCommand())
                        {
                            command.CommandText =
                                @"
INSERT INTO move (game_id, play, best, next, value, depth, book)
VALUES ($game_id, $play, $best, $next, $value, $depth, $book)
";
                            command.Parameters.AddWithValue("$game_id", gameId);
                            command.Parameters.AddWithValue("$play", play);
                            command.Parameters.AddWithValue("$best", move.Best);
                            command.Parameters.AddWithValue("$next", move.Next);
                            command.Parameters.AddWithValue("$value", move.Value);
                            command.Parameters.AddWithValue("$depth", move.Depth);
                            command.Parameters.AddWithValue("$book", move.Book);
                            command.ExecuteNonQuery();
                        }
                    }

                    transaction.Commit();
                }
            }

            InitialTurn ^= 1;
            Running      = false;
        }
예제 #31
0
 public static bool ExistsByLogin(string login, int id, Connection connection, SQLiteTransaction transaction)
 {
     using (var dao = new UsuarioDAO(connection))
     {
         return(dao.ExistsByLogin(login, id, transaction));
     }
 }
예제 #32
0
 public static int Execute(SQLiteConnection conn, string sql, object param = null, SQLiteTransaction trans = null, int?commandTimeout = null, CommandType?commandType = null)
 {
     return(conn.Execute(sql, param, trans, commandTimeout, commandType));
 }
예제 #33
0
        public bool Inserir(string senha, string confirmacaoSenha, out string mensagem, Connection connection, SQLiteTransaction transaction)
        {
            if (!IsValid(out mensagem, connection, transaction))
            {
                return(false);
            }

            if (string.IsNullOrEmpty(senha))
            {
                mensagem = "A senha do usuário é obrigatória!";
                return(false);
            }

            if (string.IsNullOrEmpty(confirmacaoSenha))
            {
                mensagem = "A confirmação de senha do usuário é obrigatória!";
                return(false);
            }

            if (!string.Equals(senha, confirmacaoSenha, StringComparison.InvariantCulture))
            {
                mensagem = "As senhas não coincidem!";
                return(false);
            }

            using (var dao = new UsuarioDAO(connection))
            {
                return(dao.Insert(this, senha, transaction) == 1);
            }
        }
예제 #34
0
 /// <summary>
 /// 事务查询
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="conn"></param>
 /// <param name="sql"></param>
 /// <param name="param"></param>
 /// <param name="trans"></param>
 /// <returns></returns>
 public static IEnumerable <T> Query <T>(SQLiteConnection conn, string sql, object param = null, SQLiteTransaction trans = null)
 {
     return(conn.Query <T>(sql, param, trans));
 }
 public override void Dispose()
 {
     transaction.Dispose();
     connection.Dispose();
     transaction = null;
     connection = null;
 }
예제 #36
0
        public static int UpdateUserList(DataTable dt)
        {
            int result = 0;

            try
            {
                using (SQLiteConnection conn = new SQLiteConnection("data source=" + System.IO.Path.Combine(Program.Config["SavesPath"], Program.USER_DB)))
                {
                    conn.Open();
                    string sql = string.Empty;
                    using (SQLiteTransaction trans = conn.BeginTransaction())
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            switch (dr.RowState)
                            {
                            case DataRowState.Added:
                                sql = "insert into TB_Users(UserID,PWD,Created) values(@UserID,@PWD,@Created)";
                                using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                                {
                                    cmd.Parameters.AddWithValue("@UserID", dr["UserID"].ToString());
                                    cmd.Parameters.AddWithValue("@PWD", dr["PWD"].ToString());
                                    cmd.Parameters.AddWithValue("@Created", Convert.ToDateTime(dr["Created"]));
                                    result += cmd.ExecuteNonQuery();
                                }
                                break;

                            case DataRowState.Modified:
                                sql = "update TB_Users set UserID=@UserID,PWD=@PWD where RowID=@RowID";
                                using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                                {
                                    cmd.Parameters.AddWithValue("@UserID", dr["UserID"].ToString());
                                    cmd.Parameters.AddWithValue("@PWD", dr["PWD"].ToString());
                                    cmd.Parameters.AddWithValue("@RowID", Convert.ToInt64(dr["RowID"]));
                                    result += cmd.ExecuteNonQuery();
                                }
                                break;

                            case DataRowState.Deleted:
                                sql = "delete from TB_Users where RowID=@RowID";
                                dr.RejectChanges();
                                using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                                {
                                    cmd.Parameters.AddWithValue("@RowID", Convert.ToInt64(dr["RowID"]));
                                    result += cmd.ExecuteNonQuery();
                                }
                                break;
                            }
                        }
                        trans.Commit();
                    }
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(string.Format("無法新增或修改使用者帳號資料!!\n\n原因:\n{0}", ex.Message), System.Windows.Forms.Application.ProductName, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                result = 0;
            }
            return(result);
        }
예제 #37
0
파일: Form1.cs 프로젝트: CplSyx/NiceMon
        private async void getNiceHashStats()
        {
            log("Starting update.");
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(urlParametersWithKey).Result;  // Blocking call!

            if (response.IsSuccessStatusCode)
            {
                try
                {
                    log("Obtaining data...");
                    string s = await response.Content.ReadAsStringAsync();

                    if (s.IndexOf("You have reached your API request quota limit") >= 0)
                    {
                        log("API Quota limit exceeded. Skipping.");
                        return;
                    }

                    StatsProviderEx.JsonResult jsonOutput = JsonConvert.DeserializeObject <StatsProviderEx.JsonResult>(s);

                    string json = JsonConvert.SerializeObject(jsonOutput);

                    string jsonFormatted = Newtonsoft.Json.Linq.JValue.Parse(json).ToString(Formatting.Indented);
                    log("Received data for NiceHash wallet address " + jsonOutput.result.addr);

                    log("Processing data...");
                    Dictionary <int, decimal> APIsnapshot = new Dictionary <int, decimal>();
                    for (int i = 0; i < jsonOutput.result.past.Count; i++)
                    {
                        for (int j = 0; j < jsonOutput.result.past[i].data.Count; j++)
                        {
                            try
                            {
                                APIsnapshot.Add(Int32.Parse(jsonOutput.result.past[i].data[j][0].ToString()), decimal.Parse(jsonOutput.result.past[i].data[j][2].ToString()));
                            }
                            catch (System.ArgumentException e)
                            {
                                if (e.Message.IndexOf("same key") >= 0)
                                {
                                    APIsnapshot[Int32.Parse(jsonOutput.result.past[i].data[j][0].ToString())] = APIsnapshot[Int32.Parse(jsonOutput.result.past[i].data[j][0].ToString())] + decimal.Parse(jsonOutput.result.past[i].data[j][2].ToString());
                                }
                                else
                                {
                                    log(e.Message);
                                }
                            }
                        }
                    }

                    dbCon.Open();
                    Dictionary <int, decimal> existingProfitTable = new Dictionary <int, decimal>();
                    int Limit30Days = ((int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds - 1513282869) / 300;
                    using (SQLiteCommand cmd = new SQLiteCommand("SELECT timestamp, btc FROM profit WHERE address='" + nicehashWalletAddress + "' AND timestamp > '" + Limit30Days + "'", dbCon))
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                existingProfitTable[(int)reader["timestamp"]] = (decimal)reader["btc"];
                            }
                        }
                    }

                    var itemsToUpdate = APIsnapshot.Except(existingProfitTable);

                    log("Complete.");

                    /*foreach (KeyValuePair<int, decimal> kvp in snapshot)
                     * {
                     *  log(kvp.Key + " : " + kvp.Value);
                     * }*/
                    log("Updating database...");


                    int k = 0;
                    using (SQLiteCommand cmd = new SQLiteCommand(dbCon))
                    {
                        using (SQLiteTransaction transaction = dbCon.BeginTransaction())
                        {
                            foreach (KeyValuePair <int, decimal> kvp in itemsToUpdate)
                            {
                                cmd.CommandText = "INSERT INTO profit (address, timestamp, btc) VALUES ('" + nicehashWalletAddress + "', '" + kvp.Key + "', '" + kvp.Value + "');";
                                cmd.ExecuteNonQuery();
                                k++;
                            }

                            transaction.Commit();
                        }
                    }
                    dbCon.Close();
                    log("Done. Inserted " + k + " rows.");

                    latestData = new SortedDictionary <int, decimal>(existingProfitTable);
                }
                catch (Exception ex)
                {
                    log("Error.");
                    log(ex.Message);
                    log(ex.ToString());
                    log(ex.StackTrace);
                }
            }
            else
            {
                log("Error connecting to API.");
                log((int)response.StatusCode + " : " + response.ReasonPhrase);
            }

            updateAverageProfit();
            updateTargetDate();

            updateProfitChart();

            log("Update complete.");
        }
예제 #38
0
            /// <summary>
            /// Executes the dataset with Transaction and object array of parameter values.
            /// </summary>
            /// <param name="transaction">SQLiteTransaction. Transaction consists of Connection, Transaction,    /// and Command, all of which must be created prior to making this method call. </param>
            /// <param name="commandText">Command text.</param>
            /// <param name="commandParameters">object[] array of parameter values.</param>
            /// <returns>DataSet</returns>
            /// <remarks>user must examine Transaction Object and handle transaction.connection .Close, etc.</remarks>
            public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, object[] commandParameters)
            {
                if (transaction == null) throw new ArgumentNullException("transaction");
                if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed,                                                          please provide an open transaction.", "transaction");
                IDbCommand cmd = transaction.Connection.CreateCommand();
                cmd.CommandText = commandText;
                AttachParameters((SQLiteCommand)cmd, cmd.CommandText, commandParameters);
                if (transaction.Connection.State == ConnectionState.Closed)
                    transaction.Connection.Open();

                DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
                return ds;
            }