Example #1
0
        static void AddNew()
        {
            string filePath = @"D:\KP097R_R206_18_1CONV.mdb";
            Stream file     = new FileStream(filePath, FileMode.Open);
            var    dict     = new DictionaryInfo
            {
                // Dictionary_id =,
                Category_id  = 1,
                Description  = "Тестовый словарь",
                FriendlyName = "Словарь1",
                FileName     = "KP097R_R206_18_1CONV.mdb",
                Action       = ActionEnum.AddDict,
                SenderLogin  = "******"
            };
            FileUploadClient client = new FileUploadClient();

            Thread.Sleep(1000);
            client.Open();
            try
            {
                client.Upload(dict, file);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadKey();
            }
            client.Close();
        }
        int NewDictFileProcessing(Stream stream, string uploadPath, DictionaryInfo dictInfo)
        {
            var tmpFolder = FileHelper.GetTemporaryDirectory();
            var tmpFile   = Path.Combine(tmpFolder, dictInfo.FileName);

            FileHelper.LoadFileFromStream(stream, tmpFile);
            ZipHelper.UnZip(tmpFile);
            var file = Directory.GetFiles(tmpFolder, "*.mdb").Single();

            if (!dictInfo.Dictionary_id.HasValue)
            {
                using (var db = new DictServiceEntities())
                {
                    var dict = new Dictionary()
                    {
                        FileName     = dictInfo.FileName,
                        Category_id  = dictInfo.Category_id,
                        Description  = dictInfo.Description,
                        PathToDict   = Path.Combine(uploadPath, dictInfo.FileName),
                        FriendlyName = dictInfo.FriendlyName
                    };
                    db.Dictionaries.Add(dict);
                    db.SaveChanges();
                    AccessHelper.SetDbStamp(file, dict.Dictionary_id);
                    dictInfo.Dictionary_id = dict.Dictionary_id;
                }
            }
            ZipHelper.CreateZipDictionary(file, uploadPath);
            return(dictInfo.Dictionary_id.Value);
        }
        /// <summary>
        /// вставить элемент справочника
        /// </summary>
        /// <param name="info"> дескриптор </param>
        /// <param name="item"> значение </param>
        /// <returns></returns>
        public JObject PutDictionaryItem(DictionaryInfo info, JObject item)
        {
            var idOrNot = item.TryGetID(true);

            if (idOrNot.HasValue)
            {
                // обновление элемента
                return(PostDictionaryItem(info, item, idOrNot.Value));
            }
            else
            {
                // вставка элемента
                using (var conn = GetConnector())
                {
                    // проверяем существование таблицы
                    var(_, table) = CheckTableExists(conn, info, true);

                    var id = conn.ExecuteScalar <int>($@"
insert into {table.QuotedFullTableName}
(name, pid, ord, extra)
values
(:P_NAME, :P_PID, :P_ORD, :P_EXTRA::jsonb)
returning id",
                                                      "P_NAME", item.GetString("name", true),
                                                      "P_PID", item.GetInt32OrNull("pid", true),
                                                      "P_ORD", item.GetInt32OrNull("ord", true),
                                                      "P_EXTRA", item.GetExtra()
                                                      );

                    return(ReadDictionaryItem(conn, table, id));
                }
            }
        }
Example #4
0
        /// <summary>
        /// 添加
        /// </summary>
        /// yaoy    15.12.01
        /// qiy		15.12.04
        /// <param name="value"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool Add(DictionaryInfo value, out string message)
        {
            message = string.Empty;

            if (value.Code.HasValue)
            {
                //指定标识
                if (!CheckSeed(value))
                {
                    message = string.Format("字典编号:{0} 已被使用.", value.Code);

                    return(false);
                }
            }
            else
            {
                //标识按类型自分配
                do
                {
                    value.Code = (byte)(_dictionaryType.GetSeed(value.Type) + 1);

                    _dictionaryType.SetSeed(value.Type, value.Code.Value);
                } while (!CheckSeed(value));
            }

            dicCommonMapper.Insert(value);

            return(true);
        }
        /// <summary>
        /// This method Edit Comment Dictionary
        /// </summary>
        private void EditCustomDictionary()
        {
            // local
            string dictionaryPath = "";

            try
            {
                // load the dictionaryInfo object from the Registry
                DictionaryInfo dictionaryInfo = RegistryHelper.GetDictionaryInfo();

                // if the dictionaryInfo object exists
                if (dictionaryInfo != null)
                {
                    // set the dictionaryPath
                    dictionaryPath = dictionaryInfo.CustomDictionaryPath;

                    // load the CommentDictionairy
                    if (this.HasHostEventHandler)
                    {
                        // auto commentText the line below the cursor
                        this.hostEventHandler("EditCommentDictionary", dictionaryPath);
                    }
                }
                else
                {
                    // Show the user a message they must set your dictionary path
                    MessageBoxHelper.ShowMessage("Before you can edit the custom dictoinary, you must setup the comment dictionary." + Environment.NewLine + "Click the 'Setup Comment Dictionary button.", "Setup Required");
                }
            }
            catch (Exception error)
            {
                // for debugging only
                string err = error.ToString();
            }
        }
Example #6
0
        /// <summary></summary>
        public virtual DictionaryInfo?CreateDictionary(XmlElement _parent_element, Type _target_type, X2OConfig _config)
        {
            if (_target_type.IsGenericType && _target_type.GenericTypeArguments.Length == 2)
            {
                // generic dictionary like Dictionary<T1, T2>
                var key_type   = _target_type.GenericTypeArguments[0];
                var value_type = _target_type.GenericTypeArguments[1];
                var dict_type  = typeof(Dictionary <,>).MakeGenericType(key_type, value_type);
                if (dict_type.IsAssignableFrom(_target_type))
                {
                    try
                    {
                        var dict = Activator.CreateInstance(_target_type) as IDictionary;
                        // declared type is derived from Dictionary<T1,T2> and we guessed the type parameters correctly
                        var dict_info = new DictionaryInfo()
                        {
                            Dictionary = dict,
                            KeyType    = key_type,
                            ValueType  = value_type
                        };
                        return(dict_info);
                    }
                    catch { }
                }
            }

            // in any other cases, we cannot guess the key and value types without traversing the object hierarchy
            // for these cases, it is better to return without guessing
            // user can override this function to get the correct types

            return(null);
        }
        /// <summary>
        /// This method returns the Dictionary Info
        /// </summary>
        private void DisplayDictionaryInfo(DictionaryInfo dictionaryInfo)
        {
            // locals
            string dictionaryPath       = "";
            double installedVersion     = 0;
            bool   useCustomDictionary  = false;
            string customDictionaryPath = "";
            bool   tryCustomFirst       = false;

            // if the dictionaryInfo object exists
            if (dictionaryInfo != null)
            {
                // set the values
                dictionaryPath       = dictionaryInfo.DictionaryPath;
                installedVersion     = dictionaryInfo.InstalledVersion;
                useCustomDictionary  = dictionaryInfo.UseCustomDictionary;
                customDictionaryPath = dictionaryInfo.CustomDictionaryPath;
                tryCustomFirst       = dictionaryInfo.TryCustomDictionaryFirst;
            }

            // display the values
            this.DictionaryPathControl.Text            = dictionaryPath;
            this.InstalledVersionTextBox.Text          = installedVersion.ToString();
            this.UseCustomDictionaryCheckBox.IsChecked = useCustomDictionary;
            this.CustomDictionaryPathControl.Text      = customDictionaryPath;
            this.TryCustomFirstCheckBox.IsChecked      = tryCustomFirst;
        }
 /// <summary>
 /// 删除数据
 /// </summary>
 /// <param name="rtuId"> </param>
 protected void DeleteInfo(int rtuId)
 {
     if (DictionaryInfo.ContainsKey(rtuId))
     {
         DictionaryInfo.Remove(rtuId);
     }
 }
Example #9
0
        public async System.Threading.Tasks.Task <byte[]> GetBytesAsync(object obj)
        {
            DictionaryInfo dInfo = null;

            if (parentOID > 0)
            {
                dInfo = await serializer.GetDictInfoOfFieldAsync(ti, parentOID, fi).ConfigureAwait(false);
            }
            else
            {
                if (obj != null)
                {
                    IDictionary actualDict   = (IDictionary)obj;
                    Type[]      keyValueType = actualDict.GetType().GetGenericArguments();
                    if (keyValueType.Length != 2)
                    {
                        throw new Sqo.Exceptions.NotSupportedTypeException("Type:" + actualDict.GetType().ToString() + " is not supported");
                    }
                    int keyTypeId   = MetaExtractor.GetAttributeType(keyValueType[0]);
                    int valueTypeId = MetaExtractor.GetAttributeType(keyValueType[1]);
                    dInfo             = new DictionaryInfo();
                    dInfo.KeyTypeId   = keyTypeId;
                    dInfo.ValueTypeId = valueTypeId;
                }
            }
            return(await rawSerializer.SerializeDictionaryAsync(obj, fi.Header.Length, ti.Header.version, dInfo, serializer).ConfigureAwait(false));
        }
Example #10
0
        public byte[] GetBytes(object obj)
        {
            DictionaryInfo dInfo = null;

            if (parentOID > 0)
            {
                dInfo = serializer.GetDictInfoOfField(ti, parentOID, fi);
            }
            else
            {
                if (obj != null)
                {
                    IDictionary actualDict   = (IDictionary)obj;
                    Type[]      keyValueType = actualDict.GetType().GetGenericArguments();
                    if (keyValueType.Length != 2)
                    {
                        throw new Sqo.Exceptions.NotSupportedTypeException("Type:" + actualDict.GetType().ToString() + " is not supported");
                    }
                    int keyTypeId   = MetaExtractor.GetAttributeType(keyValueType[0]);
                    int valueTypeId = MetaExtractor.GetAttributeType(keyValueType[1]);
                    dInfo             = new DictionaryInfo();
                    dInfo.KeyTypeId   = keyTypeId;
                    dInfo.ValueTypeId = valueTypeId;
                }
            }
            return(rawSerializer.SerializeDictionary(obj, fi.Header.Length, ti.Header.version, dInfo, serializer));
        }
Example #11
0
        /// <summary>
        /// Clean the dictionary. Remove expired items.
        /// </summary>
        /// <param name="lockedItems">Dictionary, must be locked.</param>
        private void RemoveExpired(Dictionary <string, DictionaryValue> lockedItems, DictionaryInfo info)
        {
            DateTime      now          = DateTime.Now;
            List <string> keysToremove = new List <string>();

            DateTime minExpiration = DateTime.MaxValue;

            // collect expired items, get minExpiration time
            foreach (var x in lockedItems)
            {
                if (x.Value.ExpirationTime <= now)
                {
                    keysToremove.Add(x.Key);
                }
                else
                {
                    if (x.Value.ExpirationTime < minExpiration)
                    {
                        minExpiration = x.Value.ExpirationTime;
                    }
                }
            }

            // remove expired items
            foreach (var x in keysToremove)
            {
                lockedItems.Remove(x);
            }

            // update info
            info.LastCheck         = now;
            info.MinExpirationTime = minExpiration;
        }
Example #12
0
        public static Dictionary Load(string dictionaryId)
        {
            DictionaryInfo info   = DictionaryList.First((it) => it.id == dictionaryId);
            Dictionary     result = null;

            if (info != null)
            {
                if (info.dict == null)
                {
                    try
                    {
                        var           reader = new StreamReader(File.OpenRead(info.filename));
                        List <string> listA  = new List <string>();
                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            listA.Add(line);
                        }
                        info.dict = new Dictionary(listA);
                    }
                    catch
                    {
                        info.dict = new Dictionary(new List <string>()
                        {
                        });
                    }
                }
                result    = info.dict;
                result.id = info.id;
            }
            return(result);
        }
Example #13
0
        private static ISet <Namespace> EvaluateDictionary(ExpressionEvaluator ee, Node node)
        {
            var n = (DictionaryExpression)node;
            ISet <Namespace> result;

            if (!ee.GlobalScope.NodeVariables.TryGetValue(node, out result))
            {
                var keys   = new HashSet <Namespace>();
                var values = new HashSet <Namespace>();
                foreach (var x in n.Items)
                {
                    foreach (var keyVal in ee.Evaluate(x.SliceStart))
                    {
                        keys.Add(keyVal);
                    }
                    foreach (var itemVal in ee.Evaluate(x.SliceStop))
                    {
                        values.Add(itemVal);
                    }
                }

                result = new DictionaryInfo(keys, values, ee.ProjectState).SelfSet;
                ee.GlobalScope.NodeVariables[node] = result;
            }
            return(result);
        }
        Dictionary RefreshDictionary(DictionaryInfo dictInfo, User user, Stream stream)
        {
            using (var db = new DictServiceEntities())
            {
                var dict = db.Dictionaries.Single(x => x.Dictionary_id == dictInfo.Dictionary_id.Value);
                dict.DictionaryState = db.DictionaryStates.Single(x => x.State_id == (int)DictionaryStateEnum.Refreshing);
                db.Entry(dict).State = EntityState.Modified;
                var change = new UserChangeHistory()
                {
                    Dictionary_id = dict.Dictionary_id,
                    Action_id     = (int)ActionEnum.EditDict,
                    DateHistory   = DateTime.Now,
                    User_id       = user.User_id
                };
                db.UserChangeHistories.Add(change);
                db.SaveChanges();
                ExistDictFileProcessing(stream, dict, change);
                dict.DictionaryState = db.DictionaryStates.Single(x => x.State_id == (int)DictionaryStateEnum.Available);
                db.Entry(dict).State = EntityState.Modified;

                db.SaveChanges();
                AddNewQueue(dict.Dictionary_id, ActionEnum.EditDict, change.UserHistory_id);
                return(dict);
            }
        }
Example #15
0
        /// <summary>
        /// обновить элемент справочника
        /// </summary>
        /// <param name="info"> дескриптор </param>
        /// <param name="item"> значение </param>
        /// <param name="id"> идентификатор </param>
        /// <returns></returns>
        public JObject PostDictionaryItem(DictionaryInfo info, JObject item, int id)
        {
            item.TryGetID(true);

            // обновление элемента
            using (var conn = GetConnector())
            {
                // проверяем существование таблицы
                var(_, table) = CheckTableExists(conn, info, true);

                conn.ExecuteNonQuery($@"
update {table.QuotedFullTableName}
   set name = :P_NAME,
       pid = :P_PID,
       ord = :P_ORD,
       extra = :P_EXTRA::jsonb
 where id = :P_ID",
                                     "P_NAME", item.GetString("name", true),
                                     "P_PID", item.GetInt32OrNull("pid", true),
                                     "P_ORD", item.GetInt32OrNull("ord", true),
                                     "P_EXTRA", item.GetExtra(),
                                     "P_ID", id
                                     );

                return(ReadDictionaryItem(conn, table, id));
            }
        }
        public UploadResponse Upload(UploadRequest request)
        {
            try
            {
                DictionaryInfo dictInfo = request.DictInfo;
                using (var db = new DictServiceEntities())
                {
                    var user = db.Users.SingleOrDefault(x => x.Login == dictInfo.SenderLogin);
                    if (user == null)
                    {
                        user.Login = request.DictInfo.SenderLogin;
                        db.Users.Add(user);
                        db.SaveChanges();
                    }
                    //if (!CheckExtension(dictInfo.FileName, ".mdb"))
                    //{
                    //    throw new NotSupportedException();
                    //}
                    if (!CheckPermission(user, dictInfo.Action))
                    {
                        throw new Exception("Нету прав!!!");
                    }
                    switch (dictInfo.Action)
                    {
                    case ActionEnum.AddDict:
                    {
                        AddNewDicionary(request.DictInfo, user, request.Stream);
                        break;
                    }

                    case ActionEnum.EditDict:
                    {
                        RefreshDictionary(request.DictInfo, user, request.Stream);
                        break;
                    }
                    }
                    return(new UploadResponse
                    {
                        UploadSucceeded = true
                    });
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                               validationError.PropertyName,
                                               validationError.ErrorMessage);
                    }
                }
                return(new UploadResponse
                {
                    UploadSucceeded = false,
                    Error = dbEx.ToString()
                });
            }
        }
        public override void Start()
        {
            base.Start();

            DictionaryInfo info = _parametersManager.Get <DictionaryInfo>(Parameters.LaunchedProduct);

            Header = info.Name;
        }
Example #18
0
        private void Initialize()
        {
            DictionaryInfo info    = _parametersManager.Get <DictionaryInfo>(Parameters.LaunchedProduct);
            Uri            fileUri = new Uri(string.Format(FileNameFormat, Data.FormatVersion, info.Id), UriKind.Relative);

            _dataAccessorV2 = new DataAccessorV2(fileUri);

            ReadData();
        }
Example #19
0
        /// <summary>
        /// 获取投票人信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetVoteTheUserInfos(HttpContext context)
        {
            int totalCount;
            List <BLLJIMP.Model.UserInfo> data;
            string voteId    = context.Request["VoteId"];
            string itemId    = context.Request["ItemId"];
            int    pageIndex = Convert.ToInt32(context.Request["page"]);
            int    pageSize  = Convert.ToInt32(context.Request["rows"]);
            //System.Text.StringBuilder sbWhere = new StringBuilder(string.Format(" Activityid='{0}'", ActivityId));
            StringBuilder sbWhere = new StringBuilder();

            if (!string.IsNullOrEmpty(voteId))
            {
                sbWhere.AppendFormat(" VoteId='{0}' ", voteId);
            }
            if (!string.IsNullOrEmpty(itemId))
            {
                sbWhere.AppendFormat(" And DiInfoId like'%{0}%' ", itemId);
            }
            List <BLLJIMP.Model.UserVoteInfo> uVInfo = this.bllJuActivity.GetList <BLLJIMP.Model.UserVoteInfo>(sbWhere.ToString());
            string userId = "'0'";

            foreach (BLLJIMP.Model.UserVoteInfo item in uVInfo)
            {
                userId += ",'" + item.UserId + "'";
            }
            string webUserId = string.Format("  UserID in ({0})", userId);

            totalCount = this.bllJuActivity.GetCount <BLLJIMP.Model.UserInfo>(webUserId);
            data       = this.bllJuActivity.GetLit <BLLJIMP.Model.UserInfo>(pageSize, pageIndex, webUserId);

            foreach (var user in data)
            {
                user.Ex1 = "";
                var item = uVInfo.FirstOrDefault(p => p.UserId == user.UserID);
                if (item != null)
                {
                    foreach (var voteItemId in item.DiInfoId.Split(','))
                    {
                        DictionaryInfo dic = bll.Get <DictionaryInfo>(string.Format(" ForeignKey={0} And AutoId={1}", voteId, voteItemId));
                        if (dic != null)
                        {
                            user.Ex1 += dic.ValueStr + " ";
                        }
                    }
                }
            }


            return(Common.JSONHelper.ObjectToJson(
                       new
            {
                total = totalCount,
                rows = data
            }));
        }
Example #20
0
        public void Dispose_UseDictionaryAfterBrokerDisposed_Throws()
        {
            Dictionary dictionary;

            using (Broker broker = new Broker())
            {
                dictionary = broker.RequestDictionary("en_US");
            }
            DictionaryInfo info = dictionary.Information;
        }
        /// <summary>
        /// Gets the URL for the given cdrID.
        /// Returns the URL with the friendly-name if found, otherwise with the CDRID.
        /// </summary>
        public string GetSitemapUrl(DictionaryInfo info, string cdrId)
        {
            NciUrl url = new NciUrl();

            url.SetUrl(_rootUrl);
            url.AppendPathSegment(info.DefinitionUrl);
            url.AppendPathSegment(GetFriendlyName(info, cdrId));

            return(_rootUrl + url.ToString());
        }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        public StorageMemory()
        {
            ItemsListInfo = new DictionaryInfo[ItemsList.Length];

            for (int i = 0; i < ItemsList.Length; ++i)
            {
                ItemsList[i]     = new Dictionary <string, DictionaryValue>();
                ItemsListInfo[i] = new DictionaryInfo();
            }
        }
        /// <summary>
        /// This method performs initializations for this object.
        /// </summary>
        public void Setup(DictionaryInfo dictionaryInfo)
        {
            // store the values so we can compare against the current value so we can determine if there are any changes
            this.StoredDictionaryInfo = dictionaryInfo;

            // display the dictionaryInfo
            DisplayDictionaryInfo(dictionaryInfo);

            // Enable the buttons
            UIEnable();
        }
Example #24
0
        /// <summary>
        /// получить элемент справочника
        /// </summary>
        /// <param name="info"> дескриптор </param>
        /// <param name="id"> идентификатор </param>
        /// <returns></returns>
        public JObject GetDictionaryItem(DictionaryInfo info, int id)
        {
            using (var conn = GetConnector())
            {
                // проверяем существование таблицы
                var(_, table) = CheckTableExists(conn, info, true);

                // получаем данные
                return(ReadDictionaryItem(conn, table, id));
            }
        }
        /// <summary>
        /// This method sets up this control
        /// </summary>
        internal void Setup(DictionaryInfo dictionaryInfo)
        {
            // call the method on the CommentDictionaryEditor
            CommentDictionaryEditor dictionaryEditor = this.MainHost.Child as CommentDictionaryEditor;

            // if the dictionaryEditor object exists
            if (dictionaryEditor != null)
            {
                // setup the control
                dictionaryEditor.Setup(dictionaryInfo);
            }
        }
        /// <summary>
        /// This event is fired when the 'UpdateRegistryButton' is clicked.
        /// </summary>
        private void UpdateRegistryButton_Click(object sender, RoutedEventArgs e)
        {
            // set the local values
            DictionaryInfo dictionaryInfo = this.CaptureDictionaryInfo();

            // if the UpdateRegistryMethod exists
            if (this.HasUpdateRegistryMethod)
            {
                // update the registry
                this.UpdateRegistryMethod(dictionaryInfo);
            }
        }
Example #27
0
        /// <summary>
        /// удалить элемент справочника
        /// </summary>
        /// <param name="info"> дескриптор </param>
        /// <param name="id"> идентификатор </param>
        public void DeleteDictionaryItem(DictionaryInfo info, int id)
        {
            using (var conn = GetConnector())
            {
                // проверяем существование таблицы
                var(_, table) = CheckTableExists(conn, info, true);

                conn.ExecuteNonQuery($@"
delete from {table.QuotedFullTableName}
 where id = :P_ID", "P_ID", id);
            }
        }
Example #28
0
        /// <summary>
        /// проверить существование таблицы
        /// </summary>
        /// <param name="conn"> коннектор </param>
        /// <param name="info"> дескриптор </param>
        /// <param name="createifNotExists"> указывает, что необходимо создать таблицу в случае ее отсутствия </param>
        /// <returns></returns>
        private (bool exists, TableInfo table) CheckTableExists(Connector conn, DictionaryInfo info, bool createifNotExists)
        {
            if (info == default)
            {
                throw new ArgumentNullException(nameof(info));
            }

            var table = GetDataTableName(info);

            if (!info.IsTableExists && createifNotExists)
            {
                // необходимо создать таблицу
                using (var tx = conn.BeginTransaction())
                {
                    // создаем таблицу
                    conn.ExecuteScalar($@"
CREATE TABLE {table.QuotedFullTableName}
(
  id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,
  name text NOT NULL,
  pid int4 NULL,
  ord int4 NULL,
  extra jsonb NULL,
  CONSTRAINT {table.TableName}_pk PRIMARY KEY (id),
  CONSTRAINT {table.TableName}_fk FOREIGN KEY (pid) REFERENCES {table.QuotedFullTableName}(id) ON DELETE CASCADE ON UPDATE CASCADE
)");

                    // создаем индексы
                    conn.ExecuteScalar($@"CREATE INDEX {table.TableName}_name_idx ON {table.QuotedFullTableName}(name);");
                    conn.ExecuteScalar($@"CREATE INDEX {table.TableName}_pid_idx ON {table.QuotedFullTableName}(pid);");

                    // добавляем комментарии
                    if (!string.IsNullOrWhiteSpace(info.Description))
                    {
                        conn.ExecuteScalar($@"COMMENT ON TABLE {table.QuotedFullTableName} IS {QuoteString(info.Description)}");
                    }

                    conn.ExecuteScalar($@"COMMENT ON COLUMN {table.QuotedFullTableName}.id IS 'Идентификатор записи'");
                    conn.ExecuteScalar($@"COMMENT ON COLUMN {table.QuotedFullTableName}.name IS 'Наименование записи'");
                    conn.ExecuteScalar($@"COMMENT ON COLUMN {table.QuotedFullTableName}.pid IS 'Идентификатор родительской записи'");
                    conn.ExecuteScalar($@"COMMENT ON COLUMN {table.QuotedFullTableName}.ord IS 'Порядок для сортировки'");
                    conn.ExecuteScalar($@"COMMENT ON COLUMN {table.QuotedFullTableName}.extra IS 'Дополнительные данные'");

                    // создаем команду кластеризации
                    conn.ExecuteScalar($@"CLUSTER {table.QuotedFullTableName} USING {table.TableName}_pk;");

                    tx.Commit();
                }
            }

            return(info.IsTableExists, table);
        }
Example #29
0
 IAnalysisSet ReturnsStringToObjectDict(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames)
 {
     return(unit.Scope.GetOrMakeNodeValue(node, n => {
         var dict = new DictionaryInfo(unit.ProjectEntry, node);
         dict.AddTypes(
             node,
             unit,
             unit.ProjectState.ClassInfos[BuiltinTypeId.Str].Instance,
             unit.ProjectState.ClassInfos[BuiltinTypeId.Object].Instance
             );
         return dict;
     }));
 }
        /// <summary>
        /// 解析字典。
        /// </summary>
        /// <param name="dataProviderOwner">本地化管理器。</param>
        /// <param name="dictionaryBytes">要解析的字典二进制流。</param>
        /// <param name="startIndex">字典二进制流的起始位置。</param>
        /// <param name="length">字典二进制流的长度。</param>
        /// <param name="userData">用户自定义数据。</param>
        /// <returns>是否解析字典成功。</returns>
        public override bool ParseData(LocalizationProvider dataProviderOwner, byte[] dictionaryBytes, int startIndex, int length, object userData)
        {
            try
            {
                using (MemoryStream memoryStream = new MemoryStream(dictionaryBytes, startIndex, length, false))
                {
                    using (BinaryReader binaryReader = new BinaryReader(memoryStream, Encoding.UTF8))
                    {
                        while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
                        {
                            int dataRowBytesLength = binaryReader.ReadInt32();

                            int      m_Id       = binaryReader.ReadInt32();
                            Language m_Language = (Language)Enum.Parse(typeof(Language), binaryReader.ReadString());
                            string   m_Owner    = binaryReader.ReadString();
                            string   m_Block    = binaryReader.ReadString();
                            string   m_Key      = binaryReader.ReadString();
                            string   m_Value    = binaryReader.ReadString();
                            int      m_Size     = binaryReader.ReadInt32();
                            bool     m_NewLine  = binaryReader.ReadBoolean();
                            string   m_Color    = binaryReader.ReadString();
                            string   m_Index    = binaryReader.ReadString();

                            FBlockInfo fBlockInfo = dataProviderOwner.GetBlockInfoDic(m_Owner, m_Block);

                            DictionaryInfo dictionary = new DictionaryInfo();

                            dictionary.Id       = m_Id;
                            dictionary.Language = m_Language;
                            dictionary.Size     = m_Size;
                            dictionary.NewLine  = m_NewLine;
                            dictionary.Color    = m_Color;
                            dictionary.Owner    = m_Owner;
                            dictionary.Block    = m_Block;
                            dictionary.Key      = m_Key;
                            dictionary.Value    = m_Value;
                            fBlockInfo.UpdateDicInfo(dictionary);

                            //Log.Info("m_Owner" + m_Owner + "m_Block" + m_Block + "m_Key" + m_Key + "m_Value" + m_Value);
                        }
                    }
                }

                return(true);
            }
            catch (Exception exception)
            {
                Log.Warning("Can not parse dictionary bytes with exception '{0}'.", exception.ToString());
                return(false);
            }
        }
Example #31
0
        /// <summary>
        /// Creates a new z machine character encoder
        /// </summary>
        /// <param name="buf">game memory buffer</param>
        public ZTextEncoder(MemoryBuffer buf)
        {
            //Store buffer
            this.buf = buf;

            //Get version
            this.machineVersion = buf.GetByte(0);

            //Find unicode table address
            int unicodeTable = 0;

            if (machineVersion >= 5)
            {
                //Search the extension header table
                ushort extensionHdr = buf.GetUShort(0x36);

                if (extensionHdr != 0 && buf.GetUShort(extensionHdr) >= 3)
                {
                    unicodeTable = buf.GetUShort(extensionHdr + 6);
                }
            }

            //Create unicode cache
            this.unicodeCache = CreateUnicodeCache(unicodeTable);

            //Create reverse cache
            // Go in reverse so that ASCII takes priority over custom unicode
            for(int i = 255; i > 0; i--)
            {
                //Add character
                if (unicodeCache[i] != InvalidChar)
                {
                    reverseUnicodeCache[unicodeCache[i]] = (byte) i;
                }
            }

            //Create alphabet cache
            if (machineVersion >= 5 && buf.GetUShort(0x34) != 0)
            {
                this.alphabetCache = CreateAlphabetCache(buf.GetUShort(0x34));
            }
            else
            {
                //Use default alphabet
                this.alphabetCache = machineVersion == 1 ? DEFAULT_ALPHABET_TABLE_V1 : DEFAULT_ALPHABET_TABLE;
            }

            //Create reverse alphabet cache
            for (int i = 0; i < 78; i++)
            {
                reverseAlphabetCache[reverseUnicodeCache[alphabetCache[i]]] = (byte) (i + 1);
            }

            //Create abbreviation cache
            if (machineVersion >= 2 && buf.GetUShort(0x18) != 0)
            {
                this.abbreviationCache = CreateAbbreviationCache(buf.GetUShort(0x18));
            }

            //Cache dictionary information
            mainDictionaryAddress = buf.GetUShort(0x8);
            mainDictionary = GetDictionaryInfo(mainDictionaryAddress);
        }
Example #32
0
        /// <summary>
        /// Looks up a word and adds it to the parse buffer
        /// </summary>
        /// <param name="wordAddress">address of word</param>
        /// <param name="length">length of word</param>
        /// <param name="parseAddress">address to add to</param>
        /// <returns>new parse address</returns>
        private void LookupWord(DictionaryInfo info, int textBuffer, int wordOffset, int length,
                                int parseAddress, bool ignoreUnknownWords)
        {
            //Ignore empty words
            if (length == 0)
                return;

            //Encode text
            ushort[] encoded = EncodeForDictionary(textBuffer + wordOffset, length);
            ulong encodedInteger;

            if (machineVersion >= 4)
            {
                encodedInteger = (ulong) (encoded[0] << 32 | encoded[1] << 16 | encoded[2]);
            }
            else
            {
                encodedInteger = (ulong) (encoded[0] << 16 | encoded[1]);
            }

            //Find in dictionary
            if (info.Sorted)
            {
                int leftPtr = 0;
                int rightPtr = info.EntryCount;

                //Do binary search
                while (rightPtr > leftPtr)
                {
                    //Find midpoint
                    int mid = (leftPtr + rightPtr) / 2;
                    ulong entry = ReadEntry(info.DictionaryStart + mid * info.EntrySize);

                    //How does that entry compare
                    if (entry < encodedInteger)
                    {
                        //Use left half
                        rightPtr = mid - 1;
                    }
                    else if (entry > encodedInteger)
                    {
                        //Use right half
                        leftPtr = mid + 1;
                    }
                    else
                    {
                        //Equal - word found
                        buf.SetUShort(parseAddress, (ushort) (info.DictionaryStart + mid * info.EntrySize));
                        buf.SetByte(parseAddress + 2, (byte) length);
                        buf.SetByte(parseAddress + 3, (byte) wordOffset);
                        return;
                    }
                }
            }
            else
            {
                //Linear search
                int dictEnd = info.DictionaryStart + info.EntryCount * info.EntrySize;

                for (int dictAddress = info.DictionaryStart; dictAddress < dictEnd;
                        dictAddress += info.EntrySize)
                {
                    //Compare
                    if (ReadEntry(dictAddress) == encodedInteger)
                    {
                        //Equal - word found
                        buf.SetUShort(parseAddress, (ushort) dictAddress);
                        buf.SetByte(parseAddress + 2, (byte) length);
                        buf.SetByte(parseAddress + 3, (byte) wordOffset);
                        return;
                    }
                }
            }

            //Unknown word
            if (!ignoreUnknownWords)
            {
                buf.SetUInt(parseAddress, 0);
            }
        }
Example #33
0
 /// <summary>Open the given dictionary, possibly loading from a file, 
 /// in a new LookupForm window.</summary>
 public LookupForm(DictionaryInfo dictionaryInfo)
     : this(dictionaryInfo.GetFullInstance())
 {
 }
Example #34
0
        /// <summary>
        /// Opens a dictionary window for the specified dictionary, using an 
        /// existing window if possible.
        /// </summary>
        /// <param name="dict">The dictionary to open.</param>
        public static void OpenDictionary(DictionaryInfo dict)
        {
            if (dict == null)
                return;

            try {
                ShowForm.Show(
                    form => form.Dictionary.Path == dict.Path,
                    () => new LookupForm(dict));
            } catch (System.IO.IOException e) {
                Errors.CouldNotLoadDictionary(dict.Name, dict.Path, e);
            } catch (DictionaryLoadException e) {
                Errors.CouldNotLoadDictionary(dict.Name, dict.Path, e);
            }
        }
Example #35
0
 internal static HandleRef getCPtr(DictionaryInfo obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }