Beispiel #1
0
        // CONSTRUCTOR
        public ChannelAPI(CollabrifyClient c, LoadCompletedEventHandler del = null)
        {
            Debug.WriteLine(LOG_TAG + ": building ChannelAPI.");
            mChannelClosed = true;

            client = c;

            // Builds the browser object
            try
            {
                browser = new WebBrowser();
                browser.IsScriptEnabled = true;
                browser.ScriptNotify   += ScriptCallback;
                browser.LoadCompleted  += delegate { };
                if (del != null)
                {
                    browser.LoadCompleted += del;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(LOG_TAG + ": " + ex.Source);
                Debug.WriteLine("\t" + ex.Message);
            }

            string html = null;

            using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Collabrify_wp8.Resources.home.html"))
                using (var r = new StreamReader(s))
                    html = r.ReadToEnd();

            browser.NavigateToString(html);
        } // CONSTRUCTOR
Beispiel #2
0
        public Task LogoutAsync(Uri logoutUri)
        {
            var frame = new Frame();
            var tcs   = new TaskCompletionSource <bool>();
            LoadCompletedEventHandler    loadCompletedHandler = null;
            NavigationFailedEventHandler failedHandler        = null;
            Action unsubscribe = () =>
            {
                // ReSharper disable AccessToModifiedClosure
                frame.LoadCompleted    -= loadCompletedHandler;
                frame.NavigationFailed -= failedHandler;
                // ReSharper restore AccessToModifiedClosure
            };

            loadCompletedHandler =
                (sender, e) =>
            {
                unsubscribe();
                tcs.SetResult(true);
            };
            failedHandler =
                (sender, e) =>
            {
                unsubscribe();
                tcs.SetException(e.Exception);
            };
            frame.LoadCompleted    += loadCompletedHandler;
            frame.NavigationFailed += failedHandler;
            frame.Navigate(logoutUri);
            return(tcs.Task);
        }
Beispiel #3
0
        /// <summary>
        /// Navigates to the given source URI and waits for the loading to complete or fail.
        /// </summary>
        public static async Task NavigateAsync(this WebView webView, Uri source)
        {
            var tcs = new TaskCompletionSource <object>();

            // Need to set it to null so that the compiler does not
            // complain about use of unassigned local variable.
            WebViewNavigationFailedEventHandler nfeh = null;
            LoadCompletedEventHandler           lceh = null;

            //webView.NavigationFailed
            //webView.LoadCompleted

            nfeh = (s, e) =>
            {
                webView.NavigationFailed -= nfeh;
                webView.LoadCompleted    -= lceh;
                tcs.SetResult(null);
            };

            lceh = (s, e) =>
            {
                webView.NavigationFailed -= nfeh;
                webView.LoadCompleted    -= lceh;
                tcs.SetResult(null);
            };

            webView.NavigationFailed += nfeh;
            webView.LoadCompleted    += lceh;

            webView.Navigate(source);

            await tcs.Task;
        }
        // CONSTRUCTOR
        public ChannelAPI(CollabrifyClient c, LoadCompletedEventHandler del = null)
        {
            Debug.WriteLine(LOG_TAG + ": building ChannelAPI.");
              mChannelClosed = true;

              client = c;

              // Builds the browser object
              try
              {
            browser = new WebBrowser();
            browser.IsScriptEnabled = true;
            browser.ScriptNotify += ScriptCallback;
            browser.LoadCompleted += delegate { };
            if(del != null) browser.LoadCompleted += del;
              }
              catch( Exception ex)
              {
            Debug.WriteLine(LOG_TAG + ": " + ex.Source);
            Debug.WriteLine("\t" + ex.Message);
              }

              string html = null;
              using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Collabrify_wp8.Resources.home.html"))
              using (var r = new StreamReader(s))
              html = r.ReadToEnd();

              browser.NavigateToString(html);
        }
Beispiel #5
0
 public ScriptInvoker(WebBrowser browser, string methodName, Object[] args)
 {
     this.browser                = browser;
     this.methodName             = methodName;
     this.args                   = args;
     this.handler                = new LoadCompletedEventHandler(browser_LoadCompleted);
     this.browser.LoadCompleted += handler;
 }
Beispiel #6
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// loadcompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this LoadCompletedEventHandler loadcompletedeventhandler, Object sender, NavigationEventArgs e, AsyncCallback callback)
        {
            if (loadcompletedeventhandler == null)
            {
                throw new ArgumentNullException("loadcompletedeventhandler");
            }

            return(loadcompletedeventhandler.BeginInvoke(sender, e, callback, null));
        }
Beispiel #7
0
        public static async Task GoToPageAsync(this WebBrowser browser, string url)
        {
            var resultGenerator = new TaskCompletionSource <bool>();
            LoadCompletedEventHandler loadCompletedEvent = (_, __) => resultGenerator.SetResult(true);

            browser.LoadCompleted += loadCompletedEvent;
            browser.Navigate(url);
            await resultGenerator.Task;

            browser.LoadCompleted -= loadCompletedEvent;
        }
Beispiel #8
0
        void NavigateGoogle(string url, string word)
        {
            LoadCompletedEventHandler e = null;

            e = new LoadCompletedEventHandler((o, args) =>
            {
                webBrowser.LoadCompleted -= e;
                webBrowser.InvokeScript("eval", $"document.getElementById('source').innerText='{StringToUnicode( word)}'");
            });
            webBrowser.LoadCompleted += e;
            //webBrowser.Source = new Uri(url);
            webBrowser.Navigate(url);
        }
Beispiel #9
0
    public static Task NavigateAsync(this WebBrowser wb, Uri uri)
    {
        var tcs = new TaskCompletionSource <object>();
        LoadCompletedEventHandler completedEvent = null;

        completedEvent = (sender, e) =>
        {
            wb.LoadCompleted -= completedEvent;
            tcs.SetResult(null);
        };
        wb.LoadCompleted += completedEvent;
        wb.Navigate(uri);
        return(tcs.Task);
    }
    public static Task NavigateAsync(this WebBrowser browser, Uri uri)
    {
        var tcs = new TaskCompletionSource <object>();
        LoadCompletedEventHandler loadCompleted = null;

        loadCompleted = (s, e) =>
        {
            browser.LoadCompleted -= loadCompleted;
            tcs.SetResult(e.WebResponse);
        };
        browser.LoadCompleted += loadCompleted;
        browser.Navigate(uri);
        return(tcs.Task);
    }
Beispiel #11
0
        public void NavigateTo(string pageKey, string propertyName, object parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }



            lock (pagesByKey)
            {
                if (!pagesByKey.ContainsKey(pageKey))
                {
                    throw new ArgumentException(string.Format("No such page: {0} ", pageKey), "pageKey");
                }

                Frame frame = (Frame)GetDescendantFromName(Application.Current.MainWindow, "MainFrame");


                if (frame != null)
                {
                    frame.Source = pagesByKey[pageKey];

                    LoadCompletedEventHandler eventHandler = null;
                    eventHandler = delegate(object sender, NavigationEventArgs e)
                    {
                        Page page = (Page)frame.Content;

                        PropertyInfo property = page.DataContext.GetType().GetProperty(propertyName);

                        Type vmType = page.DataContext.GetType();


                        if (property.PropertyType == parameter.GetType())
                        {
                            property.SetValue(Convert.ChangeType(page.DataContext, vmType), Convert.ChangeType(parameter, property.PropertyType), null);
                        }

                        frame.LoadCompleted -= eventHandler;
                    };

                    frame.LoadCompleted += eventHandler;
                }

                historic.Add(pageKey);
                CurrentPageKey = pageKey;
            }
        }
Beispiel #12
0
        /// <summary>
        /// Links a <see cref="ParseUser" /> to a Facebook account, allowing you to use Facebook
        /// for authentication, and providing access to Facebook data for the user.
        ///
        /// The user will be logged in through Facebook's OAuth web flow, so you must supply a
        /// <paramref name="webView"/> that will be navigated to Facebook's authentication pages.
        /// </summary>
        /// <param name="user">The user to link with Facebook.</param>
        /// <param name="webView">A web view that will be used to present the authorization pages
        /// to the user.</param>
        /// <param name="permissions">A list of Facebook permissions to request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public static async Task LinkAsync(ParseUser user,
                                           WebBrowser webView,
                                           IEnumerable <string> permissions,
                                           CancellationToken cancellationToken)
        {
            authProvider.Permissions = permissions;
            LoadCompletedEventHandler loadCompleted = (_, e) => authProvider.HandleNavigation(e.Uri);

            webView.LoadCompleted += loadCompleted;
            Action <Uri> navigate = uri => webView.Navigate(uri);

            authProvider.Navigate += navigate;
            await user.LinkWithAsync("facebook", cancellationToken);

            authProvider.Navigate -= navigate;
            webView.LoadCompleted -= loadCompleted;
        }
Beispiel #13
0
        /// <summary>
        /// Logs in a <see cref="ParseUser" /> using Facebook for authentication. If a user for the
        /// given Facebook credentials does not already exist, a new user will be created.
        ///
        /// The user will be logged in through Facebook's OAuth web flow, so you must supply a
        /// <paramref name="webView"/> that will be navigated to Facebook's authentication pages.
        /// </summary>
        /// <param name="webView">A web view that will be used to present the authorization pages
        /// to the user.</param>
        /// <param name="permissions">A list of Facebook permissions to request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The user that was either logged in or created.</returns>
        public static async Task <ParseUser> LogInAsync(WebBrowser webView,
                                                        IEnumerable <string> permissions,
                                                        CancellationToken cancellationToken)
        {
            authProvider.Permissions = permissions;
            LoadCompletedEventHandler loadCompleted = (_, e) => authProvider.HandleNavigation(e.Uri);

            webView.LoadCompleted += loadCompleted;
            Action <Uri> navigate = uri => webView.Navigate(uri);

            authProvider.Navigate += navigate;
            var result = await ParseUser.LogInWithAsync("facebook", cancellationToken);

            authProvider.Navigate -= navigate;
            webView.LoadCompleted -= loadCompleted;
            return(result);
        }
        public void Logout()
        {
            LoadCompletedEventHandler loadCompleted = null;

            loadCompleted = (sender, e) => {
                if (facebookLoginBrowser.SaveToString().Contains("logout_form"))
                {
                    FacebookLogo.Visibility = Visibility.Visible;
                    facebookLoginBrowser.InvokeScript("eval", "document.forms['logout_form'].submit();");
                    facebookLoginBrowser.Visibility     = Visibility.Collapsed;
                    facebookLoginBrowser.LoadCompleted -= loadCompleted;
                    AccessToken = null;
                }
                facebookLoginBrowser.Navigated += FacebookLoginBrowserNavigated;
                CloseLoginPage();
            };

            LoginStatusText.Visibility          = Visibility.Collapsed;
            facebookLoginBrowser.Navigated     -= FacebookLoginBrowserNavigated;
            facebookLoginBrowser.LoadCompleted += loadCompleted;
            facebookLoginBrowser.Navigate(new Uri("https://www.facebook.com/logout.php"));
        }
 public void ButtonVis(object sender, LoadCompletedEventHandler e)
 {
 }
                private void PrepareControl()
        {
            // fix bug #1 in a brutal way
            var d = DataContext as ReadArticleViewModel;
            if (d != null)
            {
                d.LoadingIndicator = true;
            }

            if (StartNavigating != null)
            {
                StartNavigating(this, new NavigatingEventArgs());
            }
            Opacity = 0;
            LoadCompleted += new LoadCompletedEventHandler((ss, ee) =>
                {
                    Opacity = 1;
                });
        }
Beispiel #17
0
		public static UnmanagedEventHandler CreateLoadCompletedEventHandlerDispatcher (LoadCompletedEventHandler handler)
		{
			return SafeDispatcher( (sender, calldata, closure)
						=> handler (NativeDependencyObjectHelper.FromIntPtr (closure),
								new NavigationEventArgs ()) );
		}
 /// <summary>
 ///   Provides a secure method for setting the LoadCompletedEventHandler property. This dependency property indicates ....
 /// </summary>
 private static void SetLoadCompletedEventHandler(DependencyObject d, LoadCompletedEventHandler value)
 {
     d.SetValue(LoadCompletedEventHandlerPropertyKey, value);
 }
Beispiel #19
0
        // Used in XamlTest
        //
        internal static NavigationWindow CreateNavigationWindow(string filename, string callingAssembly, LoadCompletedEventHandler handler)
        {
            NavigationWindow navigationWindow;

            if (BrowserInteropHelper.IsBrowserHosted)
            {
                GlobalLog.LogDebug("Browser hosted");
                navigationWindow = (NavigationWindow)Application.Current.MainWindow;
            }
            else
            {
                GlobalLog.LogDebug("not Browser hosted");
                GlobalLog.LogEvidence("Creating a NavigationWindow");
                NavigationWindow navwinsw = new NavigationWindow();
                navigationWindow = navwinsw;
            }

            if (handler != null)
            {
                navigationWindow.LoadCompleted += handler;
            }
            string strUri = "pack://application:,,,/" + callingAssembly + ";component/" + filename;

            GlobalLog.LogEvidence("Navigating to " + strUri);
            navigationWindow.Navigate(new Uri(strUri, UriKind.RelativeOrAbsolute));

            if (!BrowserInteropHelper.IsBrowserHosted)
            {
                GlobalLog.LogEvidence("Showing the Window");
                navigationWindow.Show();
            }

            DispatcherHelper.DoEvents(0, DispatcherPriority.Input);

            return(navigationWindow);
        }
Beispiel #20
0
 public static UnmanagedEventHandler CreateLoadCompletedEventHandlerDispatcher(LoadCompletedEventHandler handler)
 {
     return(SafeDispatcher((sender, calldata, closure)
                           => handler(NativeDependencyObjectHelper.FromIntPtr(closure),
                                      new NavigationEventArgs())));
 }
Beispiel #21
0
        static LoadCompletedEventHandler LastEventHandler = null;//
        public void Execute(object parameter)
        {
            var oldSrc = Container.Source;

            Container.Source         = null;
            Container.LoadCompleted -= LastEventHandler;
            OpenFuncParam param = (OpenFuncParam)parameter;

            if (param == null)
            {
                _logHelper.LogError("parameter不是有效的OpenFuncParam类型");
                MessageWindow.ShowMsg(MessageType.Error, OperationDesc.OpenFunc, MsgConst.Msg_ViewAppLog);
                return;
            }
            if (string.IsNullOrEmpty(param.PageUri))
            {
                _logHelper.LogError("PageUri不能为空");
                MessageWindow.ShowMsg(MessageType.Error, OperationDesc.OpenFunc, MsgConst.Msg_ViewAppLog);
                return;
            }
            //需要在LoadCompleted事件中,才能获取到绑定到Frame的Page实例
            LastEventHandler = (o, e) =>
            {
                try
                {
                    var page = e.Content as BasePage;
                    if (page == null)
                    {
                        throw new Exception("未找到page,请检查uri是否正确或是否继承BasePage");
                    }
                    page.FuncCode = param.FuncCode;
                }
                catch (Exception ex)
                {
                    _logHelper.LogError("Container(Frame).LoadCompleted事件", ex);
                    throw new Exception("打开功能菜单错误", ex);
                }
            };
            Container.LoadCompleted += LastEventHandler;
            if (oldSrc != null && oldSrc.ToString() == param.PageUri.Trim('/'))
            {
                //相同uri,不会重新加载,需要实例化对象
                //“/Biz.PartyBuilding.YS.Client;component/Learn/PartyLearnPage.xaml”
                var strUri    = param.PageUri.Trim('/');
                var start     = strUri.LastIndexOf("/") + 1;
                var len       = strUri.LastIndexOf(".xaml") - start;
                var className = strUri.Substring(start, len);
                var assName   = strUri.Substring(0, strUri.IndexOf(';'));
                try
                {
                    var      ass  = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name == assName).FirstOrDefault();
                    Type     type = ass.GetTypes().Where(t => t.Name == className).FirstOrDefault();
                    BasePage page = Activator.CreateInstance(type) as BasePage;
                    Container.Navigate(page);
                }
                catch (Exception ex)
                {
                    _logHelper.LogError("OpenFuncCmd.Execute——相同uri Page实例化失败,uri:" + param.PageUri, ex);
                    throw new Exception("打开功能菜单失败,实例化page失败,请检查uri是否正确");
                }
            }
            else
            {
                Container.Navigate(PageHelper.GetPageFullUri(param.PageUri));
            }
        }
Beispiel #22
0
        public static Task <object> NavigateAsync(this WebBrowser wb, string link, SynchronizationContext SC)
        {
            if (wb == null)
            {
                throw new ArgumentNullException("wb");
            }
            var tcs = new TaskCompletionSource <object>();
            LoadCompletedEventHandler handler1 = delegate { };
            NavigatedEventHandler     handler2 = delegate { };

            handler1 = (s, e) =>
            {
                dynamic activeX = wb.GetType().InvokeMember("ActiveXInstance",
                                                            BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
                                                            null, wb, new object[] { });
                activeX.Silent = true;

                //if (wb.ReadyState != WebBrowserReadyState.Complete) return;
                //if (PageLoaded.Task.IsCompleted) return;
                tcs.SetResult(wb.Document);
                wb.LoadCompleted -= handler1;
                //wb.Navigated -= handler2;
            };

            handler2 = (s, e) =>
            {
                dynamic doc = ((WebBrowser)s).Document;
                var     url = doc.url as string;
                if (url != null && url.StartsWith("res://ieframe.dll"))
                {
                    tcs.SetException(new InvalidOperationException("Page load error"));
                }
                //wb.LoadCompleted -= handler1;
                wb.Navigated -= handler2;
            };

            wb.LoadCompleted += handler1;
            wb.Navigated     += handler2;
            SC.Post(new SendOrPostCallback(o => { wb.Navigate(link); }), link);
            return(tcs.Task);

            //await Application.Current.Dispatcher.BeginInvoke(new Action(() => { wb.Navigate(link); }));
            //wb.Navigate(new Uri(link));

            /*
             * int TimeElapsed = 0;
             *          while (tcs.Task.Status != TaskStatus.RanToCompletion)
             *          {
             *              await Task.Delay(50);
             *              TimeElapsed++;
             *              if (TimeElapsed >= 1000)
             *              {
             *                 tcs.TrySetResult(true);
             *              }
             *          }
             */
            //надо ли?
            //while (tcs.Task.Status != TaskStatus.RanToCompletion)
            //{
            //    await Task.Delay(50);
            //}
            //await tcs.Task;
        }