Example #1
0
 public string GetSummonerGamesById()
 {
     try
     {
         using (this.client = new WebClient())
         {
             summonerGamesResponse = client.DownloadString(URLManager.SummonerGamesById(summonerId));
         }
         responseCode = "#02";
     }
     catch (Exception ex)
     {
         return("#03");
     }
     try
     {
         idName = ReaderManager.FileReader(jsonFilePath);
         SummonerGames summonerGamesModel = SerializerManager.SummonerGamesSerializer(summonerGamesResponse);
         this.SummonerGames = NameManager.GamesNameFiller(summonerGamesModel, this.summonerName, idName);
     }
     catch (Exception ex)
     {
         throw new ArgumentException("Either response serializing or finding name went wrong " + ex.Message);
     }
     return(responseCode);
 }
Example #2
0
        private void MainFrm_Load(object sender, EventArgs e)
        {

            // reader is our handle to the physical reader.
            //reader = new RFIDReader(this);
            handleTags = new WispHandleTags();
            readerMgr = new ReaderManager(this, handleTags);

            log = new WispLoggingManager();

            // init the saturn object.
            saturn = new SaturnDemo.Saturn();

            // Init midi config
            midi = new MIDI_Control_Demo.Midi();

            // Init bink bonk
            binkBonk = new BinkBonk.BinkBonk_Demo();
            handleTags.setBinkBonkCallback(binkBonk);

            // Setup axis labels for the various graphs.
            InitSOCGraph();
            InitTempGraph();

            // Other init code
            InitTagStats();

            // Grab initial component sizes for easy resize
            formInitialHeight = this.Height;
            pnlTagListInitialHeight = dgvTagStats.Height;

            // Init GUI operational mode to idle (disconnected)
            SetMode(ReaderManager.GuiModes.Idle);
        }
 public ReaderHistoryService()
 {
     uow = new LibraryUow();
     readerHistoryManager = new ReaderHistoryManager(uow, new ReaderHistoryFacade(uow));
     readerManager        = new ReaderManager(uow, new ReaderFacade(uow), new UsersFacade(uow));
     userManager          = new UserManager(uow, new UsersFacade(uow), readerManager);
 }
Example #4
0
        private void MainFrm_Load(object sender, EventArgs e)
        {
            // set position of form
            //base.Location = new Point(800, 150);

            // reader is our handle to the physical reader.
            //reader = new RFIDReader(this);
            handleTags = new WispHandleTags();
            readerMgr = new ReaderManager(this, handleTags);

            log = new WispLoggingManager();
            
            // init the saturn object.
            saturn = new Saturn();

            // Setup axis labels for the various graphs.
            InitSOCGraph();
            InitTempGraph();

            // Other init code
            InitTagStats();

            // Store initial sizes (for resize operation).
            formInitialSize = this.Size;
            pnlTagListInitialSize = pnlTagList.Size;

            // Init GUI operational mode to idle (disconnected)
            SetMode(ReaderManager.GuiModes.Idle);
        }
Example #5
0
        public void Close()
        {
            // Close the connection
            _setupManager = null;
            _readerManager = null;
            _infoManager = null;

            _dataManager.Close();
            //Console.WriteLine("Connection Closed");
        }
Example #6
0
        public void Add_1()
        {
            var rm = new ReaderManager();

            rm.AsEnumerable().Count().Is(0);
            rm.Add(new Reader1());
            rm.AsEnumerable().Count().Is(1);
            rm.Add(new Reader2());
            rm.AsEnumerable().Count().Is(2);
        }
Example #7
0
        public void FilterString_1()
        {
            var rm = new ReaderManager();

            rm.FilterString.Is("All files|*.*");
            rm.Add(new Reader1());
            rm.FilterString.Is("All known files|*.foo;*.bar|Foo file|*.foo|Bar file|*.bar|All files|*.*");
            rm.Add(new Reader2());
            rm.FilterString.Is("All known files|*.foo;*.bar;*.j;*.john;*.doe|Foo file|*.foo|Bar file|*.bar|john doe|*.j;*.john;*.doe|All files|*.*");
        }
Example #8
0
        /// <summary>
        /// Init readers managers
        /// </summary>
        private static void InitReadersManagers()
        {
            // Add PCSC reader manager
            IReader pcsc = new PcscReader();

            ReaderManager.Add(pcsc.TypeName, pcsc);

            // Add SmartMouse reader manager
            IReader smouse = new SmartMouseReader();

            ReaderManager.Add(smouse.TypeName, smouse);
        }
Example #9
0
        public static void Main(string[] args)
        {
            AdminManager  adminModel   = new AdminManager();
            BookManager   booksModel   = new BookManager();
            ReaderManager readersModel = new ReaderManager();
            RentalManager rentalModel  = new RentalManager();

            rental = new RentalController("server=localhost;port=3306;uid=root;pwd=root;database=Library", booksModel, rentalModel, readersModel, adminModel);
            while (true)
            {
                PrintStartInfo();
            }
        }
Example #10
0
 void Initial()
 {
     _LogManager           = new LogManager();
     _RobotManager         = new RobotManager();
     _ReaderManager        = new ReaderManager();
     _CommunicationManager = new CommunicationManager();
     _SensorManager        = new SensorManager();
     _AlarmManager         = new AlarmManager();
     _RecipeManager        = new RecipeManager();
     _SkidPlatformManager  = new SkidPlatformManager();
     _ExernalAxisManager   = new ExernalAxisManager();
     _MissionManager       = new MissionManager(_RobotManager, _RecipeManager, _AlarmManager
                                                , _CommunicationManager, _SkidPlatformManager, _ExernalAxisManager, _LogManager);
 }
Example #11
0
        public static ReaderInfo GetReader
        (
            [NotNull] string ticket
        )
        {
            Code.NotNullNorEmpty(ticket, "ticket");

            using (IrbisConnection connection = GetIrbisConnection())
            {
                ReaderManager manager = new ReaderManager(connection);
                ReaderInfo    result  = manager.GetReader(ticket);

                return(result);
            }
        }
Example #12
0
        public RentalController(String connStr, BookManager books, RentalManager rental, ReaderManager readers, AdminManager admins)
        {
            _connection = new MySqlConnection(connStr);
            _connection.Open();

            books.Connection   = _connection;
            rental.Connection  = _connection;
            readers.Connection = _connection;
            admins.Connection  = _connection;


            _books   = books;
            _rental  = rental;
            _readers = readers;
            _admins  = admins;
        }
Example #13
0
 /// <summary>
 /// A hook for extending classes to close additional resources that were used.
 /// The default implementation closes the <see cref="Index.IndexReader"/> as well as the
 /// <see cref="ITaxonomyWriterCache"/> instances that were used.
 /// <para>
 /// <b>NOTE:</b> if you override this method, you should include a
 /// <c>base.CloseResources()</c> call in your implementation.
 /// </para>
 /// </summary>
 protected virtual void CloseResources()
 {
     lock (this)
     {
         if (initializedReaderManager)
         {
             readerManager.Dispose();
             readerManager            = null;
             initializedReaderManager = false;
         }
         if (cache != null)
         {
             cache.Dispose();
         }
     }
 }
Example #14
0
 /// <summary>
 /// Opens a <see cref="ReaderManager"/> from the internal <see cref="IndexWriter"/>.
 /// </summary>
 private void InitReaderManager()
 {
     if (!initializedReaderManager)
     {
         lock (this)
         {
             // verify that the taxo-writer hasn't been closed on us.
             EnsureOpen();
             if (!initializedReaderManager)
             {
                 readerManager = new ReaderManager(indexWriter, false);
                 shouldRefreshReaderManager = false;
                 initializedReaderManager   = true;
             }
         }
     }
 }
Example #15
0
        internal IrbisExecutive
        (
            ManagedClient64 client
        )
        {
            if (ReferenceEquals(client, null))
            {
                throw new ArgumentNullException("client");
            }

            Client       = client;
            Queries      = new QueryManager();
            Magazines    = new MagazineManager(Client);
            Transactions = new IrbisTransactionManager(Client);
            Readers      = new ReaderManager(Client);
            Requests     = new RequestManager();
        }
Example #16
0
        /// <summary>
        /// Returns an asynchronous stream over `TagEvent`s generated by `reader` with an optional timeout
        /// </summary>
        public static async IAsyncEnumerable <TagEvent> EventStream(
            ReaderManager reader,
            TimeSpan?timeout = null,
            [EnumeratorCancellation] CancellationToken enumCancellation = default
            )
        {
            CancellationTokenSource timeoutTokenSource  = null;
            CancellationTokenSource combinedTokenSource = null;

            if (timeout != null)
            {
                timeoutTokenSource = new CancellationTokenSource();
                timeoutTokenSource.CancelAfter(timeout.Value);
                combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(enumCancellation, timeoutTokenSource.Token);
            }
            var cancellationToken = combinedTokenSource?.Token ?? enumCancellation;

            var buffer         = new BufferBlock <TagEvent>();
            var tagDataHandler = new TagDataListener(tagData => buffer.Post(tagData));

            try
            {
                reader.reader.OnRoAccessReportReceived += tagDataHandler.OnRoAccessReport;
                while (!cancellationToken.IsCancellationRequested)
                {
                    TagEvent tagEvent;
                    try
                    {
                        tagEvent = await buffer.ReceiveAsync(cancellationToken);
                    }
                    catch (TaskCanceledException)
                    {
                        break;
                    }
                    yield return(tagEvent);
                }
            }
            finally
            {
                reader.reader.OnRoAccessReportReceived -= tagDataHandler.OnRoAccessReport;

                timeoutTokenSource?.Dispose();
                combinedTokenSource?.Dispose();
            }
        }
Example #17
0
        protected override void OnStart()
        {
            // Copy Tego License
            WriteResourceToFile("Example.TegoOS.Lic", FileHelper.Combine(FileHelper.GetLocalDirectory(), "TegoOS.Lic"));

            // Remember to add Bluetooth permission in package manifest, info.plist, etc. for each platform's app
            readerManager = new ReaderManager();

            Reader = readerManager.CreateReader(typeof(SimulatedReader));
            SimulatedTagPopulation.AddUniqueTag("E2817000");
            SimulatedTagPopulation.AddUniqueTag("E2817000");

            //Reader = readerManager.CreateReader(typeof(TechnologySolutionsReader));

            //Reader = readerManager.CreateReader(typeof(ZetiReader));

            ConnectReader();
        }
Example #18
0
 private void OpenCommand_Execute(string[] filenames, int index, bool single_tab, object tag)
 {
     Busy = true;
     Task.Run(() =>
     {
         ITableController[] result;
         if (single_tab && filenames.Length > 1)
         {
             var bundle = ReaderManager.Read(filenames, index);
             if (!bundle.Assets.Any(a => a.TransPairs.Any()))
             {
                 throw new InvalidOperationException("All files have no contents.");
             }
             result = new[] { TableController.LoadBilingualAssets(bundle) };
         }
         else
         {
             result = filenames.Select(f =>
             {
                 var bundle = ReaderManager.Read(f, index);
                 if (!bundle.Assets.Any(a => a.TransPairs.Any()))
                 {
                     throw new InvalidOperationException(string.Format("{0} has no contents.", f));
                 }
                 return(TableController.LoadBilingualAssets(bundle));
             }).ToArray();
         }
         Array.ForEach(result, tc => { tc.Tag = tag; });
         return(result);
     }).ContinueWith(worker =>
     {
         if (worker.IsFaulted)
         {
             InvokeThrowTaskException(worker);
         }
         else
         {
             _Tables.AddRange(worker.Result);
             RaisePropertyChanged("Tables");
         }
         Busy = false;
     }, Scheduler);
 }
Example #19
0
        public void Reader_FilterIndex_1()
        {
            var rm = new ReaderManager();

            rm.Add(new Reader1());
            rm.Add(new Reader2());

            // Reader1 and Reader2 have priorities 1 and 2 respectively, so
            // Reader1 will be listed first in the filter, but
            // Reader2 will be considered first when auto-detecting.

            rm.Read("filename").Assets.ElementAt(0).Original.Is("Reader2.-1");
            rm.Read("filename", 0).Assets.ElementAt(0).Original.Is("Reader2.-1");
            rm.Read("filename", 1).Assets.ElementAt(0).Original.Is("Reader1.0");
            rm.Read("filename", 2).Assets.ElementAt(0).Original.Is("Reader1.1");
            rm.Read("filename", 3).Assets.ElementAt(0).Original.Is("Reader2.0");
            rm.Read("filename", 4).Assets.ElementAt(0).Original.Is("Reader2.-1");
            AssertEx.Catch <ArgumentOutOfRangeException>(() => rm.Read("filename", -2));
            AssertEx.Catch <ArgumentOutOfRangeException>(() => rm.Read("filename", 6));
        }
Example #20
0
        public IAssetBundle Read(string filename, int filterindex)
        {
            if (filterindex < 0)
            {
                // Excel can open virtually any text-based file formats,
                // but it could take incredibly long time if the file is not suitable for a table.
                // If a user opened an unknown file with disfr using "All files" file types,
                // assuming it is an XLIFF, but it was actually not,
                // disfr's automatic file detection scheme eventually passes the file to this method
                // (unless another reader accepted it), and the file could occupy Excel for long,
                // causing disfr to appear as though it hung up.
                // I think we should avoid such a behaviour.
                if (!PrimaryExtensions.Any(ext => filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase)))
                {
                    return(null);
                }
            }

            var full_pathname = Path.GetFullPath(filename);

            return(LoaderAssetBundle.Create(
                       ReaderManager.FriendlyFilename(filename),
                       () => ReadAssets(full_pathname)));
        }
Example #21
0
 private void OpenCommand_Execute(string[] filenames, int index, bool single_tab, object tag)
 {
     Busy = true;
     Task.Run(() =>
     {
         ITableController[] result;
         var started = DateTime.UtcNow;
         if (single_tab && filenames.Length > 1)
         {
             result = new[]
             {
                 TableController.LoadBilingualAssets(ReaderManager.Read(filenames, index))
             };
         }
         else
         {
             result = filenames.Select(f =>
                                       TableController.LoadBilingualAssets(ReaderManager.Read(f, index))
                                       ).ToArray();
         }
         Array.ForEach(result, tc => { tc.Tag = tag; });
         return(result);
     }).ContinueWith(worker =>
     {
         if (worker.IsFaulted)
         {
             InvokeThrowTaskException(worker);
         }
         else
         {
             _Tables.AddRange(worker.Result);
             RaisePropertyChanged("Tables");
         }
         Busy = false;
     }, Scheduler);
 }
 /// <summary>
 /// Opens a <seealso cref="ReaderManager"/> from the internal <seealso cref="IndexWriter"/>. 
 /// </summary>
 private void InitReaderManager()
 {
     if (!initializedReaderManager)
     {
         lock (this)
         {
             // verify that the taxo-writer hasn't been closed on us.
             EnsureOpen();
             if (!initializedReaderManager)
             {
                 readerManager = new ReaderManager(indexWriter, false);
                 shouldRefreshReaderManager = false;
                 initializedReaderManager = true;
             }
         }
     }
 }
 /// <summary>
 /// A hook for extending classes to close additional resources that were used.
 /// The default implementation closes the <seealso cref="IndexReader"/> as well as the
 /// <seealso cref="TaxonomyWriterCache"/> instances that were used. <br>
 /// <b>NOTE:</b> if you override this method, you should include a
 /// <code>super.closeResources()</code> call in your implementation.
 /// </summary>
 protected virtual void CloseResources()
 {
     lock (this)
     {
         if (initializedReaderManager)
         {
             readerManager.Dispose();
             readerManager = null;
             initializedReaderManager = false;
         }
         if (cache != null)
         {
             cache.Close();
         }
     }
 }
Example #24
0
        public OpusDto(string userName, Opus opus, ProjectManager projectUnitOfWork, ReaderManager readerManager)
        {
            Id          = opus.Id;
            IsPublished = opus.IsPublished;
            IsFallback  = opus.IsFallback;
            OpusName    = opus.Name;
            ProjectId   = opus.Project.Id;

            // on display: TRUE --> Author; FALSE --> Co-Author
            IsAuthor       = opus.UserIsTeamLead(userName);
            TeamMemberRole = opus.Project
                             .Team
                             .Members.Single(m => m.Member.UserName == userName)
                             .Role.ContributorRoles.ToString();
            Authors = opus.Project.Team.Members
                      .OrderByDescending(x => x.TeamLead)
                      .Select(x => new MemberDto {
                MemberId      = x.Id,
                FullName      = x.Member.Profile.FullName,
                Roles         = x.GetLocalizedContributorRoles(),
                ThumbnailPath = String.Format(Constants.Images.ApiUrlTemplate, x.Member.Profile.Id, Constants.Images.StandardTypes.Profile)
            });

            // JOERG:
            // We need Name; Authors; Role of User; New Messages; Cover Image
            if (opus.IsPublished && opus.Published != null)
            {
                Title       = opus.Published.Title;
                Description = opus.Project.Description;
                CoverUrl    = String.Format(Constants.Images.ApiUrlTemplate, opus.Published.Id, Constants.Images.StandardTypes.Project);
                NewMessages = projectUnitOfWork.GetTopWorkroomMessages(opus.Published.Id)
                              .Where(x => !x.Closed)
                              .Select(x => new CommentDto {
                    Subject  = x.Name,
                    Text     = x.Content,
                    UserName = x.Owner.UserName
                });

                PublishedNewMessages = readerManager.GetPublishedComments(opus.Published.Id)
                                       .Where(x => !x.Closed)
                                       .Select(x => new CommentDto {
                    Subject  = x.Name,
                    Text     = x.Content,
                    UserName = x.Owner.UserName
                });;
                SubTitle = opus.Published.SubTitle;
            }
            else
            {
                Title       = opus.Project.Name;
                Description = opus.Project.Description;
                CoverUrl    = string.Format(Constants.Images.ApiUrlTemplate, opus.Project.Id, Constants.Images.StandardTypes.Project);
                NewMessages = projectUnitOfWork.GetTopWorkroomMessages(opus.Project.Id)
                              .Where(x => !x.Closed)
                              .Select(x => new CommentDto {
                    Subject  = x.Name,
                    Text     = x.Content,
                    UserName = x.Owner.UserName
                });
            }
        }
Example #25
0
        private static void Main()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                string connectionString = ConfigurationUtility
                                          .GetString("connectionString")
                                          .ThrowIfNull("connectionString not set");
                Threshold = IrbisDate.ConvertStringToDate
                            (
                    ConfigurationUtility
                    .GetString("threshold")
                    .ThrowIfNull("threshold not set")
                            );
                LowerBound = DateTime.MinValue;
                string lowerText = ConfigurationUtility.GetString("lowerBound");
                if (!string.IsNullOrEmpty(lowerText))
                {
                    LowerBound = IrbisDate.ConvertStringToDate(lowerText);
                }

                Console.WriteLine("Loading readers");

                List <ReaderInfo> allReaders = new List <ReaderInfo>();
                OldReaders = new BlockingCollection <ReaderInfo>();

                using (IrbisConnection connection
                           = new IrbisConnection(connectionString))
                {
                    ReaderManager manager = new ReaderManager(connection)
                    {
                        OmitDeletedRecords = true
                    };
                    manager.BatchRead += (obj, ea) => Console.Write(".");

                    string[] databases = ConfigurationUtility.GetString("databases")
                                         .ThrowIfNull("databases not specified")
                                         .Split
                                         (
                        new[] { ' ', ';', ',' },
                        StringSplitOptions.RemoveEmptyEntries
                                         );

                    foreach (string database in databases)
                    {
                        Console.WriteLine
                        (
                            "Database: {0}, records: {1}",
                            database,
                            connection.GetMaxMfn(database) - 1
                        );

                        allReaders.AddRange
                        (
                            manager.GetAllReaders(database)
                        );

                        Console.WriteLine();
                    }
                }

                WriteDelimiter();

                Console.WriteLine("Merging");
                Console.WriteLine("Records before merging: {0}", allReaders.Count);

                allReaders = ReaderManager.MergeReaders(allReaders);

                Console.WriteLine("Records after merging: {0}", allReaders.Count);
                WriteDelimiter();

                Console.WriteLine("Filtering");

                ParallelOptions options = new ParallelOptions
                {
                    MaxDegreeOfParallelism = 4
                };
                Parallel.ForEach(allReaders, options, ProcessReader);

                ReaderInfo[] oldReaders = OldReaders.ToArray();

                WriteDelimiter();

                Console.WriteLine("Sorting");

                oldReaders = oldReaders.OrderBy
                             (
                    reader => reader.FullName
                             )
                             .ToArray();

                WriteDelimiter();

                Console.WriteLine
                (
                    "Create table: {0} lines",
                    oldReaders.Length
                );

                Workbook workbook = new Workbook();
                workbook.CreateNewDocument();
                Worksheet worksheet = workbook.Worksheets[0];

                int row = 0;

                worksheet.Cells[row, 0].Value = "ФИО";
                worksheet.Cells[row, 1].Value = "Билет";
                worksheet.Cells[row, 2].Value = "Регистрация";
                worksheet.Cells[row, 3].Value = "Кол-во";
                worksheet.Cells[row, 4].Value = "Последнее событие";
                worksheet.Cells[row, 5].Value = "Отделы";

                DrawBorders(worksheet, row);

                row++;

                for (int i = 0; i < oldReaders.Length; i++)
                {
                    if (i % 100 == 0)
                    {
                        Console.Write(".");
                    }

                    ReaderInfo reader   = oldReaders[i];
                    string     lastDate = (string)reader.UserData;
                    if (string.IsNullOrEmpty(lastDate))
                    {
                        lastDate = "--";
                    }

                    string departments = StringUtility.Join
                                         (
                        ", ",
                        reader.Registrations
                        .Select(reg => reg.Chair)
                        .Concat
                        (
                            reader.Visits
                            .Select(visit => visit.Department)
                        )
                        .NonEmptyLines()
                        .Distinct()
                                         );

                    worksheet.Cells[row, 0].Value = reader.FullName;
                    worksheet.Cells[row, 1].Value = reader.Ticket;
                    worksheet.Cells[row, 2].Value = reader.RegistrationDate
                                                    .ToShortDateString();
                    worksheet.Cells[row, 3].Value = reader.Visits.Length
                                                    + reader.Registrations.Length;
                    worksheet.Cells[row, 4].Value = lastDate;
                    worksheet.Cells[row, 5].Value = departments;

                    DrawBorders(worksheet, row);

                    row++;
                }

                WriteDelimiter();

                workbook.SaveDocument(OutputFile);

                Console.WriteLine("All done");

                stopwatch.Stop();
                TimeSpan elapsed = stopwatch.Elapsed;
                Console.WriteLine("Elapsed: {0}", elapsed);
                Console.WriteLine("Old readers: {0}", oldReaders.Length);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Example #26
0
        private void SetupManagers()
        {
            // Open a connection to the reader
            _dataManager = new DataManager(DataManager.ConnectionTypes.SOCKET, _ipAddress, 0);
            _dataManager.OpenConnection();
            //Console.WriteLine("Connection Opened");

            // Get the reader's name
            _infoManager = new InfoManager(_dataManager);
            String v = _infoManager.Name;
            //Console.WriteLine("Name: " + v);
            _infoManager = null;

            // Login as administrator
            _readerManager = new ReaderManager(_dataManager);
            if (!_readerManager.Login(_login, _password))
            {
                throw new Exception("Login attempt failed: " + _readerManager.LastErrorMessage);
            }

            v = _readerManager.WhoAmI();
            //Console.WriteLine("Login: " + v);
        }
Example #27
0
 public IAssetBundle Read(string filename, int filterindex)
 {
     return(LoaderAssetBundle.Create(
                ReaderManager.FriendlyFilename(filename),
                () => ReadAsset(filename, filterindex < 0)));
 }
Example #28
0
 public SuccessController()
 {
     _projectUnitOfWork  = UnitOfWork <ProjectManager>();
     _readerUnitOfWork   = UnitOfWork <ReaderManager>();
     _resourceUnitOfWork = UnitOfWork <ResourceManager>();
 }
Example #29
0
        public OverviewDto(string userName, Opus opus, ProjectManager projectUnitOfWork, ReaderManager readerManager) : base(userName, opus, projectUnitOfWork, readerManager)
        {
            var projId = opus.Project.Id;
            var pckgs  = projectUnitOfWork.GetAssignedMarketingPackage(projId) ?? projectUnitOfWork.GetAndAddMarketingPackage(opus.Project);

            if (opus.Published != null)
            {
                PublishingDate = opus.Published.CreatedAt;
                Keywords       = opus.Published.ExternalPublisher.Keywords.Split(';', ',');
                Categories     = opus.Published.Catalogs.Select(c => c.Name);
                License        = pckgs.GetLocalizedMarketingType();
                Language       = new CultureInfo(opus.LocaleId).NativeName;
                Location       = "Berlin"; // TODO: Manage publishers and their location
            }
        }
        // we need to guarantee that if several threads call this concurrently, only
        // one executes it, and after it returns, the cache is updated and is either
        // complete or not.
        private void PerhapsFillCache()
        {
            lock (this)
            {
                if (cacheMisses.Get() < cacheMissesUntilFill)
                {
                    return;
                }

                if (!shouldFillCache)
                {
                    // we already filled the cache once, there's no need to re-fill it
                    return;
                }
                shouldFillCache = false;

                InitReaderManager();

                bool aborted = false;
                DirectoryReader reader = readerManager.Acquire();
                try
                {
                    TermsEnum termsEnum = null;
                    DocsEnum docsEnum = null;
                    foreach (AtomicReaderContext ctx in reader.Leaves)
                    {
                        Terms terms = ctx.AtomicReader.Terms(Consts.FULL);
                        if (terms != null) // cannot really happen, but be on the safe side
                        {
                            termsEnum = terms.Iterator(termsEnum);
                            while (termsEnum.Next() != null)
                            {
                                if (!cache.Full)
                                {
                                    BytesRef t = termsEnum.Term();
                                    // Since we guarantee uniqueness of categories, each term has exactly
                                    // one document. Also, since we do not allow removing categories (and
                                    // hence documents), there are no deletions in the index. Therefore, it
                                    // is sufficient to call next(), and then doc(), exactly once with no
                                    // 'validation' checks.
                                    FacetLabel cp = new FacetLabel(FacetsConfig.StringToPath(t.Utf8ToString()));
                                    docsEnum = termsEnum.Docs(null, docsEnum, DocsEnum.FLAG_NONE);
                                    bool res = cache.Put(cp, docsEnum.NextDoc() + ctx.DocBase);
                                    Debug.Assert(!res, "entries should not have been evicted from the cache");
                                }
                                else
                                {
                                    // the cache is full and the next put() will evict entries from it, therefore abort the iteration.
                                    aborted = true;
                                    break;
                                }
                            }
                        }
                        if (aborted)
                        {
                            break;
                        }
                    }
                }
                finally
                {
                    readerManager.Release(reader);
                }

                cacheIsComplete = !aborted;
                if (cacheIsComplete)
                {
                    lock (this)
                    {
                        // everything is in the cache, so no need to keep readerManager open.
                        // this block is executed in a sync block so that it works well with
                        // initReaderManager called in parallel.
                        readerManager.Dispose();
                        readerManager = null;
                        initializedReaderManager = false;
                    }
                }
            }
        }
Example #31
0
        // we need to guarantee that if several threads call this concurrently, only
        // one executes it, and after it returns, the cache is updated and is either
        // complete or not.
        private void PerhapsFillCache()
        {
            lock (this)
            {
                if (cacheMisses < cacheMissesUntilFill)
                {
                    return;
                }

                if (!shouldFillCache)
                {
                    // we already filled the cache once, there's no need to re-fill it
                    return;
                }
                shouldFillCache = false;

                InitReaderManager();

                bool            aborted = false;
                DirectoryReader reader  = readerManager.Acquire();
                try
                {
                    TermsEnum termsEnum = null;
                    DocsEnum  docsEnum  = null;
                    foreach (AtomicReaderContext ctx in reader.Leaves)
                    {
                        Terms terms = ctx.AtomicReader.GetTerms(Consts.FULL);
                        if (terms != null) // cannot really happen, but be on the safe side
                        {
                            termsEnum = terms.GetIterator(termsEnum);
                            while (termsEnum.Next() != null)
                            {
                                if (!cache.IsFull)
                                {
                                    BytesRef t = termsEnum.Term;
                                    // Since we guarantee uniqueness of categories, each term has exactly
                                    // one document. Also, since we do not allow removing categories (and
                                    // hence documents), there are no deletions in the index. Therefore, it
                                    // is sufficient to call next(), and then doc(), exactly once with no
                                    // 'validation' checks.
                                    FacetLabel cp = new FacetLabel(FacetsConfig.StringToPath(t.Utf8ToString()));
                                    docsEnum = termsEnum.Docs(null, docsEnum, DocsFlags.NONE);
                                    bool res = cache.Put(cp, docsEnum.NextDoc() + ctx.DocBase);
                                    Debug.Assert(!res, "entries should not have been evicted from the cache");
                                }
                                else
                                {
                                    // the cache is full and the next put() will evict entries from it, therefore abort the iteration.
                                    aborted = true;
                                    break;
                                }
                            }
                        }
                        if (aborted)
                        {
                            break;
                        }
                    }
                }
                finally
                {
                    readerManager.Release(reader);
                }

                cacheIsComplete = !aborted;
                if (cacheIsComplete)
                {
                    lock (this)
                    {
                        // everything is in the cache, so no need to keep readerManager open.
                        // this block is executed in a sync block so that it works well with
                        // initReaderManager called in parallel.
                        readerManager.Dispose();
                        readerManager            = null;
                        initializedReaderManager = false;
                    }
                }
            }
        }
Example #32
0
        public IAssetBundle Read(string filename, int filterindex)
        {
            // An sdltm file is an SQLite database.
            // Quickly check the signature will accelerate auto-detection processes.
            // (I know the following code looks silly.)
            using (var s = File.OpenRead(filename))
            {
                if (s.ReadByte() != 'S' ||
                    s.ReadByte() != 'Q' ||
                    s.ReadByte() != 'L' ||
                    s.ReadByte() != 'i' ||
                    s.ReadByte() != 't' ||
                    s.ReadByte() != 'e' ||
                    s.ReadByte() != ' ' ||
                    s.ReadByte() != 'f' ||
                    s.ReadByte() != 'o' ||
                    s.ReadByte() != 'r' ||
                    s.ReadByte() != 'm' ||
                    s.ReadByte() != 'a' ||
                    s.ReadByte() != 't' ||
                    s.ReadByte() != ' ' ||
                    s.ReadByte() != '3' ||
                    s.ReadByte() != '\0')
                {
                    return(null);
                }
            }

            IDbConnection connection = null;
            IDataReader   reader     = null;

            try
            {
                // Try to open the file.

                try
                {
                    var b = new SQLiteConnectionStringBuilder()
                    {
                        DataSource = filename
                    };
                    connection = new SQLiteConnection(b.ConnectionString);
                    connection.Open();
                }
                catch (Exception)
                {
                    return(null);
                }

                // Some sanity check.

                var version = ExecScalar(connection, @"SELECT value FROM parameters WHERE name = 'VERSION'") as string;
                if (version?.StartsWith("8.") != true)
                {
                    return(null);
                }

                var tm_min   = ExecScalarValue <int>(connection, @"SELECT min(id) FROM translation_memories");
                var tm_max   = ExecScalarValue <int>(connection, @"SELECT max(id) FROM translation_memories");
                var tm_count = tm_max - tm_min + 1;
                if (tm_count <= 0 || tm_count > 1000)
                {
                    return(null);
                }

                // Read asset metadata.
                // An asset corresponds to a memory in an sdltm file.

                var assets = new SdltmAsset[tm_count];

                reader = ExecReader(connection, @"SELECT id, name, source_language, target_language FROM translation_memories");
                while (reader.Read())
                {
                    var tmid = reader.GetInt32(0);
                    assets[tmid - tm_min] = new SdltmAsset()
                    {
                        Package    = filename,
                        Original   = reader.GetString(1),
                        SourceLang = reader.GetString(2),
                        TargetLang = reader.GetString(3),
                    };
                }
                reader.Close();
                reader.Dispose();
                reader = null;

                // Read the contents of assets (memories).

                var pool    = new StringPool();
                var matcher = new TagMatcher();

                reader = ExecReader(connection, @"SELECT translation_memory_id, id, source_segment, target_segment, creation_date, creation_user, change_date, change_user FROM translation_units");
                while (reader.Read())
                {
                    var tmid = reader.GetInt32(0);
                    var pair = new SdltmPair()
                    {
                        Id            = reader.GetInt32(1).ToString(),
                        Source        = GetInlineString(reader.GetString(2)),
                        Target        = GetInlineString(reader.GetString(3)),
                        SourceLang    = assets[tmid - tm_min].SourceLang,
                        TargetLang    = assets[tmid - tm_min].TargetLang,
                        _CreationDate = pool.Intern(reader.GetString(4)),
                        _CreationUser = pool.Intern(reader.GetString(5)),
                        _ChangeDate   = pool.Intern(reader.GetString(6)),
                        _ChangeUser   = pool.Intern(reader.GetString(7)),
                    };
                    matcher.MatchTags(pair.Source, pair.Target, reader.GetString(2), reader.GetString(3));
                    assets[tmid - tm_min]._TransPairs.Add(pair);
                }
                reader.Close();
                reader.Dispose();
                reader = null;

                // Fix the serial numbers.

                int serial = 0;
                foreach (var asset in assets)
                {
                    foreach (var pair in asset._TransPairs)
                    {
                        pair.Serial = ++serial;
                    }
                }

                // That's all.

                return(new SimpleAssetBundle(assets, ReaderManager.FriendlyFilename(filename)));
            }
            finally
            {
                reader?.Close();
                reader?.Dispose();
                connection?.Dispose();
            }
        }
 public MarketingController()
 {
     _projectUnitOfWork  = UnitOfWork <ProjectManager>();
     _readerUnitOfWork   = UnitOfWork <ReaderManager>();
     _resourceUnitOfWork = UnitOfWork <ResourceManager>();
 }
Example #34
0
 public AttenTestForm()
 {
     attenMgr  = new AttenuatorTest();
     readerMgr = new ReaderManager(this, attenMgr);
     InitializeComponent();
 }