Exemplo n.º 1
0
 /// <summary>
 /// Adds an entry to the dictionary.
 /// </summary>
 /// <remarks>Does not check for duplicate keys.</remarks>
 public void Add(ExpressionBase key, ExpressionBase value)
 {
     _entries.Add(new DictionaryEntry {
         Key = key, Value = value
     });
     _state = DictionaryState.Unprocessed;
 }
Exemplo n.º 2
0
        private DictionaryEntry GetEntry(ExpressionBase key, bool createIfNotFound)
        {
            if (_state == DictionaryState.Unprocessed)
            {
                var error = UpdateState();
                if (error != null)
                {
                    return new DictionaryEntry {
                               Value = error
                    }
                }
                ;
            }

            if (_state == DictionaryState.DynamicKeysUnsorted)
            {
                foreach (var entry in _entries)
                {
                    if (entry.Key == key)
                    {
                        return(entry);
                    }
                }

                if (createIfNotFound)
                {
                    var entry = new DictionaryEntry {
                        Key = key
                    };

                    _entries.Add(entry);
                    return(entry);
                }
            }
            else
            {
                var entry = new DictionaryEntry {
                    Key = key
                };
                var comparer = (IComparer <DictionaryEntry>)entry;
                var index    = _entries.BinarySearch(entry, comparer);
                if (index >= 0)
                {
                    return(_entries[index]);
                }

                if (createIfNotFound)
                {
                    _entries.Insert(~index, entry);
                    if (!key.IsConstant)
                    {
                        _state = DictionaryState.DynamicKeysUnsorted;
                    }

                    return(entry);
                }
            }

            return(null);
        }
        /// <summary>
        /// Pushes the context state, setting a new scope name,
        /// and returns an object that restores the previous state when disposed.
        /// </summary>
        /// <param name="scope">
        /// The new scope name. Used as the first parameter in formatting [EmitName] strings.
        /// </param>
        public IDisposable Push(string scope)
        {
            var disposable = new DictionaryState(this);

            m_dictionary = m_dictionary.SetItem(s_scope, scope);
            return(disposable);
        }
Exemplo n.º 4
0
        public void UpdateKeywordToDatabase(String keyword, DictionaryState state, bool replace = false)
        {
            if (projectInfo.remote_dictionary)
            {
                String dictionary_table = projectInfo.db_dictionary_table.Trim() == "" ? "tb_keywords" : projectInfo.db_dictionary_table.Trim();
                //网络辞典模式
                HunterDatabaseHelper hdh = new HunterDatabaseHelper(projectInfo);
                Database             db  = hdh.GetDatabaseInstance();
                try
                {
                    db.DbOpen();
                    StringBuilder keyword_condition = new StringBuilder();
                    keyword_condition.Append("SELECT key_typeandengine FROM " + dictionary_table + " WHERE key_value = \"" + GetKeyword(CurrentKeywordProgress).Replace("'", "\\'") + "\" LIMIT 1;");
                    MySqlCommand  cmd              = new MySqlCommand(keyword_condition.ToString(), db.mysql_connection);
                    String        result           = cmd.ExecuteScalar().ToString();
                    StringBuilder sb_typeandengine = new StringBuilder(result);
                    if (result != null)
                    {
                        if (!replace)
                        {
                            sb_typeandengine.Append("(" + Filetype + ":" + StrategyData.information.Uri + ":" + state + ");");
                        }
                        else
                        {
                            sb_typeandengine.Replace("(" + Filetype + ":" + StrategyData.information.Uri + ":" + DictionaryState.doing + ");", "(" + Filetype + ":" + StrategyData.information.Uri + ":" + state + ");");
                        }

                        String str_cmd = String.Format("UPDATE {2} SET key_typeandengine = '{0}' WHERE key_value = '{1}'",
                                                       sb_typeandengine.ToString(), keyword.Replace("'", "\\'"), dictionary_table);
                        cmd = new MySqlCommand(str_cmd, db.mysql_connection);
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        String str_cmd = String.Format("INSERT INTO {2} (key_value, key_typeandengine) VALUES ('{0}','{1}')", keyword.Replace("'", "\\'"), "(" + Filetype + ":" + StrategyData.information.Uri + ":" + state + ");", dictionary_table);
                        cmd = new MySqlCommand(str_cmd, db.mysql_connection);
                        cmd.ExecuteNonQuery();
                    }
                    projectInfo.mHunterConsole.WriteDetails("辞典中的关键字信息成功添加到数据库中。");
                }
                catch (Exception ex)
                {
                    projectInfo.mHunterConsole.WriteException(ex);
                    projectInfo.mHunterConsole.WriteException(new Exception("上传关键字信息到数据库失败。"));
                }
                finally
                {
                    try { db.DbClose(); }
                    catch { }
                }
            }
        }
Exemplo n.º 5
0
        protected virtual void ReadRecordField(DictionaryState state, TableDescriber table, FieldDefinition fieldDefinition, string[] fields)
        {
            if (fieldDefinition.StartPosition >= fields.Length)
            {
                if (fieldDefinition.IsOptional) return;
                throw new MessagingException("Message does not match definition. Too few fields in current record.");
            }

            if (fields[fieldDefinition.StartPosition].StartsWith("\"") && fields[fieldDefinition.StartPosition].EndsWith("\"")) // Remove quotes
            {
                fields[fieldDefinition.StartPosition] = fields[fieldDefinition.StartPosition].Substring(1, fields[fieldDefinition.StartPosition].Length - 2);
            }

            var describer = new ColumnDescriber(fieldDefinition.Name, table);

            if (fieldDefinition.Type.IsIn(FieldDefinitionType.DateTime))
            {
                state[describer] = DateTime.ParseExact(fields[fieldDefinition.StartPosition].Trim('"'), fieldDefinition.Format, CultureInfo.InvariantCulture);
            }
            else if (fieldDefinition.Type.IsIn(FieldDefinitionType.Amount, FieldDefinitionType.InvertedAmount, FieldDefinitionType.Decimal))
            {
                object oldvalue;

                decimal oldAmount = state.TryGetValue(describer, out oldvalue) && oldvalue is decimal
                                        ? (decimal) oldvalue
                                        : 0;

                decimal amount = !string.IsNullOrWhiteSpace(fields[fieldDefinition.StartPosition].Trim('"'))
                            ? Decimal.Parse(fields[fieldDefinition.StartPosition].Trim('"'),
                                fieldDefinition.Format.IsNullOrEmpty() ? CultureInfo.InvariantCulture : new CultureInfo(fieldDefinition.Format))
                            : 0;

                if (fieldDefinition.Type == FieldDefinitionType.InvertedAmount) amount *= -1;

                state[describer] = oldAmount + amount;
            }
            else if (fieldDefinition.Type == FieldDefinitionType.AmountSign)
            {
                if (IsNegativeAmountSign(fields[fieldDefinition.StartPosition], fieldDefinition))
                {
                    state[describer] = Decimal.Negate(((decimal)state[describer]));
                }
            }
            else
            {
                object oldvalue;
                state[describer] = state.TryGetValue(describer, out oldvalue)
                                       ? oldvalue + " " + fields[fieldDefinition.StartPosition]
                                       : fields[fieldDefinition.StartPosition];
            }
        }
Exemplo n.º 6
0
 // Method to add an element to the collections.
 public void Add(Monarchy monarchy)
 {
     try
     {
         ListState.Add(monarchy.BaseState);
         ListString.Add(monarchy.BaseState.ToString());
         DictionaryState.Add(monarchy.BaseState, monarchy);
         DictionaryString.Add(monarchy.BaseState.ToString(), monarchy);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
Exemplo n.º 7
0
        private ParseErrorExpression UpdateState()
        {
            if (_entries.Count == 0)
            {
                _state = DictionaryState.ConstantSorted;
            }
            else if (_entries.TrueForAll(e => e.Key.IsConstant))
            {
                // sort by key
                var comparer = (IComparer <DictionaryEntry>)_entries[0];
                _entries.Sort(comparer);

                // check for duplicates
                for (int i = 0; i < _entries.Count - 1; i++)
                {
                    if (comparer.Compare(_entries[i], _entries[i + 1]) == 0)
                    {
                        var           entry   = _entries[i + 1];
                        StringBuilder builder = new StringBuilder();
                        entry.Key.AppendString(builder);
                        builder.Append(" already exists in dictionary");
                        return(new ParseErrorExpression(builder.ToString(), entry.Key));
                    }
                }

                // check for constant values
                if (_entries.TrueForAll(e => e.Value.IsConstant))
                {
                    _state = DictionaryState.ConstantSorted;
                }
                else
                {
                    _state = DictionaryState.ConstantKeysSorted;
                }
            }
            else
            {
                _state = DictionaryState.DynamicKeysUnsorted;
            }

            return(null);
        }
Exemplo n.º 8
0
        internal ParseErrorExpression Assign(ExpressionBase key, ExpressionBase value)
        {
            var entry = GetEntry(key, true);

            var error = entry.Value as ParseErrorExpression;

            if (error != null)
            {
                return(error);
            }

            entry.Value = value;

            if (_state == DictionaryState.ConstantSorted && !value.IsConstant)
            {
                _state = DictionaryState.ConstantKeysSorted;
            }

            return(null);
        }
Exemplo n.º 9
0
        private IEnumerable<Record> BreakIntoRecords(MessageDefinition definition, StreamReader reader)
        {
            var currentLine = 1;
            var currentRecord = string.Empty;

            try
            {
                var records = new List<Record>();
                var recordDefinition = definition.Records[0];
                var table = new TableDescriber(recordDefinition.Name, DataSources.NoSource);

                var line = reader.ReadLine();
                if (definition.HasHeader) line = reader.ReadLine();

                string seperator = recordDefinition.FieldSeparator.Length == 1
                                       ? string.Format(@"(?<=^(?:[^""]*""[^""]*"")*[^""]*){0}",
                                                       recordDefinition.FieldSeparator)
                                       : recordDefinition.FieldSeparator;
                Regex seperatorRegex = recordDefinition.FieldSeparator.Length == 1
                                           ? new Regex(seperator, RegexOptions.Compiled)
                                           : null;

                while (line != null)
                {
                    string[] fields = seperatorRegex != null ? seperatorRegex.Split(line) : line.Split(new[] { recordDefinition.FieldSeparator }, StringSplitOptions.None);

                    var state = new DictionaryState { IsNew = true };

                    if (!recordDefinition.Fields.Exists(f => f.Name.Equals("ID", StringComparison.OrdinalIgnoreCase)))
                    {
                        state[new ColumnDescriber("ID", table, isIdentity: true)] = Guid.NewGuid();
                    }
                    state[new ColumnDescriber("TimeStamp", table, isTimestamp: true)] = null;

                    foreach (var fieldDefinition in recordDefinition.Fields)
                    {
                        currentRecord = fieldDefinition.Name;
                        ReadRecordField(state, table, fieldDefinition, fields);
                    }

                    records.Add(recordDefinition.Create(state));

                    line = reader.ReadLine();
                    currentLine++;
                    currentRecord = string.Empty;
                }

                return records;
            }
            catch (FormatException exception)
            {
                throw new MessagingException(string.Format("Unknown message format. Line {1}, field {2}. {0}", exception.Message, currentLine, currentRecord), exception);
            }
        }
Exemplo n.º 10
0
 public DictionaryEventArgs(DictionaryState state, float value)
 {
     this.state = state;
     this.value = value;
 }
Exemplo n.º 11
0
 public DictionaryEventArgs(DictionaryState state, float value)
 {
     this.state = state;
     this.value = value;
 }
Exemplo n.º 12
0
 internal void MarkUnprocessed()
 {
     _state = DictionaryState.Unprocessed;
 }
Exemplo n.º 13
0
        private IInternalState CreateState(IAdfQuery query, SqlDataReader reader = null)
        {
            var state = new DictionaryState { IsNew = true };

            if (reader != null)
            {
                var schema = reader.GetSchemaTable();

                if (schema == null) throw new InvalidOperationException("could not load schema");

                var table = new TableDescriber(query.Tables[0].Name, DataSource);

                for (int i = 0; i < reader.VisibleFieldCount; i++)
                {
                    var column = new ColumnDescriber(reader.GetName(i), table,
                                                     isIdentity: (bool) schema.Rows[i]["IsKey"],
                                                     isAutoIncrement: (bool) schema.Rows[i]["IsAutoIncrement"],
                                                     isTimestamp: (bool) schema.Rows[i]["IsRowVersion"]);

                    if (reader.HasRows)
                    {
                        var value = reader[i];
                        if (value == DBNull.Value) value = null;

                        state[column] = value;

                        state.IsNew = false;
                    }
                    else
                    {
                        state[column] = null;   // just add column info
                    }
                }
            }

            //            if (reader != null && reader.HasRows && state.Timestamp == null) throw new InvalidOperationException("Row has no Timestamp field");

            return state;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Executes a query
        /// </summary>
        /// <param name="state"></param>
        /// <param name="query"></param>
        /// <returns>The new timestamp</returns>
        protected bool RunSave(DictionaryState state, IAdfQuery query)
        {
            if (query == null) throw new ArgumentNullException("query");

            IDbConnection connection = Provider.GetConnection(DataSource);

            try
            {
                if (connection.State == ConnectionState.Closed) connection.Open();

                var command = Provider.GetCommand(DataSource, connection, query);

                const string autoIncr = "autoincrement";
                var queryExt = string.Format(";SELECT @@DBTS as {0},  CAST(SCOPE_IDENTITY() as int) as {1}", Timestamp, autoIncr);

                command.CommandText += queryExt;

                var reader = (SqlDataReader) command.ExecuteReader();

                if (reader.RecordsAffected == 0)
                    throw new DBConcurrencyException("Concurrency error updating table " + query.LeadTable());

                reader.Read();

                if (state.IsNew)
                {
                    var autoIncrement = state.Keys.FirstOrDefault(col => col.IsAutoIncrement);

                    if (autoIncrement != null)
                    {
                        state[autoIncrement] = reader[autoIncr];
                    }
                }

                var timestamp = state.Keys.First(col => col.IsTimestamp);

                state[timestamp] = reader[Timestamp];

                state.IsNew = false;
                state.IsAltered = false;
            }
            catch (Exception exception)
            {
                Provider.HandleException(exception, DataSource, query);
                return false;
            }

            finally
            {
                connection.Close();
            }

            return true;
        }
Exemplo n.º 15
0
        private IInternalState CreateState(Dictionary<string, ColumnDescriber> describers, SqlDataReader reader = null)
        {
            var state = new DictionaryState { IsNew = true };

            if (reader == null)     // New
            {
                foreach (var describer in describers)
                {
                    state.Add(describer.Value, null);
                }

                return state;
            }

            for (int i = 0; i < reader.VisibleFieldCount; i++)
            {
                ColumnDescriber column;

                if (!describers.TryGetValue(reader.GetName(i), out column))
                    // dont throw exception. this could be due to an added column to the database while the application is running
                    continue; // throw new InvalidOperationException("column not found: " + reader.GetName(i));

                if (reader.HasRows)
                {
                    var value = reader.GetValue(i);
                    if (value == DBNull.Value) value = null;

                    state[column] = value;

                    state.IsNew = false;
                }
                else
                {
                    state[column] = null;   // just add column info
                }
            }
            return state;
        }