Example #1
0
        public MovieFormViewModel(
            Movie movie,
            ReadOnlyObservableCollection <Kind> kinds,
            ReadOnlyObservableCollection <Tag> tags,
            string fileName,
            ResourceManager?resourceManager     = null,
            IScheduler?scheduler                = null,
            IEntityService <Movie>?movieService = null)
            : base(movie.Entry, tags, resourceManager, scheduler)
        {
            this.Movie = movie;
            this.Kinds = kinds;

            this.movieService = movieService ?? Locator.Current.GetService <IEntityService <Movie> >(fileName);

            this.CopyProperties();

            this.YearRule               = this.ValidationRule(vm => vm.Year, MovieMinYear, MovieMaxYear);
            this.ImdbLinkRule           = this.ValidationRule(vm => vm.ImdbLink, link => link.IsUrl(), "ImdbLinkInvalid");
            this.RottenTomatoesLinkRule = this.ValidationRule(
                vm => vm.RottenTomatoesLink, link => link.IsUrl(), "RottenTomatoesLinkInvalid");
            this.PosterUrlRule = this.ValidationRule(vm => vm.PosterUrl, url => url.IsUrl(), "PosterUrlInvalid");

            this.InitializeValueDependencies();
            this.CanDeleteWhenNotChanged();
            this.CanCreateFranchise();
            this.EnableChangeTracking();
        }
        public SpecialEpisodeFormViewModel(
            SpecialEpisode episode,
            SeriesFormViewModel parent,
            IObservable <int> maxSequenceNumber,
            ResourceManager?resourceManager,
            IScheduler?scheduler = null)
            : base(parent, maxSequenceNumber, resourceManager, scheduler)
        {
            this.SpecialEpisode = episode;
            this.CopyProperties();

            this.ChannelRule = this.ValidationRule(
                vm => vm.Channel, channel => !String.IsNullOrWhiteSpace(channel), "ChannelEmpty");

            this.YearRule = this.ValidationRule(vm => vm.Year, SeriesMinYear, SeriesMaxYear);

            this.RottenTomatoesLinkRule = this.ValidationRule(
                vm => vm.RottenTomatoesLink, link => link.IsUrl(), "RottenTomatoesLinkInvalid");

            this.PosterUrlRule = this.ValidationRule(vm => vm.PosterUrl, url => url.IsUrl(), "PosterUrlInvalid");

            this.InitializeValueDependencies();
            this.CanAlwaysDelete();
            this.EnableChangeTracking();
        }
Example #3
0
        protected TitledFormBase(ResourceManager?resourceManager, IScheduler?scheduler = null)
            : base(resourceManager, scheduler)
        {
            this.InitializeTitles(title => !title.IsOriginal, out this.titles);
            this.InitializeTitles(title => title.IsOriginal, out this.originalTitles);

            this.FormTitle = this.Titles.ToObservableChangeSet()
                             .AutoRefresh(vm => vm.Name)
                             .AutoRefresh(vm => vm.Priority)
                             .ToCollection()
                             .Select(vms => vms.OrderBy(vm => vm.Priority).Select(vm => vm.Name).FirstOrDefault())
                             .Select(this.GetFormTitle)
                             .ObserveOn(RxApp.MainThreadScheduler);

            var canAddTitle = this.Titles.ToObservableChangeSet()
                              .Count()
                              .Select(count => count < MaxTitleCount);

            var canAddOriginalTitle = this.OriginalTitles.ToObservableChangeSet()
                                      .Count()
                                      .Select(count => count < MaxTitleCount);

            this.Close = ReactiveCommand.Create(() => { });

            this.AddTitle         = ReactiveCommand.Create(() => this.OnAddTitle(false), canAddTitle);
            this.AddOriginalTitle = ReactiveCommand.Create(() => this.OnAddTitle(true), canAddOriginalTitle);
        }
Example #4
0
        protected SeriesComponentFormBase(
            SeriesFormViewModel parent,
            IObservable <int> maxSequenceNumber,
            ResourceManager?resourceManager,
            IScheduler?scheduler = null)
            : base(resourceManager, scheduler)
        {
            this.Parent = parent;

            this.GoToSeries = ReactiveCommand.Create <Unit, SeriesFormViewModel>(_ => this.Parent, this.Valid);

            var isNotFirst = this.WhenAnyValue(vm => vm.SequenceNumber)
                             .Select(num => num != 1);

            var isNotLast = Observable.CombineLatest(this.WhenAnyValue(vm => vm.SequenceNumber), maxSequenceNumber)
                            .Select(nums => nums[0] < nums[1]);

            this.MoveUp   = ReactiveCommand.Create(() => { this.SequenceNumber--; }, isNotFirst);
            this.MoveDown = ReactiveCommand.Create(() => { this.SequenceNumber++; }, isNotLast);

            this.GoToNext = ReactiveCommand.Create(
                () => { },
                Observable.CombineLatest(isNotLast, this.Valid).AllTrue());

            this.GoToPrevious = ReactiveCommand.Create(
                () => { },
                Observable.CombineLatest(isNotFirst, this.Valid).AllTrue());
        }
        public MiniseriesFormViewModel(
            Series series,
            ReadOnlyObservableCollection <Kind> kinds,
            ReadOnlyObservableCollection <Tag> tags,
            string fileName,
            ResourceManager?resourceManager       = null,
            IScheduler?scheduler                  = null,
            IEntityService <Series>?seriesService = null,
            ISettingsService?settingsService      = null)
            : base(series.Entry, tags, resourceManager, scheduler)
        {
            this.Series = series;
            this.Kinds  = kinds;

            this.seriesService   = seriesService ?? Locator.Current.GetService <IEntityService <Series> >(fileName);
            this.settingsService = settingsService ?? Locator.Current.GetService <ISettingsService>(fileName);

            this.CopyProperties();

            this.ChannelRule = this.ValidationRule(
                vm => vm.Channel, channel => !String.IsNullOrWhiteSpace(channel), "ChannelEmpty");

            this.ImdbLinkRule           = this.ValidationRule(vm => vm.ImdbLink, link => link.IsUrl(), "ImdbLinkInvalid");
            this.RottenTomatoesLinkRule = this.ValidationRule(
                vm => vm.RottenTomatoesLink, link => link.IsUrl(), "RottenTomatoesLinkInvalid");
            this.PosterUrlRule = this.ValidationRule(vm => vm.PosterUrl, url => url.IsUrl(), "PosterUrlInvalid");

            this.ConvertToSeries = ReactiveCommand.Create(() => { });

            this.CanDeleteWhenNotChanged();
            this.CanCreateFranchise();
            this.EnableChangeTracking();
        }
Example #6
0
 public bool TryFind(Func <ResourceManager, bool> predicate, [NotNullWhen(true)] out ResourceManager?resourceManager)
 {
     lock (_lock)
     {
         resourceManager = _resourceManagers.FirstOrDefault(predicate);
         return(resourceManager != null);
     }
 }
Example #7
0
        public void Setup()
        {
            resourceManager     = new MockResourceManager();
            initialCulture      = CultureInfo.InvariantCulture;
            localizationManager = LocalizationResourceManager.Current;

            localizationManager.Init(resourceManager, initialCulture);
        }
        internal GnuFilter(CommandLine?commandLine)
        {
            _resourceManager = commandLine?.ResourceManager;

            AddMatch(nameof(Version), v => Version = v);
            AddMatch('h', nameof(Help), v => Help  = v);
            SetResult(() => this);
        }
Example #9
0
        public MovieSeriesFormViewModel(
            MovieSeries movieSeries,
            string fileName,
            ResourceManager?resourceManager = null,
            IScheduler?scheduler            = null,
            IEntityService <MovieSeries>?movieSeriesService = null)
            : base(movieSeries.Entry, resourceManager, scheduler)
        {
            this.MovieSeries = movieSeries;

            this.movieSeriesService = movieSeriesService ??
                                      Locator.Current.GetService <IEntityService <MovieSeries> >(fileName);

            this.entriesSource.Connect()
            .Transform(this.CreateEntryViewModel)
            .AutoRefresh(vm => vm.SequenceNumber)
            .Sort(SortExpressionComparer <MovieSeriesEntryViewModel> .Ascending(vm => vm.SequenceNumber))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind(out this.entries)
            .Subscribe();

            this.FormTitle =
                this.FormTitle
                .Select(this.GetFullFormTitle)
                .StartWith(this.GetFullFormTitle(
                               this.GetFormTitle(this.MovieSeries.ActualTitles.FirstOrDefault()?.Name ?? String.Empty)));

            this.PosterUrlRule = this.ValidationRule(vm => vm.PosterUrl, url => url.IsUrl(), "PosterUrlInvalid");

            this.entriesSource.Connect()
            .Count()
            .Select(count => count > 0)
            .ToPropertyEx(this, vm => vm.CanShowTitles);

            var canSelectEntry = this.FormChanged.Invert();

            this.SelectEntry = ReactiveCommand.Create <MovieSeriesEntryViewModel, MovieSeriesEntry>(
                vm => vm.Entry, canSelectEntry);

            this.DetachEntry = ReactiveCommand.Create <MovieSeriesEntry, MovieSeriesEntry>(this.OnDetachEntry);

            var canAddEntry = Observable.CombineLatest(
                Observable.Return(!this.IsNew).Merge(this.Save.Select(_ => true)),
                this.FormChanged.Invert())
                              .AllTrue();

            this.AddMovie       = ReactiveCommand.Create(this.GetFirstDisplayNumber, canAddEntry);
            this.AddSeries      = ReactiveCommand.Create(this.GetFirstDisplayNumber, canAddEntry);
            this.AddMovieSeries = ReactiveCommand.Create(this.GetFirstDisplayNumber, canAddEntry);

            this.InitializeValueDependencies();
            this.CopyProperties();
            this.CanDeleteWhenNotChanged();
            this.CanCreateMovieSeries();
            this.EnableChangeTracking();
        }
Example #10
0
 public GenericKindManager(
     IResourceDocumentStore <SchemaDrivenKind.DynamicResource> documentStore,
     Kind <SchemaDrivenKind.DynamicResource> kind,
     ResourceManager?parentKindManager,
     ResourceManagerContainer resourceManagers) :
     base(documentStore, resourceManagers)
 {
     _parentKindManager = parentKindManager;
     TypedKind          = kind;
 }
Example #11
0
        private bool TryGetKindManager(ResourceDocument partialResourceDocument, [NotNullWhen(true)] out ResourceManager?kindManager)
        {
            if (partialResourceDocument.Kind == null)
            {
                kindManager = default;
                return(false);
            }

            return(_resourceManagers.TryFind(q => q.Kind.GetKindDescriptor().Equals(partialResourceDocument.Kind.Value), out kindManager));
        }
Example #12
0
#pragma warning restore SA1401 // Fields should be private

                internal ResourceManagerClone(ResourceManager source)
                {
                    Debug.Assert(source != null, "resourceManager == null");
                    var containingType = source.ContainingType();

                    Debug.Assert(containingType != null, "containingType == null");

                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse want this check in release build
                    if (containingType != null)
                    {
                        this.ResourceManager = new ResourceManager(source.BaseName, containingType.Assembly);
                    }
                }
Example #13
0
        public bool Equals(ResourceManager?x, ResourceManager?y)
        {
            if (x is null && y is null)
            {
                return(true);
            }

            if (x is null || y is null)
            {
                return(false);
            }

            return(StringComparer.Equals(x.BaseName, y.BaseName));
        }
Example #14
0
            internal static NameDescription?FromVerbType(Type verbType,
                                                         ResourceManager?_resourceManager)
            {
                if (verbType.IsDefined(typeof(VerbAttribute)))
                {
                    var attribute = verbType.GetCustomAttribute <VerbAttribute>() !;

                    var name        = attribute.VerbName;
                    var description = GetLocalizedDescription(attribute, _resourceManager);

                    return(new NameDescription(name, description));
                }
                else
                {
                    return(default);
Example #15
0
        public PreferencesFormViewModel(
            UserPreferences userPreferences,
            IBlobCache?store = null,
            ResourceManager?resourceManager = null,
            IScheduler?scheduler            = null)
            : base(userPreferences, resourceManager, scheduler)
        {
            this.store = store ?? Locator.Current.GetService <IBlobCache>(StoreKey);

            this.Header = new TabHeaderViewModel(
                String.Empty, this.ResourceManager.GetString("Preferences") ?? String.Empty);

            this.CopyProperties();
            this.CanNeverDelete();
            this.EnableChangeTracking();
        }
Example #16
0
        protected FormBase(ResourceManager?resourceManager = null, IScheduler?scheduler = null)
        {
            this.ResourceManager = resourceManager ?? Locator.Current.GetService <ResourceManager>();
            this.Scheduler       = scheduler ?? System.Reactive.Concurrency.Scheduler.Default;

            this.Valid = Observable.CombineLatest(this.validSubject, this.IsValid()).AllTrue();

            var canSave = Observable.CombineLatest(
                Observable.CombineLatest(this.formChangedSubject, this.canSaveSubject).AnyTrue(),
                this.Valid)
                          .AllTrue();

            this.Save   = ReactiveCommand.CreateFromTask(this.OnSaveAsync, canSave);
            this.Cancel = ReactiveCommand.Create(this.CopyProperties, this.formChangedSubject);
            this.Delete = ReactiveCommand.CreateFromTask(this.OnDeleteAsync, this.canDeleteSubject);
        }
Example #17
0
        public MovieSeriesEntryViewModel(
            MovieSeriesEntry entry,
            MovieSeriesFormViewModel parentForm,
            ResourceManager?resourceManager = null,
            IScheduler?scheduler            = null)
            : base(resourceManager, scheduler)
        {
            this.Log().Debug($"Creating a view model for an entry inside the movie series form: {entry}");

            this.Entry      = entry;
            this.ParentForm = parentForm;

            this.Select = ReactiveCommand.Create(() => { });

            var canMoveUp = this.WhenAnyValue(vm => vm.SequenceNumber)
                            .Select(num => num != 1);

            var canMoveDown = this.WhenAnyValue(vm => vm.SequenceNumber)
                              .Select(num => num < this.Entry.ParentSeries.Entries.Count);

            this.MoveUp   = ReactiveCommand.Create(() => { }, canMoveUp);
            this.MoveDown = ReactiveCommand.Create(() => { }, canMoveDown);

            var canHideDisplayNumber = this.WhenAnyValue(vm => vm.ParentForm.IsLooselyConnected)
                                       .Invert()
                                       .CombineLatest(this.WhenAnyValue(vm => vm.DisplayNumber).Select(num => num != null), (a, b) => a && b);

            var canShowDisplayNumber = this.WhenAnyValue(vm => vm.ParentForm.IsLooselyConnected)
                                       .Invert()
                                       .CombineLatest(this.WhenAnyValue(vm => vm.DisplayNumber).Select(num => num == null), (a, b) => a && b);

            this.HideDisplayNumber = ReactiveCommand.Create(() => { }, canHideDisplayNumber);
            this.ShowDisplayNumber = ReactiveCommand.Create(() => { }, canShowDisplayNumber);

            this.WhenAnyValue(
                vm => vm.DisplayNumber,
                vm => vm.ParentForm.IsLooselyConnected,
                (num, isLooselyConnected) => (Number: num, IsLooselyConnected: isLooselyConnected))
            .Select(props => props.Number.AsDisplayNumber(props.IsLooselyConnected))
            .ToPropertyEx(this, vm => vm.NumberToDisplay);

            this.CopyProperties();

            this.CanDeleteWhen(this.ParentForm.Entries.ToObservableChangeSet().Count().Select(count => count > 1));

            this.EnableChangeTracking();
        }
Example #18
0
        public PeriodFormViewModel(
            Period period,
            IObservable <bool> canDelete,
            ResourceManager?resourceManager,
            IScheduler?scheduler = null)
            : base(resourceManager, scheduler)
        {
            this.Period = period;
            this.CopyProperties();

            this.StartYearRule = this.ValidationRule(vm => vm.StartYear, SeriesMinYear, SeriesMaxYear, YearProperty);
            this.EndYearRule   = this.ValidationRule(vm => vm.EndYear, SeriesMinYear, SeriesMaxYear, YearProperty);

            this.NumberOfEpisodesRule = this.ValidationRule(
                vm => vm.NumberOfEpisodes,
                PeriodMinNumberOfEpisodes,
                PeriodMaxNumberOfEpisodes);

            this.RottenTomatoesLinkRule = this.ValidationRule(
                vm => vm.RottenTomatoesLink, link => link.IsUrl(), "RottenTomatoesLinkInvalid");

            this.PosterUrlRule = this.ValidationRule(vm => vm.PosterUrl, url => url.IsUrl(), "PosterUrlInvalid");

            var periodValid =
                this.WhenAnyValue(
                    vm => vm.StartMonth,
                    vm => vm.StartYear,
                    vm => vm.EndMonth,
                    vm => vm.EndYear,
                    (int startMonth, int startYear, int endMonth, int endYear) =>
                    startYear < endYear || startYear == endYear && startMonth <= endMonth)
                .Throttle(TimeSpan.FromMilliseconds(250), this.Scheduler)
                .ObserveOn(RxApp.MainThreadScheduler);

            this.PeriodRule = this.ValidationRule(
                periodValid,
                this.ResourceManager.GetString("ValidationPeriodInvalid") ?? String.Empty);

            this.CanDeleteWhen(canDelete);

            this.InitializeValueDependencies();

            this.EnableChangeTracking();
        }
Example #19
0
        protected MovieSeriesEntryFormBase(
            MovieSeriesEntry?entry,
            ResourceManager?resourceManager,
            IScheduler?scheduler = null)
            : base(resourceManager, scheduler)
        {
            this.MovieSeriesEntry = entry;

            var formNotChanged = this.FormChanged.Invert();

            int lastSequenceNumber = this.MovieSeriesEntry?.ParentSeries
                                     .Entries
                                     .Select(e => (int?)e.SequenceNumber)
                                     .Max()
                                     ?? 0;

            var canGoToMovieSeries = this.IfMovieSeriesPresent(() => formNotChanged);

            this.GoToMovieSeries = ReactiveCommand.Create <Unit, MovieSeries>(
                _ => this.MovieSeriesEntry !.ParentSeries, canGoToMovieSeries);

            var canGoToNext = this.IfMovieSeriesPresent(() =>
                                                        this.MovieSeriesEntry !.SequenceNumber >= lastSequenceNumber
                    ? Observable.Return(false)
                    : formNotChanged);

            this.GoToNext = ReactiveCommand.Create <Unit, MovieSeriesEntry>(
                _ => this.MovieSeriesEntry !.ParentSeries.Entries
                .First(e => e.SequenceNumber > this.MovieSeriesEntry !.SequenceNumber),
                canGoToNext);

            var canGoToPrevious = this.IfMovieSeriesPresent(() =>
                                                            this.MovieSeriesEntry !.SequenceNumber == 1
                    ? Observable.Return(false)
                    : formNotChanged);

            this.GoToPrevious = ReactiveCommand.Create <Unit, MovieSeriesEntry>(
                _ => this.MovieSeriesEntry !.ParentSeries.Entries
                .Last(e => e.SequenceNumber < this.MovieSeriesEntry !.SequenceNumber),
                canGoToPrevious);

            this.CreateMovieSeries = ReactiveCommand.Create(() => { }, this.canCreateMovieSeriesSubject);
        }
Example #20
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(false);

            var loaderMessages = await Task.Run(FillCatalog, cancellationToken).ConfigureAwait(false);

            _performanceTracer = ExportProvider.GetExportedValue <PerformanceTracer>();

            var menuCommandService = await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(false);

            await JoinableTaskFactory.SwitchToMainThreadAsync();

            SynchronizationContextThrottle.TaskFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());

            ShowLoaderMessages(loaderMessages);

            ErrorProvider.Register(ExportProvider);

            ConnectEvents();

            // start background services
            ExportProvider
            .GetExportedValues <IService>()
            .ForEach(service => service.Start());

            _resourceManager = ExportProvider.GetExportedValue <ResourceManager>();
            _resourceManager.ProjectFileSaved += ResourceManager_ProjectFileSaved;

            // Add our command handlers for menu (commands must exist in the .vsct file)
            if (!(menuCommandService is IMenuCommandService mcs))
            {
                return;
            }

            // Create the command for the menu item.
            CreateMenuCommand(mcs, PkgCmdIdList.cmdidMyCommand, ShowToolWindow);
            // Create the command for the tool window
            CreateMenuCommand(mcs, PkgCmdIdList.cmdidMyTool, ShowToolWindow);
            // Create the command for the solution explorer context menu
            CreateMenuCommand(mcs, PkgCmdIdList.cmdidMySolutionExplorerContextMenu, ShowSelectedResourceFiles).BeforeQueryStatus += SolutionExplorerContextMenuCommand_BeforeQueryStatus;
            // Create the command for the text editor context menu
            CreateMenuCommand(mcs, PkgCmdIdList.cmdidMyTextEditorContextMenu, MoveToResource).BeforeQueryStatus += TextEditorContextMenuCommand_BeforeQueryStatus;
        }
Example #21
0
        public PeriodFormViewModel(
            Period period,
            IObservable <bool> canDelete,
            ResourceManager?resourceManager,
            IScheduler?scheduler = null)
            : base(resourceManager, scheduler)
        {
            this.Period = period;
            this.CopyProperties();

            this.StartYearRule = this.ValidationRule(vm => vm.StartYear, SeriesMinYear, SeriesMaxYear, "Year");
            this.EndYearRule   = this.ValidationRule(vm => vm.EndYear, SeriesMinYear, SeriesMaxYear, "Year");

            this.NumberOfEpisodesRule = this.ValidationRule(
                vm => vm.NumberOfEpisodes,
                PeriodMinNumberOfEpisodes,
                PeriodMaxNumberOfEpisodes,
                nameof(this.NumberOfEpisodes));

            this.PosterUrlRule = this.ValidationRule(vm => vm.PosterUrl, url => url.IsUrl(), "PosterUrlInvalid");

            var periodValid = this.WhenAnyValue(
                vm => vm.StartMonth,
                vm => vm.StartYear,
                vm => vm.EndMonth,
                vm => vm.EndYear)
                              .Throttle(TimeSpan.FromMilliseconds(250), this.Scheduler)
                              .Select(((int StartMonth, string StartYear, int EndMonth, string EndYear)values) =>
                                      Int32.TryParse(values.StartYear, out int startYear) &&
                                      Int32.TryParse(values.EndYear, out int endYear) &&
                                      (startYear < endYear || startYear == endYear && values.StartMonth <= values.EndMonth))
                              .ObserveOn(RxApp.MainThreadScheduler);

            this.PeriodRule = this.ValidationRule(
                _ => periodValid.StartWith(true),
                (vm, isValid) => isValid ? String.Empty : vm.ResourceManager.GetString("ValidationPeriodInvalid"));

            this.CanDeleteWhen(canDelete);

            this.InitializeValueDependencies();

            this.EnableChangeTracking();
        }
Example #22
0
    public TitleFormViewModel(
        Title title,
        IObservable <bool> canDelete,
        ResourceManager?resourceManager = null,
        IScheduler?scheduler            = null)
        : base(resourceManager, scheduler)
    {
        this.Title = title;
        this.CopyProperties();

        this.ValidationRule(vm => vm.Name, name => !String.IsNullOrWhiteSpace(name), "TitleNameEmpty");

        this.CanDeleteWhen(canDelete);

        var canMoveUp = this.WhenAnyValue(vm => vm.Priority)
                        .Select(priority => priority >= MinTitleCount);

        this.MoveUp = ReactiveCommand.Create(() => { this.Priority--; }, canMoveUp);

        this.EnableChangeTracking();
    }
    public SettingsFormViewModel(
        string fileName,
        Settings settings,
        IEnumerable <Kind> kinds,
        IEnumerable <Tag> tags,
        ISettingsService?settingsService          = null,
        ISettingsEntityService <Kind>?kindService = null,
        ISettingsEntityService <Tag>?tagService   = null,
        ResourceManager?resourceManager           = null,
        IScheduler?scheduler = null)
        : base(new SettingsModel(settings, kinds.ToList(), tags.ToList()), resourceManager, scheduler)
    {
        this.settingsService = settingsService ?? GetDefaultService <ISettingsService>(fileName);
        this.kindService     = kindService ?? GetDefaultService <ISettingsEntityService <Kind> >(fileName);
        this.tagService      = tagService ?? GetDefaultService <ISettingsEntityService <Tag> >(fileName);

        this.ValidationRule(vm => vm.ListName, name => !String.IsNullOrWhiteSpace(name), "ListNameEmpty");

        this.CopyProperties();
        this.CanNeverDelete();
        this.EnableChangeTracking();
    }
    public PreferencesFormViewModel(
        UserPreferences userPreferences,
        IBlobCache?store                = null,
        ThemeManager?themeManager       = null,
        ResourceManager?resourceManager = null,
        IScheduler?scheduler            = null)
        : base(userPreferences, resourceManager, scheduler)
    {
        this.store = store ?? GetDefaultService <IBlobCache>(StoreKey);
        themeManager ??= GetDefaultService <ThemeManager>();

        this.Header = new TabHeaderViewModel(
            String.Empty, this.ResourceManager.GetString("Preferences") ?? String.Empty);

        this.CopyProperties();

        this.WhenAnyValue(vm => vm.Theme)
        .ObserveOn(RxApp.MainThreadScheduler)
        .BindTo(themeManager, tm => tm.Theme);

        this.CanNeverDelete();
        this.EnableChangeTracking();
    }
 public void Init(ResourceManager resource) => resourceManager = resource;
Example #26
0
        private static string?InternalGetResourceString(string?key)
        {
            if (key == null || key.Length == 0)
            {
                Debug.Fail("SR::GetResourceString with null or empty key.  Bug in caller, or weird recursive loading problem?");
                return(key !);
            }

            // We have a somewhat common potential for infinite
            // loops with mscorlib's ResourceManager.  If "potentially dangerous"
            // code throws an exception, we will get into an infinite loop
            // inside the ResourceManager and this "potentially dangerous" code.
            // Potentially dangerous code includes the IO package, CultureInfo,
            // parts of the loader, some parts of Reflection, Security (including
            // custom user-written permissions that may parse an XML file at
            // class load time), assembly load event handlers, etc.  Essentially,
            // this is not a bounded set of code, and we need to fix the problem.
            // Fortunately, this is limited to mscorlib's error lookups and is NOT
            // a general problem for all user code using the ResourceManager.

            // The solution is to make sure only one thread at a time can call
            // GetResourceString.  Also, since resource lookups can be
            // reentrant, if the same thread comes into GetResourceString
            // twice looking for the exact same resource name before
            // returning, we're going into an infinite loop and we should
            // return a bogus string.

            bool lockTaken = false;

            try
            {
                Monitor.Enter(_lock, ref lockTaken);

                // Are we recursively looking up the same resource?  Note - our backout code will set
                // the ResourceHelper's currentlyLoading stack to null if an exception occurs.
                if (_currentlyLoading != null && _currentlyLoading.Count > 0 && _currentlyLoading.LastIndexOf(key) != -1)
                {
                    // We can start infinitely recursing for one resource lookup,
                    // then during our failure reporting, start infinitely recursing again.
                    // avoid that.
                    if (_infinitelyRecursingCount > 0)
                    {
                        return(key);
                    }
                    _infinitelyRecursingCount++;

                    // Note: our infrastructure for reporting this exception will again cause resource lookup.
                    // This is the most direct way of dealing with that problem.
                    string message = $"Infinite recursion during resource lookup within {System.CoreLib.Name}.  This may be a bug in {System.CoreLib.Name}, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names.  Resource name: {key}";
                    Environment.FailFast(message);
                }
                if (_currentlyLoading == null)
                {
                    _currentlyLoading = new List <string>();
                }

                // Call class constructors preemptively, so that we cannot get into an infinite
                // loop constructing a TypeInitializationException.  If this were omitted,
                // we could get the Infinite recursion assert above by failing type initialization
                // between the Push and Pop calls below.
                if (!_resourceManagerInited)
                {
                    RuntimeHelpers.RunClassConstructor(typeof(ResourceManager).TypeHandle);
                    RuntimeHelpers.RunClassConstructor(typeof(ResourceReader).TypeHandle);
                    RuntimeHelpers.RunClassConstructor(typeof(RuntimeResourceSet).TypeHandle);
                    RuntimeHelpers.RunClassConstructor(typeof(BinaryReader).TypeHandle);
                    _resourceManagerInited = true;
                }

                _currentlyLoading.Add(key); // Push

                if (ResourceManager == null)
                {
                    ResourceManager = new ResourceManager(SR.ResourceType);
                }
                string?s = ResourceManager.GetString(key, null);
                _currentlyLoading.RemoveAt(_currentlyLoading.Count - 1); // Pop

                Debug.Assert(s != null, "Managed resource string lookup failed.  Was your resource name misspelled?  Did you rebuild mscorlib after adding a resource to resources.txt?  Debug this w/ cordbg and bug whoever owns the code that called SR.GetResourceString.  Resource name was: \"" + key + "\"");
                return(s ?? key);
            }
            catch
            {
                if (lockTaken)
                {
                    // Backout code - throw away potentially corrupt state
                    ResourceManager   = null;
                    _currentlyLoading = null;
                }
                throw;
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(_lock);
                }
            }
        }
Example #27
0
        public SeriesFormViewModel(
            Series series,
            ReadOnlyObservableCollection <Kind> kinds,
            string fileName,
            ResourceManager?resourceManager       = null,
            IScheduler?scheduler                  = null,
            IEntityService <Series>?seriesService = null,
            ISettingsService?settingsService      = null)
            : base(series.Entry, resourceManager, scheduler)
        {
            this.Series = series;
            this.Kinds  = kinds;

            this.seriesService   = seriesService ?? Locator.Current.GetService <IEntityService <Series> >(fileName);
            this.settingsService = settingsService ?? Locator.Current.GetService <ISettingsService>(fileName);

            this.SelectComponent = ReactiveCommand.Create <ISeriesComponentForm, ISeriesComponentForm>(
                form => form);

            this.componentsSource.Connect()
            .Transform(this.CreateForm)
            .Sort(
                SortExpressionComparer <ISeriesComponentForm> .Ascending(form => form.SequenceNumber),
                resort: this.resort)
            .Bind(out this.componentForms)
            .DisposeMany()
            .Subscribe();

            this.ComponentForms.ToObservableChangeSet()
            .Transform(this.CreateComponent)
            .Bind(out this.components)
            .DisposeMany()
            .Subscribe();

            this.ComponentForms.ToObservableChangeSet()
            .Filter(form => form is SeasonFormViewModel)
            .Transform(form => (SeasonFormViewModel)form)
            .Bind(out this.seasons)
            .DisposeMany()
            .Subscribe();

            this.ComponentForms.ToObservableChangeSet()
            .Filter(form => form is SpecialEpisodeFormViewModel)
            .Transform(form => (SpecialEpisodeFormViewModel)form)
            .Bind(out this.specialEpisodes)
            .DisposeMany()
            .Subscribe();

            this.Components.ToObservableChangeSet()
            .AutoRefresh(component => component.SequenceNumber)
            .ToCollection()
            .Select(components => components.Count != 0 ? components.Max(c => c.SequenceNumber) : 0)
            .Subscribe(this.maxSequenceNumberSubject);

            this.CopyProperties();

            this.ImdbLinkRule  = this.ValidationRule(vm => vm.ImdbLink, link => link.IsUrl(), "ImdbLinkInvalid");
            this.PosterUrlRule = this.ValidationRule(vm => vm.PosterUrl, url => url.IsUrl(), "PosterUrlInvalid");

            this.AddSeason           = ReactiveCommand.CreateFromTask(this.AddSeasonAsync);
            this.AddSpecialEpisode   = ReactiveCommand.Create(this.OnAddSpecialEpisode);
            this.ConvertToMiniseries = ReactiveCommand.Create(() => { }, this.CanConvertToMiniseries);

            this.AddSeason
            .Merge(this.AddSpecialEpisode)
            .SelectMany(_ => this.ComponentForms.MaxBy(season => season.SequenceNumber))
            .Cast <ISeriesComponentForm>()
            .InvokeCommand(this.SelectComponent);

            this.CanDeleteWhenNotChanged();
            this.CanCreateMovieSeries();
            this.EnableChangeTracking();
        }
 private static string GetLocalizedDescription(CommandLineAttribute attribute, ResourceManager?resourceManager)
 => resourceManager != null && !string.IsNullOrWhiteSpace(attribute.LocalizableDescription)
         ? resourceManager.GetString(attribute.LocalizableDescription, CultureInfo.CurrentUICulture) ?? ""
         : attribute.Description ?? "";
 /// <summary>Tries to get from cache or create a <see cref="ResourceManager"/> for <paramref name="resourcesType"/>. </summary>
 /// <param name="resourcesType">Ex. typeof(Properties.Resources).</param>
 /// <param name="result">The <see cref="ResourceManager"/>.</param>
 /// <returns>True if a <see cref="ResourceManager"/> could be created for <paramref name="resourcesType"/>.</returns>
 internal static bool TryGetForType(Type resourcesType, [NotNullWhen(true)] out ResourceManager?result)
 {
     result = TypeManagerCache.GetOrAdd(resourcesType, x => CreateManagerForTypeOrDefault(x));
     return(result != null);
 }
Example #30
0
 private CommandLine(ListGroup <SingleOptimizedStrings> optionArgs, ResourceManager?resourceManager)
 {
     _optionArgs     = optionArgs ?? throw new ArgumentNullException(nameof(optionArgs));
     ResourceManager = resourceManager;
 }