public void Initialise(EngineRoomServiceDB erdb)
        {
            DBRow row = erdb.GetLatestEvent(EngineRoomServiceDB.LogEventType.ON, ID);

            if (row != null)
            {
                LastOn = row.GetDateTime("created");
            }
            row = erdb.GetLatestEvent(EngineRoomServiceDB.LogEventType.OFF, ID);
            if (row != null)
            {
                LastOff = row.GetDateTime("created");
            }

            DBRow enabled  = erdb.GetLatestEvent(EngineRoomServiceDB.LogEventType.ENABLE, ID);
            DBRow disabled = erdb.GetLatestEvent(EngineRoomServiceDB.LogEventType.DISABLE, ID);

            bool enable = true;

            if (disabled != null)
            {
                enable = enabled == null ? false : enabled.GetDateTime("created").Ticks > disabled.GetDateTime("created").Ticks;
            }
            else if (enabled != null)
            {
                enable = true;
            }
            Enable(enable);

            String desc = String.Format("Initialised engine {0} ... engine is {1}", ID, Enabled ? "enabled" : "disabled");

            erdb.LogEvent(EngineRoomServiceDB.LogEventType.INITIALISE, ID, desc);
        }
示例#2
0
 /*
  * Insert the previously given values into the db table.
  * A warning will be printed and no data added if the given data doesn't
  * fit the db file's structure.
  */
 public override void Execute()
 {
     // insert always into packed files at the save to file
     foreach (PackedFile packed in PackedFiles)
     {
         // we'll read from packed, but that is in the source pack;
         // get or create the db file in the target pack
         DBFile targetFile = GetTargetFile(packed);
         foreach (RowValues insertValues in Source.Values)
         {
             if (targetFile.CurrentType.Fields.Count == insertValues.Count)
             {
                 DBRow newRow = targetFile.GetNewEntry();
                 for (int i = 0; i < newRow.Count; i++)
                 {
                     newRow[i].Value = insertValues[i];
                 }
                 targetFile.Entries.Add(newRow);
             }
             else
             {
                 Console.WriteLine("Cannot insert: was given {0} values, expecting {1} in {2}",
                                   insertValues.Count, targetFile.CurrentType.Fields.Count, packed.FullPath);
                 Console.WriteLine("Values: {0}", string.Join(",", insertValues));
             }
         }
         // encode and store in target pack
         PackedFile newPacked = new PackedFile(packed.FullPath, false);
         newPacked.Data = PackedFileDbCodec.GetCodec(newPacked).Encode(targetFile);
         SaveTo.Add(newPacked, true);
     }
 }
示例#3
0
        // creates a list of field values from the given type.
        // stream needs to be positioned at the beginning of the entry.
        private DBRow ReadFields(BinaryReader reader, TypeInfo ttype, bool skipHeader = true)
        {
            if (!skipHeader)
            {
                readHeader(reader);
            }
            List <FieldInstance> entry = new List <FieldInstance>();

            for (int i = 0; i < ttype.Fields.Count; ++i)
            {
                FieldInfo field = ttype.Fields[i];

                FieldInstance instance = null;
                try {
                    instance = field.CreateInstance();
                    instance.Decode(reader);
                    entry.Add(instance);
                } catch (Exception x) {
                    throw new InvalidDataException(string.Format
                                                       ("Failed to read field {0}/{1}, type {3} ({2})", i, ttype.Fields.Count, x.Message, instance.Info.TypeName));
                }
            }
            DBRow result = new DBRow(ttype, entry);

            return(result);
        }
        public ActionResult DeleteConfirmed(int id)
        {
            DBRow dBRow = db.DBRows.Find(id);

            db.DBRows.Remove(dBRow);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public DBRow GetLatestEvent(LogEventType currentEvent, LogEventType preceedingEvent, String source)
        {
            DBRow pe      = GetLatestEvent(preceedingEvent, source);
            long  limitId = pe == null ? -1 : pe.ID;
            DBRow ce      = GetFirstEvent(currentEvent, source, limitId);

            return(ce);
        }
 public ActionResult Edit([Bind(Include = "ID,Number,Content,DBRowID")] DBRow dBRow)
 {
     if (ModelState.IsValid)
     {
         db.Entry(dBRow).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(dBRow));
 }
示例#7
0
        bool SameData(DBRow row1, DBRow row2)
        {
            bool result = row1.Count == row2.Count;

            for (int i = 0; result && i < row1.Count; i++)
            {
                result = row1[i].Value.Equals(row2[i].Value);
            }
            return(result);
        }
        public ActionResult Create([Bind(Include = "ID,Number,Content,DBRowID")] DBRow dBRow)
        {
            if (ModelState.IsValid)
            {
                db.DBRows.Add(dBRow);
                db.SaveChanges();
                return(PartialView("_Table", db.DBRows.ToList()));
            }

            return(PartialView(dBRow));
        }
        public long LogState(String stateSource, String stateName, Object state, String description = null)
        {
            var newRow = new DBRow();

            newRow["state_source"] = stateSource;
            newRow["state_name"]   = stateName;
            if (description != null)
            {
                newRow["state_description"] = description;
            }
            newRow["state"] = state;
            return(Insert("state_log", newRow));
        }
        public long LogEvent(LogEventType logEvent, String source, String description = null)
        {
            var newRow = new DBRow();

            newRow["event_type"]   = logEvent.ToString();
            newRow["event_source"] = source;
            if (description != null)
            {
                newRow["event_description"] = description;
            }

            return(Insert("event_log", newRow));
        }
示例#11
0
        public bool ContainsRow(DBRow checkRow)
        {
            bool result = false;

            foreach (DBRow row in gameDbFile.Entries)
            {
                if (SameData(row, checkRow))
                {
                    result = true;
                    break;
                }
            }
            return(result);
        }
        // GET: DBRows/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DBRow dBRow = db.DBRows.Find(id);

            if (dBRow == null)
            {
                return(HttpNotFound());
            }
            return(View(dBRow));
        }
示例#13
0
        private static Guid FindGroupID(DBTable gruppeTable, DBRunner runner, ISQLExecuter executer, DBConnection connection)
        {
            SQL_SelectStatement sqlSelect = new SQL_SelectStatement();

            sqlSelect.AddColumn(gruppeTable, "uiGruppeID");
            sqlSelect.AddCriteria(new Crit_MatchCriteria(gruppeTable, "txNavn", MatchType.Equal, "Dødsattester midlertidig opbevaring"));
            DBRow row = runner.SelectAndReturnFirstRow(executer, connection, sqlSelect);

            if (row == null)
            {
                return(Guid.Empty);
            }

            return((Guid)row["uiGruppeID"]);
        }
示例#14
0
        private static Guid FindPluginID(DBTable pluginsTable, DBRunner runner, ISQLExecuter executer, DBConnection connection)
        {
            SQL_SelectStatement sqlSelect = new SQL_SelectStatement();

            sqlSelect.AddColumn(pluginsTable, "uiPluginID");
            sqlSelect.AddCriteria(new Crit_MatchCriteria(pluginsTable, "txNavn", MatchType.Equal, "dk.hob.ei.mortality.Plugin"));
            DBRow row = runner.SelectAndReturnFirstRow(executer, connection, sqlSelect);

            if (row == null)
            {
                return(Guid.Empty);
            }

            return((Guid)row["uiPluginID"]);
        }
示例#15
0
        public void CompareTablesTest()
        {
            DBTable lTable = new DBTable();
            DBTable rTable = new DBTable();

            lTable.AddField("field", "String");
            rTable.AddField("field", "String");
            EString el  = new EString("Sample");
            DBRow   row = new DBRow();

            row.AddElement(el);
            lTable.AddRow(row);
            el  = new EString("Sample");
            row = new DBRow();
            row.AddElement(el);
            rTable.AddRow(row);
            Assert.AreEqual(lTable, rTable);
        }
示例#16
0
        public void JoinTablesTest()
        {
            // Create tables
            DBTable leftTable = new DBTable();

            leftTable.AddField("Name", "String");
            leftTable.AddField("ValX", "Integer");
            DBTable rightTable = new DBTable();

            rightTable.AddField("Name", "String");
            rightTable.AddField("ValY", "Integer");
            DBTable joinedTable = new DBTable();

            joinedTable.AddField("Name", "String");
            joinedTable.AddField("ValX", "Integer");
            joinedTable.AddField("ValY", "Integer");
            // Fill tables
            DBRow row = new DBRow();

            row.AddElement(new EString("A"));
            row.AddElement(new EInteger(1));
            leftTable.AddRow(row);
            row = new DBRow();
            row.AddElement(new EString("B"));
            row.AddElement(new EInteger(2));
            leftTable.AddRow(row);
            row = new DBRow();
            row.AddElement(new EString("B"));
            row.AddElement(new EInteger(3));
            rightTable.AddRow(row);
            row = new DBRow();
            row.AddElement(new EString("C"));
            row.AddElement(new EInteger(4));
            rightTable.AddRow(row);
            row = new DBRow();
            row.AddElement(new EString("B"));
            row.AddElement(new EInteger(2));
            row.AddElement(new EInteger(3));
            joinedTable.AddRow(row);
            Database db = new Database();

            db.JoinTables(leftTable, 0, rightTable, 0);
            Assert.AreEqual(joinedTable, db.GetTable(0));
        }
示例#17
0
        protected override ArduinoCommand CreateCommand(string deviceName, DBRow row)
        {
            var command = new ArduinoCommand((String)row["command_alias"]);

            command.Type = ArduinoCommand.CommandType.SEND;
            switch (Encoding)
            {
            case IREncoding.HEX:
                command.AddArgument(Convert.ToInt64((String)row["command"], 16));
                break;

            case IREncoding.LONG:
                command.AddArgument(Convert.ToInt64((String)row["command"]));
                break;
            }
            command.AddArgument(Convert.ToUInt16(row["bits"]));
            command.AddArgument(Convert.ToInt16(row["protocol"]));
            return(command);
        }
示例#18
0
        private void cloneRowsButton_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectedRows = dataGridView.SelectedRows;

            if (selectedRows.Count != 0)
            {
                foreach (DataGridViewRow row in selectedRows)
                {
                    DBRow toCopy = EditedFile.Entries[row.Index];
                    var   copy   = new DBRow(EditedFile.CurrentType, toCopy);
                    createRow(copy, row.Index);
                }
            }
            else
            {
                MessageBox.Show("Please select the Row(s) to Clone!", "Please select Rows",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
示例#19
0
        public void SearchTest()
        {
            DBTable searchTable = new DBTable();
            DBTable resultTable = new DBTable();

            searchTable.AddField("field", "String");
            resultTable.AddField("field", "String");
            DBRow   row = new DBRow();
            EString el  = new EString("RISC");

            row.AddElement(el);
            searchTable.AddRow(row);
            resultTable.AddRow(row);
            row = new DBRow();
            el  = new EString("CISC");
            row.AddElement(el);
            searchTable.AddRow(row);
            Assert.AreEqual(resultTable, searchTable.Search("R", "String"));
        }
示例#20
0
        /// <summary>
        /// Check whether database xml from communication has correct version.
        /// </summary>
        /// <param name="commSnapshot">The snapshot from other branch.</param>
        /// <param name="dbSnapshot">The snapshot created from database.</param>
        /// <returns><c>true</c> if database xml from communication has correct version; otherwise, <c>false</c>.</returns>
        public bool ValidateVersion(DBRow commSnapshot, DBXml dbSnapshot)
        {
            if (dbSnapshot != null &&
                commSnapshot.HasAction == false && //only delete action is valid
                commSnapshot.PreviousVersion.Equals(dbSnapshot.Table(MainObjectTag).FirstRow().Element("version").Value,
                                                    StringComparison.OrdinalIgnoreCase) == false)
            {
                return(false);
            }
            else if (dbSnapshot != null &&
                     commSnapshot.HasAction == true && //only delete action is valid
                     commSnapshot.Element("version").Value.Equals(dbSnapshot.Table(MainObjectTag).FirstRow().Element("version").Value,
                                                                  StringComparison.OrdinalIgnoreCase) == false)
            {
                return(false);
            }

            else
            {
                return(true);
            }
        }
        public void Initialise(EngineRoomServiceDB erdb)
        {
            DBRow enabled  = erdb.GetLatestEvent(EngineRoomServiceDB.LogEventType.ENABLE, ID);
            DBRow disabled = erdb.GetLatestEvent(EngineRoomServiceDB.LogEventType.DISABLE, ID);

            bool enable = true;

            if (disabled != null)
            {
                enable = enabled == null ? false : enabled.GetDateTime("created").Ticks > disabled.GetDateTime("created").Ticks;
            }
            else if (enabled != null)
            {
                enable = true;
            }
            Enable(enable);

            _initialisedAt = DateTime.Now;

            String desc = String.Format("Initialised {0} water tanks ... tanks are {1}", Tanks.Count, Enabled ? "enabled" : "disabled");

            erdb.LogEvent(EngineRoomServiceDB.LogEventType.INITIALISE, ID, desc);
        }
示例#22
0
        private static void FindDocuments(DBTable pluginsTable, DBTable gruppePostkasseTable, DBTable revisionssporTable, DBRunner runner, ISQLExecuter executer, DBConnection connection, String plugin, params String[] tables)
        {
            Output("");
            Output("Find plugin ID for " + plugin);

            SQL_SelectStatement sqlSelect = new SQL_SelectStatement();

            sqlSelect.AddColumn(pluginsTable, "uiPluginID");
            sqlSelect.AddCriteria(new Crit_MatchCriteria(pluginsTable, "txNavn", MatchType.Equal, plugin));
            DBRow row = runner.SelectAndReturnFirstRow(executer, connection, sqlSelect);

            if (row == null)
            {
                throw new Exception("Couldn't find plugin ID");
            }

            Guid pluginID = (Guid)row["uiPluginID"];

            // Find all the document IDs
            Dictionary <Guid, Object> documentIDs = new Dictionary <Guid, Object>();

            Output("Find document IDs for " + gruppePostkasseTable.TableName);
            sqlSelect          = new SQL_SelectStatement();
            sqlSelect.Distinct = true;
            sqlSelect.AddColumn(gruppePostkasseTable, "uiSkemaID");
            sqlSelect.AddCriteria(new Crit_MatchCriteria(gruppePostkasseTable, "uiPluginID", MatchType.Equal, pluginID));
            AddIDs(sqlSelect, runner, executer, connection, documentIDs);

            foreach (String tableName in tables)
            {
                Output("Find document IDs for " + tableName);
                DBTable table = pluginsTable.Database.AddTable("EISST", tableName);
                table.AddColumn("uiSkemaID", ColumnType.Guid, ColumnFlag.None);

                sqlSelect = new SQL_SelectStatement();
                sqlSelect.AddColumn(table, "uiSkemaID");
                AddIDs(sqlSelect, runner, executer, connection, documentIDs);
            }

            Output("Check the revisionsspor to see which documents are missing");
            sqlSelect          = new SQL_SelectStatement();
            sqlSelect.Distinct = true;
            sqlSelect.AddColumn(revisionssporTable, "uiSkemaID");
            sqlSelect.AddCriteria(new Crit_MatchCriteria(revisionssporTable, "uiPluginID", MatchType.Equal, pluginID));
            sqlSelect.AddCriteria(new Crit_MatchCriteria(revisionssporTable, "iType", MatchType.Equal, (short)0));
            sqlSelect.AddCriteria(new Crit_MatchCriteria(revisionssporTable, "uiSkemaID", MatchType.IsNotNull));
            sqlSelect.AddSort(revisionssporTable, "uiSkemaID", Order.Ascending);

            using (DBReader reader = runner.GetReader(executer, connection, sqlSelect))
            {
                while ((row = reader.GetNextRow()) != null)
                {
                    Guid id = (Guid)row["uiSkemaID"];

                    if (!documentIDs.ContainsKey(id))
                    {
                        Output(id.ToString("B").ToUpper());
                    }
                }
            }
        }
示例#23
0
 abstract protected ArduinoCommand CreateCommand(String deviceName, DBRow row);
示例#24
0
 //Set values - Prevents Content Panel changes from causing database updates
 public void SetDisplayDB(DBRow query)
 {
     DisplayDB.selectedEntry.Date = query.Date;
     DisplayDB.selectedEntry.TimeIn = query.TimeIn;
     DisplayDB.selectedEntry.TimeOut = query.TimeOut;
     DisplayDB.selectedEntry.LunchIn = query.LunchIn;
     DisplayDB.selectedEntry.LunchOut = query.LunchOut;
     DisplayDB.selectedEntry.ClockedTime = query.ClockedTime;
 }
示例#25
0
        //Update the already present entry in the database
        public void UpdateRowInDb(DBRow newrow)
        {
            ChangeSet cs = database.GetChangeSet(); //debug
            DBRow query = QueryRowInDb(newrow.Date);

            query.TimeIn = newrow.TimeIn;
            query.TimeOut = newrow.TimeOut;
            query.LunchIn = newrow.LunchIn;
            query.LunchOut = newrow.LunchOut;
            query.ClockedTime = newrow.ClockedTime;

            cs = database.GetChangeSet(); //debug
            database.SubmitChanges();

            cs = database.GetChangeSet(); //debug
        }
示例#26
0
 public CurrentDisplay()
 {
     selectedEntry = new DBRow();
     calculationErrorMessage = "₪";
 }
示例#27
0
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.Out.WriteLine("usage: dbcorrect [-cleanup] <packfile>");
                return;
            }
            bool   cleanup        = false;
            String inPackFileName = args[0];

            if (args.Length == 2)
            {
                cleanup = "-cleanup".Equals(args[0]);
                Console.WriteLine("Cleanup enabled (will not add empty db files)");
                inPackFileName = args[1];
            }
            Console.Out.WriteLine("opening {0}", inPackFileName);
            PackFile packFile = new PackFileCodec().Open(inPackFileName);

            String   correctedFileName = inPackFileName.Replace(".pack", "_corrected.pack");
            String   emptyFileName     = inPackFileName.Replace(".pack", "_empty.pack");
            String   missingFileName   = inPackFileName.Replace(".pack", "_unknown.pack");
            PackFile correctedPack     = new PackFile(correctedFileName, packFile.Header);
            PackFile emptyPack         = new PackFile(emptyFileName, packFile.Header);
            PackFile missingPack       = new PackFile(missingFileName, packFile.Header);

            DBTypeMap.Instance.InitializeTypeMap(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            VirtualDirectory dbDir = packFile.Root.GetSubdirectory("db");

            foreach (PackedFile packedFile in dbDir.AllFiles)
            {
                PackFile targetPack = correctedPack;
                Console.Out.WriteLine(packedFile.FullPath);
                DBFileHeader header    = PackedFileDbCodec.readHeader(packedFile);
                DBFileHeader newHeader = new DBFileHeader(header);
                if (header.EntryCount == 0)
                {
                    emptyPack.Add(packedFile);
                    continue;
                }
                String typeName = DBFile.Typename(packedFile.FullPath);
                byte[] fileData = packedFile.Data;
                // we only accept the exact type/version combination here
                // and only if we don't have to go around trying which one it is (yet)
                var  infos = DBTypeMap.Instance.GetVersionedInfos(typeName, header.Version);
                bool added = false;
                foreach (Filetypes.TypeInfo typeInfo in infos)
                {
                    Console.Out.WriteLine("trying {0}", typeInfo);
                    DBFile newDbFile = new DBFile(newHeader, typeInfo);
                    try {
                        using (BinaryReader reader = new BinaryReader(new MemoryStream(fileData, 0, fileData.Length))) {
                            reader.BaseStream.Position = header.Length;
                            while (reader.BaseStream.Position != fileData.Length)
                            {
                                // try decoding a full row of fields and add it to the new file
                                DBRow newRow = new DBRow(typeInfo);
                                foreach (Filetypes.FieldInfo info in typeInfo.Fields)
                                {
                                    newRow[info.Name].Decode(reader);
                                    //FieldInstance instance = info.CreateInstance();
                                    //instance.Decode(reader);
                                    //newRow.Add(instance);
                                }
                                newDbFile.Entries.Add(newRow);
                            }
                            // all data read successfully!
                            if (newDbFile.Entries.Count == header.EntryCount)
                            {
                                Console.Out.WriteLine("{0}: entry count {1} is correct", packedFile.FullPath, newDbFile.Entries.Count);
#if DEBUG
//                                foreach(DBRow row in newDbFile.Entries) {
//                                    String line = "";
//                                    foreach(FieldInstance instance in row) {
//                                        line += String.Format("{0} - ", line);
//                                    }
//                                    Console.WriteLine(line);
//                                }
#endif
                            }
                            else
                            {
                                Console.Out.WriteLine("{0}: entry count {1} will be corrected to {2}",
                                                      packedFile.FullPath, header.EntryCount, newDbFile.Entries.Count);
                            }
                            if (newDbFile.Entries.Count == 0)
                            {
                                targetPack = emptyPack;
                            }
                            PackedFile        newPackedFile = new PackedFile(packedFile.FullPath, false);
                            PackedFileDbCodec codec         = PackedFileDbCodec.FromFilename(packedFile.FullPath);
                            newPackedFile.Data = codec.Encode(newDbFile);
                            targetPack.Add(newPackedFile);
                            added = true;
                            Console.Out.WriteLine("stored file with {0} entries", newDbFile.Entries.Count);
                            break;
                        }
                    } catch (Exception e) {
                        Console.Error.WriteLine("Will not add {0}: a problem occurred when reading it: {1} at entry {2}",
                                                packedFile.FullPath, e, newDbFile.Entries.Count);
                    }
                }
                if (!added)
                {
                    missingPack.Add(packedFile);
                }
            }
            Console.Out.WriteLine("saving {0}", correctedPack.Filepath);
            PackFileCodec packCodec = new PackFileCodec();
            packCodec.Save(correctedPack);
            packCodec.Save(emptyPack);
            packCodec.Save(missingPack);
        }
示例#28
0
        public DBRow[] SelectRows(
            DBColumn[] columnSelections, Tuple <string, string> tableSelection, DBJoinTable[] tableJoins,
            DBCondition[] conditions
            )
        {
            List <DBRow>  rowsOut = new List <DBRow>();
            List <string> columnSelectionStrings = new List <string>();
            List <string> tableJoinStrings       = new List <string>();

#if USE_SQLITE
            foreach (DBColumn column in columnSelections)
            {
                columnSelectionStrings.Add(
                    column.TableChar + "." + column.Name
                    );
            }

            // Convert the join objects into DB-specific join strings.
            foreach (DBJoinTable join in tableJoins)
            {
                tableJoinStrings.Add(String.Format(
                                         "LEFT OUTER JOIN {0} AS {1} ON {2}.{3}={4}.{5} ",
                                         join.TableName,
                                         join.TableChar,
                                         tableSelection.Item2,
                                         join.MainKey,
                                         join.TableChar,
                                         join.ForeignKey
                                         ));
            }

            string[] conditionStrings = TransformConditionStrings(conditions);

            string selectQueryString = String.Format(
                "SELECT {0} FROM {1} AS {2} {3} WHERE {4} ORDER BY t.src_ip ASC",
                string.Join(",", columnSelectionStrings),
                tableSelection.Item1,
                tableSelection.Item2,
                string.Join(" ", tableJoinStrings),
                string.Join(" AND ", conditionStrings)
                );

            using (SQLiteCommand trafficReadCommand = new SQLiteCommand(
                       selectQueryString, database
                       )) {
                /*
                 * trafficReadCommand.Parameters.AddWithValue( "@ipLowParameter", DBConversions.IP_LOCAL_LOW );
                 * trafficReadCommand.Parameters.AddWithValue( "@ipHighParameter", DBConversions.IP_LOCAL_HIGH );
                 * trafficReadCommand.Parameters.AddWithValue( "@timeStartParameter", this.startTime );
                 * trafficReadCommand.Parameters.AddWithValue( "@timeEndParameter", this.endTime );
                 */

                // Add the proxies.
                foreach (DBCondition condition in conditions)
                {
#if USE_SQLITE_MANAGED
                    trafficReadCommand.Parameters.Add(
                        TransformProxyToken(condition),
                        condition.TestValue
                        );
#else
                    trafficReadCommand.Parameters.AddWithValue(
                        TransformProxyToken(condition),
                        condition.TestValue
                        );
#endif // USE_SQLITE_MANAGED
                }

                using (SQLiteDataReader reader = trafficReadCommand.ExecuteReader()) {
                    while (reader.Read())
                    {
                        int   columnIndexIter = 0;
                        DBRow rowIter         = new DBRow();

                        foreach (DBColumn column in columnSelections)
                        {
                            string columnKey = column.TableChar + "." + column.Name;

                            switch (column.Type)
                            {
                            case DBDataType.STRING:
                                rowIter.Set(columnKey, "");
                                if (!reader.IsDBNull(columnIndexIter))
                                {
                                    rowIter.Set(columnKey, reader.GetString(columnIndexIter));
                                }
                                break;

                            case DBDataType.INT:
                                rowIter.Set(columnKey, reader.GetInt32(columnIndexIter));
                                break;

                            case DBDataType.DOUBLE:
                                rowIter.Set(columnKey, reader.GetDouble(columnIndexIter));
                                break;
                            }

                            columnIndexIter++;
                        }

                        rowsOut.Add(rowIter);
                    }
                }
            }
#endif

            return(rowsOut.ToArray());
        }
示例#29
0
        /// <summary>
        /// Generates the changeset - diff beetween two snapshots.
        /// </summary>
        /// <param name="commSnapshot">The snapshot from other branch.</param>
        /// <param name="dbSnapshot">The snapshot created from database.</param>
        /// <returns>Generated xml changeset.</returns>
        public virtual DBXml GenerateChangeset(DBXml commSnapshot, DBXml dbSnapshot)
        {
            DBXml result = new DBXml(commSnapshot);
            Dictionary <string, string> previousVersion = GetPreviousVersion(result);

            RemovePreviousVersion(result);

            IEnumerable <DBRow> resultEntries = result.Tables.SelectMany(table => table.Rows);

            if (dbSnapshot == null)
            {
                var eTables = new List <DBTable>();
                foreach (var table in result.Tables)
                {
                    if (table.HasRows == false)
                    {
                        eTables.Add(table);
                    }
                }
                foreach (var table in eTables)
                {
                    table.Remove();
                }

                return(MarkAsInserted(resultEntries).First().Table.Document);
            }

            IEnumerable <DBRow> dbEntries = dbSnapshot.Tables.SelectMany(table => table.Rows).Where(row => row.HasAction == false);

            List <DBRow> unmodifiedEntries = new List <DBRow>();

            foreach (DBRow entry in resultEntries)
            {
                DBRow match = dbSnapshot.FindRow(entry);

                if (match != null)
                {
                    //entry.Action != DBRowState.Delete - niestety musialem dolozyc ten warunek gdyz ciezko jest dogadac sie z chlopakami
                    // by entry przy delete tez zawieraly wersje
                    if (entry.Action != DBRowState.Delete && entry.IsTheSameAs(match))
                    {
                        if (entry.Action == null)
                        {
                            unmodifiedEntries.Add(entry);
                        }
                        else if (entry.Action == DBRowState.Insert)
                        {
                            entry.SetAction(DBRowState.Update);
                        }
                    }
                    else if (entry.Action == null)
                    {
                        entry.Element("version").Name = "_version";
                        entry.SetAction(DBRowState.Update);
                    }

                    match.Remove();
                }
                else if (entry.Action == null)
                {
                    entry.SetAction(DBRowState.Insert);
                }
            }

            if (previousVersion != null) // && result.Table(MainObjectTag).FirstRow().Element("version") == null
            {
                SetPreviousVersion(result, previousVersion);
                //result.Table(MainObjectTag).FirstRow().AddElement("version", previousVersion);
            }

            // remove unmodified entries from result
            unmodifiedEntries.ForEach(entry => entry.Remove());

            foreach (DBRow entry in dbEntries)
            {
                entry.SetAction(DBRowState.Delete);
            }

            result.AddTable(from table in dbSnapshot.Tables where table.HasRows select table);

            var emptyTables = new List <DBTable>();

            foreach (var table in result.Tables)
            {
                if (table.HasRows == false)
                {
                    emptyTables.Add(table);
                }
            }
            foreach (var table in emptyTables)
            {
                table.Remove();
            }

            return(result);
        }
示例#30
0
        //Creates a row against the date to database
        public void AddRowToDb(string date, string tin = "00:00", string tout = "00:00", string lin = "00:00", string lout = "00:00")
        {
            //Create a default entry
            DBRow tempp = new DBRow()
            {
                Date = date,
                TimeIn = tin,
                TimeOut = tout,
                LunchIn = lin,
                LunchOut = lout,
                ClockedTime = "00:00"
                //_version = new System.Data.Linq.Binary(bytes)
            };

            //Remove all unknown changes
            //RefreshAndDiscardDbChanges();

            //Insert the new row
            ChangeSet cs = database.GetChangeSet();

            database.logentries.InsertOnSubmit(tempp);
            database.SubmitChanges();
            //Check if successful!
            var readback = QueryRowInDb(date);

            if (readback == null)
            {
                OutOfMemoryException Expc = new OutOfMemoryException("Entry could not be made into the timelog database");
            }
        }