コード例 #1
0
        public override void AddEntry(IEntry entry)
        {
            if (!saveStat) return;

            if (!string.IsNullOrWhiteSpace(entry.Source.Pool))
            {
                // проверить наличие записи в таблице пулов
                if (!poolIds.ContainsKey(entry.Source.Pool))
                {
                    lock (sync) // отладить при многопоточности (есть проблемы при появлении нового пула)
                    {
                        if (!poolIds.ContainsKey(entry.Source.Pool))
                            poolIds.Add(entry.Source.Pool, GetPoolId(entry.Source.Pool));
                    }
                }

                entry.Source.PoolId = poolIds[entry.Source.Pool];
            }
            else
            {
                entry.Source.PoolId = -1;
            }

            base.AddEntry(entry);
        }
コード例 #2
0
		public virtual MembershipUser Create(IEntry entry) {
			if(!entry.IsBound()) {
				return null;
			}

			var name = entry.GetProperties<string>(config.Users.RdnAttribute).FirstOrDefault() ?? entry.Name;
			var providerUserKey = name;
			var email = entry.GetProperties<string>(config.Users.EmailAttribute).FirstOrDefault();
			var description = entry.GetProperties<string>(config.Users.DescriptionAttribute).FirstOrDefault();

			var creationDate = entry.GetProperties<DateTime>(config.Users.CreationDateAttribute).FirstOrDefault();
			var lastLoginDate = entry.GetProperties<DateTime>(config.Users.LastLoginDateAttribute).FirstOrDefault();
			var lastPasswordChangedDate = entry.GetProperties<DateTime>(config.Users.LastPasswordChangedDateAttribute).FirstOrDefault();
			var lastLockoutDate = creationDate;
			var lastActivitiyDate = GetDateTimeNow();

			return CreateMembershipUser(name,
			                            providerUserKey,
			                            email,
										description,
										lastActivitiyDate,
										lastLoginDate,
										lastLockoutDate,
										lastPasswordChangedDate,
										creationDate,
										entry.Properties,
										entry.Path);
		}
コード例 #3
0
        public int UpdateEntry(IEntry entry)
        {
            var entries = GetAllEntries();
            var concreteEntry = (Entry)entry;

            //ensure the date doesn't have any hours, mins or seconds
            concreteEntry.EntryDate = concreteEntry.EntryDate.Date;

            if (concreteEntry.EntryId == 0)
            {
                //insert new.
                concreteEntry.EntryId = entries.Any() ? entries.Max(x => x.EntryId) + 1 : 1;
                entries.Add(concreteEntry);
            }
            else
            {
                var existingIndex = entries.FindIndex(x => x.EntryId == concreteEntry.EntryId);
                if (existingIndex < 0)
                {
                    return -1;
                }

                entries[existingIndex] = concreteEntry;
            }

            SaveAllEntries(entries);

            return concreteEntry.EntryId;
        }
コード例 #4
0
ファイル: TableOfContent.cs プロジェクト: jaygumji/EnigmaDb
 public bool TryGet(IKey key, out IEntry entry)
 {
     Entry tempEntry;
     var result = _entries.TryGetValue(key, out tempEntry) && !tempEntry.IsReserved;
     entry = result ? tempEntry : null;
     return result;
 }
コード例 #5
0
        public IEnumerable<IEntryItem> GetEntryDetails(IEntry entry)
        {
            Argument.IsNotNull(() => entry);

            if (entry.Items.Count > 0)
            {
                return entry.Items;
            }

            string url = entry.Url;

            try
            {
                Log.Debug("Trying to fetch entry items from '{0}'", url);

                var webClient = new WebClient();
                var pageContent = webClient.DownloadString(url);

                var entryItems = _parserService.ParseEntryItems(entry, pageContent);
                entry.Items.ReplaceRange(entryItems);

                return entry.Items;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to get VrijMiBo entries from '{0}'", url);

                return new List<IEntryItem>();
            }
        }
コード例 #6
0
ファイル: SentFilterSource.cs プロジェクト: karno/OpenSolar
		/// <summary>
		/// 指定したエントリがこのソースから取得できるエントリとして扱うかどうかを取得します。
		/// </summary>
		/// <param name="entry">判定するエントリ。</param>
		/// <returns>このソースから取得できるエントリとして扱うかどうか。</returns>
		protected override bool StreamEntryMatches(IEntry entry)
		{
			return entry.TypeMatch
			(
				(Status _) => !_.IsDirectMessage && _.UserName == _.Account.Name,
				_ => false
			);
		}
コード例 #7
0
		/// <summary>
		/// 指定したエントリがこのソースから取得できるエントリとして扱うかどうかを取得します。
		/// </summary>
		/// <param name="entry">判定するエントリ。</param>
		/// <returns>このソースから取得できるエントリとして扱うかどうか。</returns>
		protected override bool StreamEntryMatches(IEntry entry)
		{
			return entry.TypeMatch
			(
				(DirectMessage _) => _.UserID == _.Account.UserID,
				_ => false
			);
		}
コード例 #8
0
		/// <summary>
		/// 指定したエントリがこのソースから取得できるエントリとして扱うかどうかを取得します。
		/// </summary>
		/// <param name="entry">判定するエントリ。</param>
		/// <returns>このソースから取得できるエントリとして扱うかどうか。</returns>
		protected override bool StreamEntryMatches(IEntry entry)
		{
			return entry.TypeMatch
			(
				(Status _) => _.Favorited,
				_ => false
			);
		}
コード例 #9
0
ファイル: PublicFilterSource.cs プロジェクト: karno/OpenSolar
		/// <summary>
		/// 指定したエントリがこのソースから取得できるエントリとして扱うかどうかを取得します。
		/// </summary>
		/// <param name="entry">判定するエントリ。</param>
		/// <returns>このソースから取得できるエントリとして扱うかどうか。</returns>
		protected override bool StreamEntryMatches(IEntry entry)
		{
			return entry.TypeMatch
			(
				(Status _) => !_.IsDirectMessage,
				_ => false
			);
		}
コード例 #10
0
ファイル: SearcherFactory.cs プロジェクト: aelveborn/njupiter
		private IDirectorySearcher CreateSearcher(IEntry entry, SearchScope searchScope, string rdnAttribute) {
			var searcher = CreateSearcher(entry, searchScope);
			if(serverConfig.PropertySortingSupport || serverConfig.VirtualListViewSupport) {
				searcher.Sort.PropertyName = rdnAttribute;
				searcher.Sort.Direction = SortDirection.Ascending;
			}
			return searcher;
		}
コード例 #11
0
ファイル: SearcherFactory.cs プロジェクト: aelveborn/njupiter
		public virtual IDirectorySearcher CreateSearcher(IEntry entry, SearchScope searchScope, IEntryConfig entryConfig) {
			var searcher = CreateSearcher(entry, searchScope, entryConfig.RdnAttribute);
			searcher.PropertiesToLoad.Add(entryConfig.RdnAttribute);
			foreach(var attribute in entryConfig.Attributes) {
				searcher.PropertiesToLoad.Add(attribute.Name);
			}
			return searcher;
		}
コード例 #12
0
		/// <summary>
		/// 指定したエントリがこのソースから取得できるエントリとして扱うかどうかを取得します。
		/// </summary>
		/// <param name="entry">判定するエントリ。</param>
		/// <returns>このソースから取得できるエントリとして扱うかどうか。</returns>
		protected override bool StreamEntryMatches(IEntry entry)
		{
			return entry.TypeMatch
			(
				(Status _) => !_.IsDirectMessage && _.Mentions.Contains(_.Account.Name) && !_.IsRetweet,
				_ => false
			);
		}
コード例 #13
0
        private ActionResult CreateNewEntry(IEntry entry)
        {
            this.modelFactory.EntryService.CreateEntry(entry);
            TempData["SaveResult"] = "Items was successfully saved with Id = " + entry.Id;

            return RedirectToAction("EditEntry",
                                    "AdminEntry",
                                    new {id = entry.Id});
        }
コード例 #14
0
 internal static SyndicationItem CreateSyndicationItem(IEntry entry, string uriString)
 {
     return new SyndicationItem(entry.SeoTitle,
                                SyndicationContent.
                                    CreateHtmlContent(entry.EntryBody),
                                new Uri(uriString),
                                string.Format("item-id-{0}", entry.Id),
                                entry.CreatedAt);
 }
コード例 #15
0
        public bool TryGet(IKey key, out IEntry entry)
        {
            foreach (var fragment in _fragments)
                if (fragment.TableOfContent.TryGet(key, out entry))
                    return true;

            entry = null;
            return false;
        }
 public void AddAndEditTerm(IEntry term, string source, string target)
 {
     var dataGrid = new ExcelDataGrid
     {
         Term = target,
         Approved = null
     };
     AddAndEditAction?.Invoke(term, dataGrid);
 }
コード例 #17
0
ファイル: SourceFilterTerms.cs プロジェクト: karno/OpenSolar
		/// <summary>
		/// 条件に項目が一致するかどうかを判断します。
		/// </summary>
		/// <param name="entry">エントリ。</param>
		/// <returns>条件に一致するかどうか。</returns>
		public override bool FilterStatus(IEntry entry)
		{
			return entry.TypeMatch
			(
				(Status _) => this.Sources.Contains(_.SourceName)
						   || _.SourceUri != null && this.Sources.Contains(_.SourceUri.AbsoluteUri),
				_ => false
			);
		}
コード例 #18
0
 public void CreateEntry(IEntry entry)
 {
     Check.Argument.IsNotNull(entry,
                              "entry");
     entry.ModifiedAt = DateTime.Now;
     entry.CreatedAt = DateTime.Now;
     entry.Author = User.GetCurrentUser();
     this.daoFactory.EntryDao.Save(entry);
 }
コード例 #19
0
        public static RouteValueDictionary GetRouteValues( IEntry entry)
        {
            if (null == entry)
            {
                return new RouteValueDictionary();
            }

            return new RouteValueDictionary(new { id = entry.Id, name = entry.Alias });
        }
コード例 #20
0
		/// <summary>
		/// 指定したエントリがこのソースから取得できるエントリとして扱うかどうかを取得します。
		/// </summary>
		/// <param name="entry">判定するエントリ。</param>
		/// <returns>このソースから取得できるエントリとして扱うかどうか。</returns>
		protected override bool StreamEntryMatches(IEntry entry)
		{
			return entry.TypeMatch
			(
				(Status _) => _.IsRetweet
						   && _.RetweetedStatus.UserName == _.Account.Name,
				_ => false
			);
		}
コード例 #21
0
        public void Save(IEntry entry)
        {
            Check.Argument.IsNotNull(entry,
                                     "entry");
            IEntry savedEntry = this.Load(entry.Id);
            entry.ModifiedAt = DateTime.Now;
            entry.Author = savedEntry.Author;

            this.daoFactory.EntryDao.Save(entry);
        }
コード例 #22
0
 private ActionResult ShowPage(IEntry entry)
 {
     ISiteAttributes attributes = this.serviceFactory.SiteService.LoadSiteAttributes();
     return View("Index",
                 new ViewModelHome
                     {
                         Entry = entry,
                         Attributes = attributes
                     });
 }
コード例 #23
0
 private void AddHomePage(ISitemap sitemap, IEntry page, string homePage)
 {
     ISitemapUrl url = this.domainObjectFactory.CreateSitemapUrl();
     url.Location = homePage;
     url.ChangeFrequency = CalculateFrequency(page.ModifiedAt);
     url.Priority = 0.9;
     url.LastModified = page.ModifiedAt.ToString();
     sitemap.Insert(0,
                    url);
 }
コード例 #24
0
ファイル: SearcherFactory.cs プロジェクト: aelveborn/njupiter
		public virtual IDirectorySearcher CreateSearcher(IEntry entry, SearchScope searchScope) {
			var searcher = new DirectorySearcherAdapter(entry, filterBuilder);
			searcher.SearchRoot = entry.GetDirectoryEntry();
			searcher.SearchScope = searchScope;
			searcher.ServerTimeLimit = serverConfig.TimeLimit;
			SetPageSizeIfNotDefault(searcher);
			SetSizeLimitIfNotDefault(searcher);
			searcher.PropertiesToLoad.Clear();
			return searcher;
		}
コード例 #25
0
        public List<IEntryItem> ParseEntryItems(IEntry entry, string pageContent)
        {
            Argument.IsNotNull(() => entry);
            Argument.IsNotNullOrWhitespace(() => pageContent);

            const string StartText = "<article id=\"";
            const string EndText = "</article>";

            var entryItems = new List<IEntryItem>();

            int firstIndex = pageContent.IndexOf(StartText);
            if (firstIndex == -1)
            {
                Log.Warning("Failed to find start of article, cannot return entry items for url '{0}'", entry.Url);
                return entryItems;
            }

            var lastIndex = pageContent.IndexOf(EndText, firstIndex);
            if (lastIndex == -1)
            {
                Log.Warning("Failed to find end of article, probably returning way too many entries for url '{0}'", entry.Url);
            }

            string subPageContent = pageContent.Substring(firstIndex, lastIndex - firstIndex);

            // Parse all href elements
            int currentIndex = 0;
            while (currentIndex < lastIndex)
            {
                int newIndex;
                string linkUrl = GetUrlFromPage(subPageContent, currentIndex, out newIndex);
                if (linkUrl == null)
                {
                    Log.Debug("No urls found, we probably parsed all links");
                    break;
                }

                if (!linkUrl.ToLower().Contains(entry.Url.ToLower()))
                {
                    Log.Debug("Found link '{0}'", linkUrl);

                    entryItems.Add(new EntryItem
                    {
                        Url = linkUrl,
                        EntryItemType = GetEntryItemType(linkUrl)
                    });
                }

                currentIndex = newIndex + 1;
            }

            return entryItems;
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: steveoleary/TeraDupe
        private static ulong GetHash(IEntry file)
        {
            ulong hashFromBytes;

            using (BinaryReader b = new BinaryReader(File.Open(file.Path, FileMode.Open)))
            {
                int length = (int)b.BaseStream.Length;
                int pos = length / 2;
                //TODO: If length is less than 2000 bytes read in entire file
                b.BaseStream.Seek(pos, SeekOrigin.Begin);
                hashFromBytes = GetHashFromBytes(b.ReadBytes(2000));
            }

            return hashFromBytes;
        }
コード例 #27
0
 protected override void AnalyzeEntry( IEntry entry )
 {
     if( entry is Content )
     {
         Content content = (Content)entry;
         foreach( char c in content.Text )
         {
             this.totalCount++;
             string upperc = Char.ToUpper( c ).ToString();
             if( this.histogram.ContainsKey( upperc ) )
                 this.histogram[upperc] = this.histogram[upperc] + 1;
             else
                 this.histogram[upperc] = 1;
         }
     }
 }
コード例 #28
0
ファイル: TextExport.cs プロジェクト: tkrehbiel/Tewpf
 private static void WriteEntry( TextWriter writer, IEntry entry )
 {
     if( entry is Content && entry.IsIncluded )
     {
         Content content = (Content)entry;
         if( content.Title != null )
         {
             writer.WriteLine( content.Title );
             writer.WriteLine();
         }
         writer.WriteLine( content.Text );
         if( content.HasChildren )
         {
             TextExport.WriteEntries( writer, entry.Children );
         }
     }
 }
コード例 #29
0
		/// <summary>
		/// 指定したエントリがこのソースから取得できるエントリとして扱うかどうかを取得します。
		/// </summary>
		/// <param name="entry">判定するエントリ。</param>
		/// <returns>このソースから取得できるエントリとして扱うかどうか。</returns>
		protected override bool StreamEntryMatches(IEntry entry)
		{
			return entry.TypeMatch
			(
				(Status _) =>
				{
					if (this.Query == null)
						return false;

					var words = this.Query.Split(' ', ' ');

					return words.Any()
						&& (words.All(_.UserName.Contains) || words.All(_.Text.Contains));
				},
				_ => false
			);
		}
コード例 #30
0
        public EntryViewModel(IEntry entry, IPleaseWaitService pleaseWaitService, ICrawlerService crawlerService, IProcessService processService, 
            ISettings settings)
        {
            Argument.IsNotNull(() => entry);
            Argument.IsNotNull(() => pleaseWaitService);
            Argument.IsNotNull(() => crawlerService);
            Argument.IsNotNull(() => processService);
            Argument.IsNotNull(() => settings);

            Entry = entry;
            _pleaseWaitService = pleaseWaitService;
            _crawlerService = crawlerService;
            _processService = processService;
            _settings = settings;

            OpenInBrowser = new Command(OnOpenInBrowserExecute, OnOpenInBrowserCanExecute);
        }
コード例 #31
0
        private static bool IsDeadEntry(IEntry entry)
        {
            CommonData data;

            return(!entry.IsLoading && !entry.Data.TryGetTarget(out data));
        }
コード例 #32
0
        public void GenerateCfg(string filePath)
        {
            // Сначала выпишем все зависимости для элементов
            // Обработаем все команды, привязанные к одиночным кнопкам и не являющимся первыми в каких-либо комбинациях
            //

            // Очередь по добавлению зависимостей
            Queue <Dependency> dependencies = new Queue <Dependency>();

            // Откроем файловый поток
            using (StreamWriter writer = File.CreateText(filePath)) // TODO: Проверить на конфигах разной длины
            {
                // Сначала запишем все зависимости
                // Т.к. один и тот же скрипт с зависимостями может быть на разных сочетаниях - сгруппируем все элементы по именам
                // Исходим из того, что одно и то же имя (первичный ключ) соответствует идентичным скриптам
                // и достаточно записать их зависимости один раз
                IEnumerable <IEntry> castedEntries = this.Entries.Values
                                                     .SelectMany(list => list.Select(e => (IEntry)e))
                                                     .Concat(this.defaultEntries);

                // Группируем по первичному ключу статические и полустатические элементы, т.к. зависимости у них одинаковые
                IEnumerable <IGrouping <string, IEntry> > groupedByPK =
                    castedEntries.Where(e => e.Type != EntryType.Dynamic).GroupBy(entry => entry.PrimaryKey);

                // Пройдемся по каждой группе и выпишем их зависимости
                foreach (IGrouping <string, IEntry> group in groupedByPK)
                {
                    IEntry firstElement = group.ElementAt(0);
                    dependencies.Enqueue(new Dependency()
                    {
                        Name = firstElement.PrimaryKey.ToString(), Commands = firstElement.Dependencies
                    });
                }

                // Теперь пройдемся по нестатическим элементам и тоже сохраним зависимости
                foreach (IEntry entry in castedEntries.Where(e => e.Type == EntryType.Dynamic))
                {
                    //string keyDescription = (entry.OnKeyDown != null ? entry.OnKeyDown : entry.OnKeyRelease).ToString();
                    //string dependencyName = $"{entry.PrimaryKey.ToString()} - {keyDescription}";

                    dependencies.Enqueue(
                        new Dependency()
                    {
                        Name     = $"{entry.PrimaryKey.ToString()}{(entry.Cmd != null? $" - {entry.Cmd}": "")}",//dependencyName,
                        Commands = entry.Dependencies
                    });
                }

                // Соберем все привязываемые элементы вместе
                IEnumerable <BindEntry> allBindEntries = new List <BindEntry>();

                // Объединяем все коллекции в единую
                allBindEntries = this.entries.Values.SelectMany(list => list);

                // Словарь с биндами по дефолту для ВСЕХ кнопок
                Dictionary <string, Executable> defaultKeyBinds = new Dictionary <string, Executable>();
                // Словарь динамических биндов, которые формируются по ходу итераций
                Dictionary <string, DynamicCmd> dynamicBinds = new Dictionary <string, DynamicCmd>();
                // Узнаем все клавиши, которые задействованы в конфиге
                HashSet <string> keySet = new HashSet <string>();
                foreach (KeySequence keySequence in this.entries.Keys)
                {
                    foreach (string key in keySequence.Keys)
                    {
                        keySet.Add(key);
                    }
                }
                // Пусть каждая из них по умолчанию разбиндена
                foreach (string key in keySet)
                {
                    dynamicBinds.Add(key, new DynamicCmd(new SingleCmd($"unbind {key}")));
                }

                // Обработаем сначала все команды, привязанные к одиночным кнопкам
                // и не являющимся первыми в каких-либо комбинациях, их мы обработаем позже
                foreach (var pair in this.entries.Where(e => e.Key.Keys.Length == 1 &&
                                                        this.entries.Where(innerEntry => innerEntry.Key.Keys.Length == 2 && innerEntry.Key[0] == e.Key[0]).Count() == 0))
                {
                    string           key     = pair.Key[0];
                    List <BindEntry> entries = pair.Value;

                    // Если ничего не привязано, то ничего и не делаем
                    if (entries.Count == 0)
                    {
                        continue;
                    }

                    // Узнаем статический ли он (может ли бинд на клавишу измениться)
                    // То есть проверяем есть ли сочетания, где вторая клавиша - текущая
                    bool isStaticKey = this.entries.Where(entry => entry.Key.Keys.Length == 2)
                                       .Where(innerEntry => innerEntry.Key.Keys[1] == key).Count() == 0;

                    // Проверим нужно ли генерировать мета-алиас к клавише.
                    // Нужно, если хотя бы одна команда задана при отжатии клавиши, либо установлено только отжатие,
                    // либо если клавиша не статическая и необходимо упростить название бинда в любом случае
                    bool needMetaScript = entries.Any(e => e.OnKeyDown == null || e.OnKeyRelease != null) || !isStaticKey;

                    if (needMetaScript)
                    {
                        // Если ко всей клавише привязан один мета-скрипт, то обходимся без генерации зависимостей
                        if (entries.Count == 1 && entries[0].IsMetaScript)//this.IsMetaScript(entries[0]))
                        {
                            // Просто создаем команду по типу: bind e +use
                            // Обновляя динамический бинд
                            dynamicBinds[key].Cmd = new BindCmd(key, entries[0].OnKeyDown);
                        }
                        else
                        {
                            string metaName = $"meta_{key}";
                            // Формируем мета-алиас
                            MetaCmd metaCmd = this.GenerateMetaCmd(metaName, entries);
                            // И вешаем его на клавишу
                            // Запоминаем для нестатической клавиши бинд по умолчанию, обновляя динамический бинд
                            dynamicBinds[key].Cmd = new BindCmd(key, metaCmd.AliasOnKeyDown.Name);
                            // Добавляем зависимость
                            dependencies.Enqueue(new Dependency()
                            {
                                Name = metaName, Commands = metaCmd
                            });
                        }
                    }
                    else
                    {
                        // Клавиша гарантированно статическая, обрабатывается только нажатие и нет мета-скриптов
                        BindCmd bind = new BindCmd(key, entries.Select(e => e.OnKeyDown));
                        // Обновляем динамическую команду с биндом
                        dynamicBinds[key].Cmd = bind;
                    }
                }


                // Обработали все одиночные кнопки, обработаем теперь все парные
                // Переведем бинды, привязанные к сочетанию клавиш в нормальный вид.
                // Получим все элементы словаря, где ключ состоит из 2 клавиш
                IEnumerable <KeyValuePair <KeySequence, List <BindEntry> > > combinedKeysEntries =
                    this.entries.Where(e => e.Key.Keys.Length == 2);

                // Группируем их по первой клавише
                IEnumerable <IGrouping <string, KeyValuePair <KeySequence, List <BindEntry> > > > groupedByFirstKey =
                    combinedKeysEntries.GroupBy(dictEntry => dictEntry.Key[0]);

                // Теперь нужно сформировать мета-скрипты, с именемами +meta_key1_key2/-meta_key1_key2
                // При чем каждая группа будет различаться значением key2
                foreach (var group in groupedByFirstKey)
                {
                    // Необходимо сформировать мета-скрипты для первой клавиши
                    // Для этого нужно получить набор команд привязанный чисто к этой клавише и туда добавить мета-скрипты
                    // Либо сформировать новую коллекцию
                    string      key1            = group.Key;
                    KeySequence monoKeySequence = new KeySequence(key1);

                    // Мета-скрипт для первой кнопки, который мы постепенно заполним командами
                    MetaCmd key1MetaCmd;
                    string  key1MetaScriptName = $"meta_{key1}";

                    // Если есть такой ключ
                    if (this.entries.ContainsKey(monoKeySequence))
                    {
                        key1MetaCmd = GenerateMetaCmd(key1MetaScriptName, this.entries[monoKeySequence]);
                    }
                    else
                    {
                        key1MetaCmd = new MetaCmd(key1MetaScriptName, new CommandCollection(), new CommandCollection());
                    }

                    // Пройдемся по комбинациям парам кнопок, у которых первая общая и заполним мета-скрипт первой кнопки командами
                    foreach (KeyValuePair <KeySequence, List <BindEntry> > pair in group)
                    {
                        KeySequence      keySequence = pair.Key;
                        List <BindEntry> cfgEntries  = pair.Value;

                        // Действие при нажатии определим далее
                        Executable onKey1DownKey2action;
                        // Действие при отжатии говорим брать из динамической команды
                        Executable onKey1ReleaseKey2action = dynamicBinds[keySequence[1]];

                        bool isWholeKeyMetaScript = cfgEntries.Count == 1 && cfgEntries[0].IsMetaScript;//this.IsMetaScript(cfgEntries[0]);

                        // Если ко всей клавише привязан один мета-скрипт, то обходимся без генерации зависимостей
                        if (isWholeKeyMetaScript)
                        {
                            onKey1DownKey2action = new BindCmd(keySequence[1], cfgEntries[0].OnKeyDown);
                        }
                        else
                        {
                            string metaScriptName = $"meta_{keySequence[0]}_{keySequence[1]}";
                            // Формируем мета-скрипт
                            MetaCmd metaCmd = this.GenerateMetaCmd(metaScriptName, cfgEntries);

                            // Добавляем в очередь зависимостей новую для сочетания кнопок
                            dependencies.Enqueue(new Dependency()
                            {
                                Name = metaScriptName, Commands = metaCmd
                            });

                            // Добавим бинд мета-скрипта на кнопку key2
                            // Два бинда на привязку
                            onKey1DownKey2action = new BindCmd(keySequence[1], metaCmd.AliasOnKeyDown.Name);
                        }

                        key1MetaCmd.AliasOnKeyDown.Commands.Add(onKey1DownKey2action);
                        key1MetaCmd.AliasOnKeyRelease.Commands.Add(onKey1ReleaseKey2action);
                    }

                    //// Сформировали набор команд при нажатии первой кнопки
                    //// Создадим мета-скрипт
                    BindCmd key1Bind = new BindCmd(key1, key1MetaCmd.AliasOnKeyDown.Name);
                    // Обновляем динамическую команду с биндом на 1-ю клавишу
                    dynamicBinds[key1].Cmd = key1Bind;
                    // Добавляем зависимость для первой клавиши
                    dependencies.Enqueue(new Dependency()
                    {
                        Name = key1MetaScriptName, Commands = key1MetaCmd
                    });
                }


                // --- Сгенерируем сам конфиг ---

                // Выпишем зависимости
                if (dependencies.Where(d => d.Commands.Count > 0).Count() > 0)
                {
                    writer.WriteLine("// --- Dependencies ---");
                    writer.WriteLine();

                    while (dependencies.Count > 0)
                    {
                        Dependency dependency = dependencies.Dequeue();

                        if (dependency.Commands.Count == 0)
                        {
                            continue;
                        }

                        writer.WriteLine($"// {dependency.Name}");
                        foreach (Executable cmd in dependency.Commands)
                        {
                            writer.WriteLine(cmd.ToString());
                        }
                        writer.WriteLine();
                    }
                    writer.WriteLine();
                }

                // Выпишем бинды
                IEnumerable <KeyValuePair <string, DynamicCmd> > dynamicBindPairs =
                    dynamicBinds.Where(p => p.Value.ToString().StartsWith("bind"));

                if (dynamicBindPairs.Count() > 0)
                {
                    writer.WriteLine("// --- Binds ---");
                    writer.WriteLine();

                    // Записываем только те команды, которые начинаются со слова bind
                    foreach (KeyValuePair <string, DynamicCmd> dynamicBindPair in dynamicBindPairs)
                    {
                        writer.WriteLine(dynamicBindPair.Value.ToString());
                    }

                    writer.WriteLine();
                }

                // Выпишем комментарий
                IEnumerable <IEntry> defaultEntries = this.defaultEntries.Where(e => e.Cmd != null);
                if (defaultEntries.Count() > 0)
                {
                    writer.WriteLine("// --- Default settings ---");
                    writer.WriteLine();

                    // Выпишем дефолтные параметры
                    foreach (IEntry entry in defaultEntries)
                    {
                        writer.WriteLine(entry.Cmd.ToString());
                    }

                    writer.WriteLine();
                }

                // Выведем в консоль фирменный комментарий
                writer.WriteLine("echo \"\"");
                writer.WriteLine("echo \"Config is created by Exide's Config Maker\"");
                writer.WriteLine("echo \"----------- blog.exideprod.com -----------\"");
                writer.WriteLine("echo \"------------ vk.com/exideprod ------------\"");
                writer.WriteLine("echo \"\"");
            } // Закрываем файловый поток
        }
コード例 #33
0
ファイル: Data.cs プロジェクト: WChrisK/HelionUnity
 /// <summary>
 /// Finds the latest entry for the name and namespace.
 /// </summary>
 /// <param name="name">The entry name.</param>
 /// <param name="resourceNamespace">The namespace.</param>
 /// <param name="entry">The found entry.</param>
 /// <returns>True if found, false if not (and entry is null in this
 /// case).</returns>
 public static bool TryFindExact(UpperString name, ResourceNamespace resourceNamespace, out IEntry entry)
 {
     return(entries.TryGetValue(name, resourceNamespace, out entry));
 }
コード例 #34
0
 public static void MapDrawPlaceholder(ICanvas canvas, RectF dirtyRect, IEntryDrawable drawable, IEntry view)
 => drawable.DrawPlaceholder(canvas, dirtyRect, view);
コード例 #35
0
 public static void UpdateCharacterSpacing(this MauiTextBox textBox, IEntry entry)
 {
     textBox.CharacterSpacing = entry.CharacterSpacing.ToEm();
 }
コード例 #36
0
 public void Save(IEntry entry)
 {
     SymbolTable.MakeCurrent(entry);
 }
コード例 #37
0
        public static IEntry GetEntryOrAddImport(IMEPackage Pcc, string importFullName)
        {
            //foreach (ImportEntry imp in Pcc.Imports)
            //{
            //    if (imp.GetFullPath == importFullName)
            //    {
            //        return imp;
            //    }
            //}

            var fullPathMappingList = new List <(string fullpath, IEntry entry)>();

            foreach (ImportEntry imp in Pcc.Imports)
            {
                fullPathMappingList.Add((imp.FullPath, imp));
            }
            foreach (ExportEntry exp in Pcc.Exports)
            {
                fullPathMappingList.Add((exp.FullPath, exp));
            }

            var directMapping = fullPathMappingList.Where(x => x.fullpath == importFullName).ToList();

            if (directMapping.Count == 1)
            {
                return(directMapping[0].entry);                          //direct single match
            }
            //Find an upstream entry to attach our import to (we can't add exports)
            string[] importParts   = importFullName.Split('.');
            int      upstreamCount = 1;

            IEntry upstreamEntryToAttachTo = null;
            string upstreamfullpath;

            while (upstreamCount < importParts.Length)
            {
                upstreamfullpath = string.Join(".", importParts, 0, importParts.Length - upstreamCount);
                var upstreammatchinglist = fullPathMappingList.Where(x => x.fullpath == upstreamfullpath).ToList();
                if (upstreammatchinglist.Where(x => x.entry is ExportEntry).HasExactly(1) || upstreammatchinglist.Where(x => x.entry is ImportEntry).HasExactly(1))
                {
                    upstreamEntryToAttachTo = upstreammatchinglist[0].entry;
                    break;
                }

                /*if (upstreamEntryToAttachTo != null)
                 * {
                 *  break;
                 * }*/
                upstreamCount++;
            }

            //upstreamImport = Pcc.Imports.FirstOrDefault(x => x.GetFullPath == upstream);



            //Check if this is an export instead

            /* itemAsImport = Pcc.Exports.FirstOrDefault(x => x.GetFullPath == importFullName && x.indexValue == 0);
             * if (itemAsImport != null)
             * {
             *  return itemAsImport;
             * }*/

            //Import doesn't exist, so we're gonna need to add it
            //But first we need to figure out what needs to be added.
            //string[] importParts = importFullName.Split('.');
            //List<int> upstreamLinks = new List<int>(); //0 = top level, 1 = next level... n = what we wanted to import

            /*ImportEntry upstreamImport = null;
             * string upstream = null;
             * while (upstreamCount < importParts.Count())
             * {
             *  upstreamfullpath = string.Join(".", importParts, 0, importParts.Count() - upstreamCount);
             *  upstreamImport = Pcc.Imports.FirstOrDefault(x => x.GetFullPath == upstreamfullpath);
             *
             *  if (upstreamImport != null)
             *  {
             *      break;
             *  }
             *  upstreamCount++;
             * }*/

            if (upstreamEntryToAttachTo == null)
            {
                //There is nothing we can attach to.
                Debug.WriteLine("cannot find a top level item to attach to for " + importFullName);
                return(null);
            }

            //Have an upstream import, now we need to add downstream imports.
            ImportEntry mostdownstreamimport = null;

            while (upstreamCount > 0)
            {
                upstreamCount--;
                string fullobjectname = string.Join(".", importParts, 0, importParts.Length - upstreamCount);
                Dictionary <string, string> importdbinfo = ImportClassDB[fullobjectname];

                var downstreamName = importParts[importParts.Length - upstreamCount - 1];
                Debug.WriteLine(downstreamName);
                int downstreamLinkIdx = upstreamEntryToAttachTo.UIndex;
                Debug.WriteLine(upstreamEntryToAttachTo.FullPath);

                var    downstreamPackageName = importdbinfo["packagefile"];
                string downstreamClassName   = importdbinfo["fullclasspath"];
                int    lastPeriodIndex       = downstreamClassName.LastIndexOf(".");
                if (lastPeriodIndex > 0)
                {
                    downstreamClassName = importdbinfo["fullclasspath"].Substring(lastPeriodIndex + 1);
                }

                //ImportEntry classImport = getOrAddImport();
                //int downstreamClass = 0;
                //if (classImport != null) {
                //    downstreamClass = classImport.UIndex; //no recursion pls
                //} else
                //{
                //    throw new Exception("No class was found for importing");
                //}

                mostdownstreamimport = new ImportEntry(Pcc)
                {
                    idxLink     = downstreamLinkIdx,
                    ClassName   = downstreamClassName,
                    ObjectName  = downstreamName,
                    PackageFile = downstreamPackageName
                };
                Pcc.AddImport(mostdownstreamimport);
                upstreamEntryToAttachTo = mostdownstreamimport;
            }
            return(mostdownstreamimport);
        }
コード例 #38
0
 public static void UpdatePlaceholder(this MauiTextBox textBox, IEntry entry)
 {
     textBox.PlaceholderText = entry.Placeholder ?? string.Empty;
 }
コード例 #39
0
 public static void UpdateIsPassword(this EditText editText, IEntry entry)
 {
     editText.SetInputType(entry);
 }
コード例 #40
0
 public static void UpdateReturnType(this EditText editText, IEntry entry)
 {
     editText.ImeOptions = entry.ReturnType.ToPlatform();
 }
コード例 #41
0
 public static void UpdateClearButtonVisibility(this EditText editText, IEntry entry, Drawable?clearButtonDrawable) =>
 UpdateClearButtonVisibility(editText, entry, () => clearButtonDrawable);
コード例 #42
0
 public static void UpdateKeyboard(this EditText editText, IEntry entry)
 {
     editText.SetInputType(entry);
 }
コード例 #43
0
        public static void CreateReachSpec(ExportEntry startNode, bool createTwoWay, ExportEntry destinationNode, string reachSpecClass, ReachSpecSize size, PropertyCollection externalGUIDProperties = null)
        {
            IMEPackage  Pcc = startNode.FileRef;
            ExportEntry reachSpectoClone = Pcc.Exports.FirstOrDefault(x => x.ClassName == "ReachSpec");

            if (externalGUIDProperties != null) //EXTERNAL
            {
                //external node

                //Debug.WriteLine("Num Exports: " + pcc.Exports.Count);
                if (reachSpectoClone != null)
                {
                    ExportEntry outgoingSpec = reachSpectoClone.Clone();
                    Pcc.AddExport(outgoingSpec);

                    IEntry reachSpecClassImp = GetEntryOrAddImport(Pcc, reachSpecClass); //new class type.

                    outgoingSpec.Class      = reachSpecClassImp;
                    outgoingSpec.ObjectName = reachSpecClassImp.ObjectName;

                    var            properties            = outgoingSpec.GetProperties();
                    ObjectProperty outgoingSpecStartProp = properties.GetProp <ObjectProperty>("Start");                                                                   //START
                    StructProperty outgoingEndStructProp = properties.GetProp <StructProperty>("End");                                                                     //Embeds END
                    ObjectProperty outgoingSpecEndProp   = outgoingEndStructProp.Properties.GetProp <ObjectProperty>(SharedPathfinding.GetReachSpecEndName(outgoingSpec)); //END
                    outgoingSpecStartProp.Value = startNode.UIndex;
                    outgoingSpecEndProp.Value   = 0;
                    var endGuid = outgoingEndStructProp.GetProp <StructProperty>("Guid");
                    endGuid.Properties = externalGUIDProperties; //set the other guid values to our guid values

                    //Add to source node prop
                    ArrayProperty <ObjectProperty> PathList = startNode.GetProperty <ArrayProperty <ObjectProperty> >("PathList");
                    PathList.Add(new ObjectProperty(outgoingSpec.UIndex));
                    startNode.WriteProperty(PathList);
                    outgoingSpec.WriteProperties(properties);


                    //Write Spec Size
                    SharedPathfinding.SetReachSpecSize(outgoingSpec, size.SpecRadius, size.SpecHeight);

                    //Reindex reachspecs.
                    SharedPathfinding.ReindexMatchingObjects(outgoingSpec);
                }
            }
            else
            {
                //Debug.WriteLine("Source Node: " + startNode.Index);

                //Debug.WriteLine("Num Exports: " + pcc.Exports.Count);
                //int outgoingSpec = pcc.ExportCount;
                //int incomingSpec = pcc.ExportCount + 1;


                if (reachSpectoClone != null)
                {
                    ExportEntry outgoingSpec = reachSpectoClone.Clone();
                    Pcc.AddExport(outgoingSpec);
                    ExportEntry incomingSpec = null;
                    if (createTwoWay)
                    {
                        incomingSpec = reachSpectoClone.Clone();
                        Pcc.AddExport(incomingSpec);
                    }

                    IEntry reachSpecClassImp = GetEntryOrAddImport(Pcc, reachSpecClass); //new class type.

                    outgoingSpec.Class      = reachSpecClassImp;
                    outgoingSpec.ObjectName = reachSpecClassImp.ObjectName;

                    var outgoingSpecProperties = outgoingSpec.GetProperties();
                    if (reachSpecClass == "Engine.SlotToSlotReachSpec")
                    {
                        outgoingSpecProperties.Add(new ByteProperty(1, "SpecDirection")); //We might need to find a way to support this edit
                    }

                    //Debug.WriteLine("Outgoing UIndex: " + outgoingSpecExp.UIndex);

                    ObjectProperty outgoingSpecStartProp = outgoingSpecProperties.GetProp <ObjectProperty>("Start");                                                       //START
                    StructProperty outgoingEndStructProp = outgoingSpecProperties.GetProp <StructProperty>("End");                                                         //Embeds END
                    ObjectProperty outgoingSpecEndProp   = outgoingEndStructProp.Properties.GetProp <ObjectProperty>(SharedPathfinding.GetReachSpecEndName(outgoingSpec)); //END
                    outgoingSpecStartProp.Value = startNode.UIndex;
                    outgoingSpecEndProp.Value   = destinationNode.UIndex;

                    //Add to source node prop
                    var PathList = startNode.GetProperty <ArrayProperty <ObjectProperty> >("PathList");
                    PathList.Add(new ObjectProperty(outgoingSpec.UIndex));
                    startNode.WriteProperty(PathList);

                    //Write Spec Size
                    SetReachSpecSize(outgoingSpecProperties, size.SpecRadius, size.SpecHeight);
                    outgoingSpec.WriteProperties(outgoingSpecProperties);

                    if (createTwoWay)
                    {
                        incomingSpec.Class      = reachSpecClassImp;
                        incomingSpec.ObjectName = reachSpecClassImp.ObjectName;
                        var incomingSpecProperties = incomingSpec.GetProperties();
                        if (reachSpecClass == "Engine.SlotToSlotReachSpec")
                        {
                            incomingSpecProperties.Add(new ByteProperty(2, "SpecDirection"));
                        }

                        ObjectProperty incomingSpecStartProp = incomingSpecProperties.GetProp <ObjectProperty>("Start");                                                       //START
                        StructProperty incomingEndStructProp = incomingSpecProperties.GetProp <StructProperty>("End");                                                         //Embeds END
                        ObjectProperty incomingSpecEndProp   = incomingEndStructProp.Properties.GetProp <ObjectProperty>(SharedPathfinding.GetReachSpecEndName(incomingSpec)); //END

                        incomingSpecStartProp.Value = destinationNode.UIndex;                                                                                                  //Uindex
                        incomingSpecEndProp.Value   = startNode.UIndex;


                        //Add reachspec to destination node's path list (returning)
                        var DestPathList = destinationNode.GetProperty <ArrayProperty <ObjectProperty> >("PathList");
                        DestPathList.Add(new ObjectProperty(incomingSpec.UIndex));
                        destinationNode.WriteProperty(DestPathList);

                        //destNode.WriteProperty(DestPathList);
                        SetReachSpecSize(incomingSpecProperties, size.SpecRadius, size.SpecHeight);

                        incomingSpec.WriteProperties(incomingSpecProperties);
                    }

                    //Reindex reachspecs.
                    SharedPathfinding.ReindexMatchingObjects(outgoingSpec);
                }
            }
        }
コード例 #44
0
 private static bool EntryMatches(IEntry entry, CommonData data)
 {
     return(entry.Id == data.Id && entry.DataType == data.GetType());
 }
コード例 #45
0
        public static async Task <IEnumerable <IBlob> > ListAllBlobsAsync(this IEntry directory)
        {
            var response = await directory.Bucket.ListAllEntries(directory.Key, false);

            return(response.OfType <IBlob>());
        }
コード例 #46
0
 public static void MapDrawIndicator(ICanvas canvas, RectF dirtyRect, IEntryDrawable drawable, IEntry view)
 => drawable.DrawIndicator(canvas, dirtyRect, view);
コード例 #47
0
 public static void UpdateIsReadOnly(this MauiTextBox textBox, IEntry entry)
 {
     textBox.IsReadOnly = entry.IsReadOnly;
 }
コード例 #48
0
        public List <DeltaEntry> Read(string Name, bool isGrouped = false)
        {
            List <DeltaEntry> deltaEntries = new List <DeltaEntry>();

            if (CommonConfig == null || Workbook == null)
            {
                return(deltaEntries);
            }
            IXLWorksheet keySheet = Workbook.Worksheets.Worksheet(Name);
            IXLRows      rows     = keySheet.RowsUsed();
            bool         firstRow = true;

            foreach (IXLRow row in rows)
            {
                if (firstRow)
                {
                    firstRow = false;
                    continue;
                }
                DeltaEntry entry = new DeltaEntry();

                // Index
                IXLCell indexCell = row.Cell("A");
                if (string.IsNullOrWhiteSpace(indexCell.GetString()))
                {
                    Logger.Error($"Empty index cell in row {row.RowNumber()}");
                    continue;
                }
                ushort index = ushort.MinValue;
                try
                {
                    index = indexCell.GetValue <ushort>();
                }
                catch (FormatException e)
                {
                    Logger.Error($"Unable to parse index '{indexCell.GetString()}' as ushort in row {row.RowNumber()}", e);
                    continue;
                }
                entry.Index = index;

                //Grouped Delta Entry
                if (isGrouped)
                {
                    entry.DataType = KeyEntries.First()
                                     .DataType;
                }
                else
                {
                    // Map DataType from KeyList
                    if (KeyEntries == null || KeyEntries.Count == 0)
                    {
                        Logger.Error("Cannot parse value of DeltaEntry, because KeyEntries are not available.");
                        continue;
                    }
                    if (KeyEntries.Count < entry.Index)
                    {
                        Logger.Error($"Cannot parse value of DeltaEntry, because index [{entry.Index}] of Delta Entry is not available in KeyEntries List (count is {KeyEntries.Count})."
                                     );
                        continue;
                    }
                    KeyEntry keyEntry = KeyEntries[entry.Index];
                    entry.DataType = keyEntry.DataType;
                }

                // Orcat
                IXLCell orcatCell = row.Cell("B");
                if (ParseOrcat(row, orcatCell, out byte?orcatValue) && orcatValue.HasValue)
                {
                    entry.Orcat = orcatValue.Value;
                }

                // Quality
                IXLCell qualityCell = row.Cell("C");
                if (ParseQuality(row, qualityCell, out ushort?qualityValue) && qualityValue.HasValue)
                {
                    entry.Quality = qualityValue.Value;
                }

                // Timestamp
                IXLCell timeStampCell = row.Cell("D");
                if (ParseTimeStamp(row, timeStampCell, out long?timeStampValue) && timeStampValue.HasValue)
                {
                    entry.TimeStamp = timeStampValue.Value;
                }

                // Value
                IXLCell valueCell  = row.Cell("E");
                IXLCell value2Cell = row.Cell("F");
                IEntry  baseEntry  = entry;
                if (!TryParse(valueCell, value2Cell, ref baseEntry))
                {
                    continue;
                }

                //Name
                if (isGrouped)
                {
                    IXLCell cellName = row.Cell("F");
                    if (!string.IsNullOrWhiteSpace(cellName.GetString()))
                    {
                        try
                        {
                            entry.Name = cellName.GetValue <string>();
                        }
                        catch (FormatException exception)
                        {
                            Logger.Error($"Unable to parse '{qualityCell.GetString()}' in row {row.RowNumber()} as UInt16", exception);
                        }
                    }
                }
                deltaEntries.Add(entry);
            }
            return(deltaEntries);
        }
コード例 #49
0
 public static void UpdateClearButtonVisibility(this MauiTextBox textBox, IEntry entry)
 {
     textBox.ClearButtonVisible = entry.ClearButtonVisibility == ClearButtonVisibility.WhileEditing;
 }
コード例 #50
0
 public static void UpdateText(this MauiTextBox textBox, IEntry entry)
 {
     textBox.Text = entry.Text;
 }
コード例 #51
0
ファイル: Data.cs プロジェクト: WChrisK/HelionUnity
 /// <summary>
 /// Looks up an entry by name. Note that this is not guaranteed to be
 /// the latest value, but rather the latest one from an implementation
 /// defined namespace.
 /// </summary>
 /// <param name="name">The entry name.</param>
 /// <param name="entry">The entry.</param>
 /// <returns>True if found, false if not.</returns>
 public static bool TryFindAny(UpperString name, out IEntry entry)
 {
     return(entries.TryGetAnyValue(name, out entry, out _));
 }
コード例 #52
0
ファイル: Data.cs プロジェクト: WChrisK/HelionUnity
 /// <summary>
 /// Finds the last loaded entry with the name provided.
 /// </summary>
 /// <param name="name">The entry name.</param>
 /// <param name="entry">The entry that was found.</param>
 /// <returns>True if found, false if not (and then entry is set to
 /// null).</returns>
 public static bool TryFindLatest(UpperString name, out IEntry entry)
 {
     return(nameToEntry.TryGetValue(name, out entry));
 }
コード例 #53
0
 public static void UpdateReturnType(this MauiTextBox textBox, IEntry entry)
 {
     textBox.InputScope = entry.ReturnType.ToNative();
 }
コード例 #54
0
ファイル: Data.cs プロジェクト: WChrisK/HelionUnity
 /// <summary>
 /// Finds the last loaded entry with the name provided. This will
 /// include the extension in searches.
 /// </summary>
 /// <param name="path">The entry path.</param>
 /// <param name="entry">The entry that was found.</param>
 /// <returns>True if found, false if not (and then entry is set to
 /// null).</returns>
 public static bool TryFindPath(UpperString path, out IEntry entry)
 {
     return(pathToEntry.TryGetValue(path, out entry));
 }
コード例 #55
0
 public static void UpdateIsTextPredictionEnabled(this EditText editText, IEntry entry)
 {
     editText.SetInputType(entry);
 }
コード例 #56
0
 public static void MapDrawBackground(ICanvas canvas, RectF dirtyRect, IEntryDrawable drawable, IEntry view)
 => drawable.DrawBackground(canvas, dirtyRect, view);
コード例 #57
0
 public static void UpdateMaxLength(this EditText editText, IEntry entry) =>
 UpdateMaxLength(editText, entry.MaxLength);
コード例 #58
0
 public static void UpdateVerticalTextAlignment(this MauiTextBox textBox, IEntry entry)
 {
     textBox.VerticalAlignment = entry.VerticalTextAlignment.ToNativeVerticalAlignment();
 }
コード例 #59
0
 public void Touch(IEntry entry)
 {
     SymbolTable.MakeCurrent(entry);
 }
コード例 #60
0
        private void btnFindText_Click(object sender, EventArgs e)
        {
            lstResults.Items.Clear();

            if (txtSearchDirectory.Text.Trim() != string.Empty && Directory.Exists(txtSearchDirectory.Text.Trim()))
            {
                if (txtFindText.Text.Trim() != string.Empty)
                {
                    string[] files   = Directory.GetFiles(txtSearchDirectory.Text.Trim(), "*.msbt", (chkSearchSubfolders.Checked ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
                    ListBox  lstTemp = new ListBox();

                    foreach (string file in files)
                    {
                        MSBT msbt = null;

                        try
                        {
                            msbt = new MSBT(file);
                        }
                        catch (InvalidMSBTException imex)
                        {
                            continue;
                        }

                        if (msbt.HasLabels)
                        {
                            lstTemp.Sorted = true;
                        }
                        else
                        {
                            lstTemp.Sorted = false;
                        }

                        lstTemp.Items.Clear();
                        for (int i = 0; i < msbt.TXT2.NumberOfStrings; i++)
                        {
                            if (msbt.HasLabels)
                            {
                                lstTemp.Items.Add(msbt.LBL1.Labels[i]);
                            }
                            else
                            {
                                lstTemp.Items.Add(msbt.TXT2.Strings[i]);
                            }
                        }

                        // Find the strings
                        for (int i = 0; i < msbt.TXT2.NumberOfStrings; i++)
                        {
                            IEntry ent = null;

                            if (msbt.HasLabels)
                            {
                                ent = msbt.LBL1.Labels[i];
                            }
                            else
                            {
                                ent = msbt.TXT2.Strings[i];
                            }

                            if (lstTemp.Items.Contains(ent))
                            {
                                lstTemp.SelectedItem = ent;
                            }

                            if (chkMatchCase.Checked)
                            {
                                if (msbt.FileEncoding.GetString(ent.Value).Contains(txtFindText.Text))
                                {
                                    SearchResult result = new SearchResult();
                                    result.Filename = file;
                                    result.Entry    = ent;
                                    result.Index    = lstTemp.SelectedIndex;
                                    lstResults.Items.Add(result);
                                }
                            }
                            else
                            {
                                if (msbt.FileEncoding.GetString(ent.Value).ToLower().Contains(txtFindText.Text.ToLower()))
                                {
                                    SearchResult result = new SearchResult();
                                    result.Filename = file;
                                    result.Entry    = ent;
                                    result.Index    = lstTemp.SelectedIndex;
                                    lstResults.Items.Add(result);
                                }
                            }
                        }
                    }
                }
            }

            if (lstResults.Items.Count == 0)
            {
                MessageBox.Show("Could not find \"" + txtFindText.Text + "\".", "Find", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }