private bool ShowDialog(IViewAware owner, DsopScopeInitInfo scope, string targetServer, out List <SecurityIdentifier> sids)
        {
            sids = null;

            var results = NativeMethods.ShowObjectPickerDialog(owner.GetHandle(), targetServer, DsopDialogInitializationOptions.DSOP_FLAG_MULTISELECT, scope, "objectClass", "objectSid");

            if (results == null)
            {
                return(false);
            }

            sids = new List <SecurityIdentifier>();

            foreach (var result in results)
            {
                byte[] sidraw = result?.Attributes["objectSid"] as byte[];

                if (sidraw != null)
                {
                    sids.Add(new SecurityIdentifier(sidraw, 0));
                }
            }

            return(true);
        }
Пример #2
0
            public void ShowWindow(IViewAware rootModel, IViewAware owningModel)
            {
                Window win = CreateWindow(rootModel, isDialog: false, context: null, settings: null);

                win.Owner = (Window)owningModel.GetView();
                win.Show();
            }
Пример #3
0
        public static IntPtr GetHandle(this IViewAware view)
        {
            Window window = Window.GetWindow(view.View);
            var    wih    = new WindowInteropHelper(window);

            return(wih.Handle);
        }
Пример #4
0
    public static void AssignViewToViewModel(ILogger logger, UIElement view, IViewAware viewAware)
    {
        logger.Information("ViewModel {ViewModelType} is IViewAware so calling LoadView() with the View {ViewType}",
                           viewAware.GetType().FullName,
                           view.GetType().FullName);

        viewAware.LoadView(view);
    }
        /// <summary>
        /// WhenLoaded allows you to register a Func to be called when a ViewModel's View is Loaded.
        /// </summary>
        /// <param name="item">Object that is view aware.</param>
        /// <param name="block">
        /// The method to be called when the corresponding View is loaded.
        /// It returns a list of Disposables that will be cleaned up when the View is unloaded.
        /// </param>
        public static void WhenLoaded(this IViewAware item, Func <IEnumerable <IDisposable> > block)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            item.View.AddOnLoadedBlock(block);
        }
Пример #6
0
            public Point?GetElementPosition(IViewAware element, IViewAware relativeTo)
            {
                if (element.GetView() == null)
                {
                    return(null);
                }

                return(((UIElement)element.GetView()).TranslatePoint(new Point(), (UIElement)relativeTo.GetView()));
            }
Пример #7
0
            void HandleViewAware(ILaunchChooser <TResult> handler, IViewAware viewAware, object storedClientId)
            {
                EventHandler <ViewAttachedEventArgs> onViewAttached = null;

                onViewAttached = (s, e) => {
                    HandleView(e.View, storedClientId, handler);
                    viewAware.ViewAttached -= onViewAttached;
                };
                viewAware.ViewAttached += onViewAttached;
            }
Пример #8
0
        public Task AddLivestream(ChannelIdentifier channelIdentifier, IViewAware viewAware)
        {
            if (channelIdentifier == null)
            {
                throw new ArgumentNullException(nameof(channelIdentifier));
            }
            Livestreams.Add(new LivestreamModel(channelIdentifier.ChannelId, channelIdentifier));

            return(Task.CompletedTask);
        }
Пример #9
0
            public IObservable <Unit> ViewLoaded(IViewAware element)
            {
                IObservable <Unit> getView = element.GetView() != null?Observable.Return(Unit.Default) :
                                                 Observable.FromEventPattern(element, "ViewAttached").Select(_ => Unit.Default).Take(1);

                return
                    (from gotView in getView
                     from loaded in Observable.FromEventPattern(element.GetView(), "Loaded").Take(1).Concat(Observable.FromEventPattern(element.GetView(), "SizeChanged"))
                     select Unit.Default);
            }
Пример #10
0
        public async Task OpenVod(VodDetails vodDetails, IViewAware viewAware)
        {
            if (string.IsNullOrWhiteSpace(vodDetails.Url) ||
                !Uri.IsWellFormedUriString(vodDetails.Url, UriKind.Absolute))
            {
                return;
            }

            var favoriteQualities = settingsHandler.Settings.GetStreamQualities(vodDetails.ApiClient.ApiName);
            var qualities         = favoriteQualities.Qualities.Union(new[] { favoriteQualities.FallbackQuality });

            string livestreamerArgs = $"--player-passthrough hls {vodDetails.Url} {string.Join(",", qualities)}";

            // hack to pass through the client id to livestreamer
            if (settingsHandler.Settings.PassthroughClientId)
            {
                // check domain name of url to see if this is a twitch.tv vod link
                bool isTwitchStream = false;
                try
                {
                    var uri = new Uri(vodDetails.Url);
                    isTwitchStream = uri.Host.Contains("twitch.tv");
                }
                catch { }

                if (isTwitchStream)
                {
                    livestreamerArgs += $" --http-header {RequestConstants.ClientIdHeaderKey}={RequestConstants.ClientIdHeaderValue}";
                }
            }
            else
            {
                var apiClient = vodDetails.ApiClient;
                if (!apiClient.IsAuthorized)
                {
                    await apiClient.Authorize(viewAware);
                }

                if (apiClient.IsAuthorized && !string.IsNullOrWhiteSpace(apiClient.LivestreamerAuthorizationArg))
                {
                    livestreamerArgs += " " + apiClient.LivestreamerAuthorizationArg;
                }
            }

            const int maxTitleLength = 70;
            var       title          = vodDetails.Title?.Length > maxTitleLength?vodDetails.Title.Substring(0, maxTitleLength) + "..." : vodDetails.Title;

            var launcher = Path.GetFileName(settingsHandler.Settings.LivestreamerFullPath);

            var messageBoxViewModel = ShowLivestreamerLoadMessageBox(
                title: title,
                messageText: $"Launching {settingsHandler.Settings.LivestreamExeDisplayName}....{Environment.NewLine}'{launcher} {livestreamerArgs}'");

            StartLivestreamer(livestreamerArgs, messageBoxViewModel);
        }
        public bool GetUsers(IViewAware owner, out List <SecurityIdentifier> sid)
        {
            sid = null;

            if (this.PromptForTargetForest(owner, out string targetServer))
            {
                return(this.GetUsers(owner, targetServer, out sid));
            }

            return(false);
        }
Пример #12
0
        public async Task OpenStream(LivestreamModel livestreamModel, IViewAware viewAware)
        {
            if (livestreamModel?.ApiClient == null || !livestreamModel.Live)
            {
                return;
            }

            var favoriteQualities = settingsHandler.Settings.GetStreamQualities(livestreamModel.ApiClient.ApiName);
            var qualities         = favoriteQualities.Qualities.Union(new[] { favoriteQualities.FallbackQuality });

            var    streamUrl        = await livestreamModel.GetStreamUrl;
            string livestreamerArgs = $"{streamUrl} {string.Join(",", qualities)}";
            var    apiClient        = livestreamModel.ApiClient;

            // hack to pass through the client id to livestreamer
            if (settingsHandler.Settings.PassthroughClientId)
            {
                if (apiClient is TwitchApiClient)
                {
                    livestreamerArgs = $"--http-header {RequestConstants.ClientIdHeaderKey}={RequestConstants.ClientIdHeaderValue} {livestreamerArgs}";
                }
            }
            else
            {
                if (!apiClient.IsAuthorized)
                {
                    await apiClient.Authorize(viewAware);
                }

                if (apiClient.IsAuthorized && !string.IsNullOrWhiteSpace(apiClient.LivestreamerAuthorizationArg))
                {
                    livestreamerArgs += " " + apiClient.LivestreamerAuthorizationArg;
                }
            }

            var launcher = Path.GetFileName(settingsHandler.Settings.LivestreamerFullPath);

            var messageBoxViewModel = ShowLivestreamerLoadMessageBox(
                title: $"Stream '{livestreamModel.DisplayName}'",
                messageText: $"Launching {settingsHandler.Settings.LivestreamExeDisplayName}....{Environment.NewLine}'{launcher} {livestreamerArgs}'");

            lock (WatchingStreamsLock)
            {
                watchingStreams.Add(livestreamModel);
            }

            StartLivestreamer(livestreamerArgs, messageBoxViewModel, onClose: () =>
            {
                lock (WatchingStreamsLock)
                {
                    watchingStreams.Remove(livestreamModel);
                }
            });
        }
Пример #13
0
        public async Task OpenChat(LivestreamModel livestreamModel, IViewAware fromScreen)
        {
            // guard against invalid/missing chrome path
            var chromeLocation = settingsHandler.Settings.ChromeFullPath;

            if (string.IsNullOrWhiteSpace(chromeLocation))
            {
                await fromScreen.ShowMessageAsync("No chrome locations specified",
                                                  $"Chrome location is not set in settings.{Environment.NewLine}Chat relies on chrome to function.");

                return;
            }
            if (!File.Exists(chromeLocation))
            {
                await fromScreen.ShowMessageAsync("Chrome not found",
                                                  $"Could not find chrome @ {chromeLocation}.{Environment.NewLine}Chat relies on chrome to function.");

                return;
            }
            // guard against stream provider not having chat support
            if (!livestreamModel.ApiClient.HasChatSupport)
            {
                await fromScreen.ShowMessageAsync("Chat not supported",
                                                  $"No external chat support for stream provider '{livestreamModel.ApiClient.ApiName}'");

                return;
            }

            string chromeArgs = $"--app={livestreamModel.ChatUrl} --window-size=350,758";

            await Task.Run(async() =>
            {
                try
                {
                    var proc = new Process
                    {
                        StartInfo =
                        {
                            FileName        = chromeLocation,
                            Arguments       = chromeArgs,
                            CreateNoWindow  = true,
                            UseShellExecute = false
                        }
                    };

                    proc.Start();
                }
                catch (Exception ex)
                {
                    await fromScreen.ShowMessageAsync("Error launching chat", ex.Message);
                }
            });
        }
Пример #14
0
 public FrameNavigationConductor(IViewAware modernWindowViewModel)
 {
     // Find the frame by looking in the control template of the window
     _frame = FindFrame(modernWindowViewModel);
     if (_frame != null)
     {
         // Wire up the events
         _frame.FragmentNavigation += frame_FragmentNavigation;
         _frame.Navigated          += frame_Navigated;
         _frame.Navigating         += frame_Navigating;
     }
 }
Пример #15
0
        public static bool SetFocus(this IViewAware screen, string property)
        {
            var view = screen.GetView() as UserControl;

            if (view != null)
            {
                var  control = FindChild(view, property);
                bool focus   = control != null && control.Focus();
                return(focus);
            }
            return(false);
        }
Пример #16
0
        public static bool SetFocus(this IViewAware screen, string property)
        {
            Contract.Requires(property != null, "Property cannot be null.");
            if (!(screen.GetView() is UserControl view))
            {
                return(false);
            }
            var  control = FindChild(view, property);
            bool focus   = control != null && control.Focus();

            return(focus);
        }
Пример #17
0
        /// <summary>
        /// Usage from a screen: e.g. control with xName="MyTextBox" -> this.SetFocus("MyTextBox"); <para />
        /// If setting focus during initial screen load, this must be called from "OnViewLoaded".
        /// </summary>
        public static bool SetFocus(this IViewAware screen, string property)
        {
            Contract.Requires(property != null, "Property cannot be null.");
            var view = screen.GetView() as ContentControl;

            if (view != null)
            {
                var  control = view.FindChild(property);
                bool focus   = control != null && control.Focus();
                return(focus);
            }
            return(false);
        }
        /// <summary>
        /// WhenLoaded allows you to register a Func to be called when a ViewModel's View is Loaded.
        /// </summary>
        /// <param name="item">Object that is view aware.</param>
        /// <param name="block">
        /// The method to be called when the corresponding View is loaded.
        /// The Action parameter (usually called 'disposables') allows
        /// you to collate all the disposables to be cleaned up during unloading.
        /// </param>
        public static void WhenLoaded(this IViewAware item, Action <CompositeDisposable> block)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            item.View.AddOnLoadedBlock(() =>
            {
                var d = new CompositeDisposable();
                block(d);
                return(new[] { d });
            });
        }
        /// <summary>
        /// WhenLoaded allows you to register a Func to be called when a ViewModel's View is Loaded.
        /// </summary>
        /// <param name="item">Object that is view aware.</param>
        /// <param name="block">
        /// The method to be called when the corresponding View is loaded.
        /// The Action parameter (usually called 'd') allows you to register Disposables to be cleaned up
        /// when the View is unloaded (i.e. "d(someObservable.Subscribe());").
        /// </param>
        public static void WhenLoaded(this IViewAware item, Action <Action <IDisposable> > block)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            item.View.AddOnLoadedBlock(() =>
            {
                var ret = new List <IDisposable>();
                block(ret.Add);
                return(ret);
            });
        }
Пример #20
0
    ModernFrame FindFrame(IViewAware viewAware)
    {
        // Get the view for the window
        var view = viewAware.GetView() as Control;

        if (view != null)
        {
            // Find the frame by name in the template
            var frame = view.Template.FindName("ContentFrame", view) as ModernFrame;
            if (frame != null)
            {
                return(frame);
            }
        }
        return(null);
    }
Пример #21
0
        public static void SetFocus(this IViewAware screen, string property)
        {
            if (!(screen.GetView() is DependencyObject view))
            {
                return;
            }

            FrameworkElement control = FindChild(view, property);

            if (control == null)
            {
                return;
            }

            KeyboardNavigationEx.Focus(control);
        }
        private bool ShowDialog(IViewAware owner, DsopScopeInitInfo scope, string targetServer, out SecurityIdentifier sid)
        {
            sid = null;

            DsopResult result = NativeMethods.ShowObjectPickerDialog(owner.GetHandle(), targetServer, DsopDialogInitializationOptions.DSOP_NONE, scope, "objectClass", "objectSid").FirstOrDefault();

            byte[] sidraw = result?.Attributes["objectSid"] as byte[];

            if (sidraw == null)
            {
                return(false);
            }

            sid = new SecurityIdentifier(sidraw, 0);

            return(true);
        }
        public bool GetUserOrGroups(IViewAware owner, string targetServer, out List <SecurityIdentifier> sids)
        {
            DsopScopeInitInfo scope = new DsopScopeInitInfo
            {
                Filter = new DsFilterFlags
                {
                    UpLevel =
                    {
                        BothModeFilter = DsopObjectFilterFlags.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE | DsopObjectFilterFlags.DSOP_FILTER_GLOBAL_GROUPS_SE | DsopObjectFilterFlags.DSOP_FILTER_UNIVERSAL_GROUPS_SE | DsopObjectFilterFlags.DSOP_FILTER_USERS | DsopObjectFilterFlags.DSOP_FILTER_WELL_KNOWN_PRINCIPALS | DsopObjectFilterFlags.DSOP_FILTER_SERVICE_ACCOUNTS | DsopObjectFilterFlags.DSOP_FILTER_BUILTIN_GROUPS
                    }
                },
                ScopeType = DsopScopeTypeFlags.DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN | DsopScopeTypeFlags.DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE | DsopScopeTypeFlags.DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN,
                InitInfo  = DsopScopeInitInfoFlags.DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS | DsopScopeInitInfoFlags.DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS | DsopScopeInitInfoFlags.DSOP_SCOPE_FLAG_STARTING_SCOPE,
            };

            return(this.ShowDialog(owner, scope, targetServer, out sids));
        }
        public async Task AddLivestream(ChannelIdentifier channelIdentifier, IViewAware viewAware)
        {
            if (channelIdentifier == null)
            {
                throw new ArgumentNullException(nameof(channelIdentifier));
            }
            if (channelIdentifiers.Contains(channelIdentifier))
            {
                return;                                                 // ignore duplicate requests
            }
            var livestreamQueryResults = await channelIdentifier.ApiClient.AddChannel(channelIdentifier);

            livestreamQueryResults.EnsureAllQuerySuccess();

            AddChannels(channelIdentifier);
            Livestreams.AddRange(livestreamQueryResults.Select(x => x.LivestreamModel));
        }
        public bool GetUsers(IViewAware owner, string targetServer, out List <SecurityIdentifier> sid)
        {
            DsopScopeInitInfo scope = new DsopScopeInitInfo
            {
                Filter = new DsFilterFlags
                {
                    UpLevel =
                    {
                        BothModeFilter = DsopObjectFilterFlags.DSOP_FILTER_USERS
                    }
                },
                ScopeType = DsopScopeTypeFlags.DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN | DsopScopeTypeFlags.DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE | DsopScopeTypeFlags.DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN,
                InitInfo  = DsopScopeInitInfoFlags.DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS | DsopScopeInitInfoFlags.DSOP_SCOPE_FLAG_STARTING_SCOPE
            };

            return(this.ShowDialog(owner, scope, targetServer, out sid));
        }
Пример #26
0
        private static MetroWindow GetMetroWindowFromScreen(this IViewAware screen)
        {
            var uiElement = screen?.GetView() as DependencyObject;

            if (uiElement == null)
            {
                throw new InvalidOperationException($"The view for {typeof(Screen).Name} is not a dependency object");
            }

            var metroWindow = MetroWindow.GetWindow(uiElement) as MetroWindow;

            if (metroWindow == null)
            {
                throw new InvalidOperationException($"Unable to get metro window from screen '{typeof(Screen).Name}'");
            }

            return(metroWindow);
        }
Пример #27
0
        public static void SetCaretIndexToEnd(this IViewAware screen, string property)
        {
            if (!(screen.GetView() is DependencyObject view))
            {
                return;
            }

            FrameworkElement control = VisualTreeExtensions.FindChild(view, property);

            if (control == null)
            {
                return;
            }

            TextBox textBox = VisualTreeExtensions.FindChild <TextBox>(control);

            if (textBox == null)
            {
                return;
            }

            textBox.CaretIndex = textBox.Text.Length;
        }
        private bool PromptForTargetForest(IViewAware owner, out string targetServer)
        {
            targetServer = null;

            SelectForestViewModel vm = new SelectForestViewModel();

            ExternalDialogWindow w = new ExternalDialogWindow
            {
                Title               = "Select forest",
                DataContext         = vm,
                SaveButtonName      = "Next...",
                SizeToContent       = SizeToContent.WidthAndHeight,
                SaveButtonIsDefault = true
            };

            foreach (Forest forest in this.domainTrustProvider.GetForests())
            {
                vm.AvailableForests.Add(forest.Name);
            }

            vm.SelectedForest = vm.AvailableForests.FirstOrDefault();

            if (vm.AvailableForests.Count > 1)
            {
                w.Owner = owner.GetWindow();

                if (!w.ShowDialog() ?? false)
                {
                    return(false);
                }
            }

            targetServer = this.discoveryServices.GetDomainController(vm.SelectedForest ?? Forest.GetCurrentForest().Name);

            return(true);
        }
Пример #29
0
        /// <summary>
        /// Given a ViewModel, create its View, ensure that it's a Window, and set it up
        /// </summary>
        /// <param name="viewModel">ViewModel to create the window for</param>
        /// <param name="isDialog">True if the window will be used as a dialog</param>
        /// <param name="ownerViewModel">Optionally the ViewModel which owns the view which should own this window</param>
        /// <returns>Window which was created and set up</returns>
        protected virtual Window CreateWindow(object viewModel, bool isDialog, IViewAware ownerViewModel)
        {
            var view   = this.viewManager.CreateAndBindViewForModelIfNecessary(viewModel);
            var window = view as Window;

            if (window == null)
            {
                var e = new StyletInvalidViewTypeException(String.Format("WindowManager.ShowWindow or .ShowDialog tried to show a View of type '{0}', but that View doesn't derive from the Window class. " +
                                                                         "Make sure any Views you display using WindowManager.ShowWindow or .ShowDialog derive from Window (not UserControl, etc)",
                                                                         view == null ? "(null)" : view.GetType().Name));
                logger.Error(e);
                throw e;
            }

            // Only set this it hasn't been set / bound to anything
            var haveDisplayName = viewModel as IHaveDisplayName;

            if (haveDisplayName != null && (String.IsNullOrEmpty(window.Title) || window.Title == view.GetType().Name) && BindingOperations.GetBindingBase(window, Window.TitleProperty) == null)
            {
                var binding = new Binding("DisplayName")
                {
                    Mode = BindingMode.TwoWay
                };
                window.SetBinding(Window.TitleProperty, binding);
            }

            if (ownerViewModel?.View is Window explicitOwner)
            {
                window.Owner = explicitOwner;
            }
            else if (isDialog)
            {
                var owner = this.InferOwnerOf(window);
                if (owner != null)
                {
                    // We can end up in a really weird situation if they try and display more than one dialog as the application's closing
                    // Basically the MainWindow's no long active, so the second dialog chooses the first dialog as its owner... But the first dialog
                    // hasn't yet been shown, so we get an exception ("cannot set owner property to a Window which has not been previously shown").
                    try
                    {
                        window.Owner = owner;
                    }
                    catch (InvalidOperationException e)
                    {
                        logger.Error(e, "This can occur when the application is closing down");
                    }
                }
            }

            if (isDialog)
            {
                logger.Info("Displaying ViewModel {0} with View {1} as a Dialog", viewModel, window);
            }
            else
            {
                logger.Info("Displaying ViewModel {0} with View {1} as a Window", viewModel, window);
            }

            // If and only if they haven't tried to position the window themselves...
            // Has to be done after we're attempted to set the owner
            if (window.WindowStartupLocation == WindowStartupLocation.Manual && Double.IsNaN(window.Top) && Double.IsNaN(window.Left) &&
                BindingOperations.GetBinding(window, Window.TopProperty) == null && BindingOperations.GetBinding(window, Window.LeftProperty) == null)
            {
                window.WindowStartupLocation = window.Owner == null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner;
            }

            // This gets itself retained by the window, by registering events
            // ReSharper disable once ObjectCreationAsStatement
            new WindowConductor(window, viewModel);

            return(window);
        }
Пример #30
0
 /// <summary>
 /// Given a ViewModel, show its corresponding View as a Dialog, and set its owner
 /// </summary>
 /// <param name="viewModel">ViewModel to show the View for</param>
 /// <param name="ownerViewModel">The ViewModel for the View which should own this dialog</param>
 /// <returns>DialogResult of the View</returns>
 public bool?ShowDialog(object viewModel, IViewAware ownerViewModel)
 {
     return(this.CreateWindow(viewModel, true, ownerViewModel).ShowDialog());
 }