Ejemplo n.º 1
0
        public static void RestoreState(PhoneApplicationPage page)
        {
            foreach (PropertyInfo tombstoneProperty in FindTombstoneProperties(page.DataContext))
            {
                string key = "ViewModel." + tombstoneProperty.Name;

                if (page.State.ContainsKey(key))
                {
                    tombstoneProperty.SetValue(page.DataContext, page.State[key], null);
                }
            }

            if (page.State.ContainsKey("FocusedControl.Name"))
            {
                string focusedControlName = (string)page.State["FocusedControl.Name"];
                Control focusedControl = (Control)page.FindName(focusedControlName);

                if (focusedControl != null)
                {
                    page.Loaded += delegate
                    {
                        focusedControl.Focus();
                    };
                }
            }
        }
Ejemplo n.º 2
0
        public void alert(string options)
        {
            string[]     args      = JSON.JsonHelper.Deserialize <string[]>(options);
            AlertOptions alertOpts = new AlertOptions();

            alertOpts.message     = args[0];
            alertOpts.title       = args[1];
            alertOpts.buttonLabel = args[2];
            string aliasCurrentCommandCallbackId = args[3];

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        var previous  = notifyBox;
                        notifyBox     = new NotificationBox();
                        notifyBox.Tag = new NotifBoxData {
                            previous = previous, callbackId = aliasCurrentCommandCallbackId
                        };
                        notifyBox.PageTitle.Text = alertOpts.title;
                        notifyBox.SubTitle.Text  = alertOpts.message;
                        Button btnOK             = new Button();
                        btnOK.Content            = alertOpts.buttonLabel;
                        btnOK.Click += new RoutedEventHandler(btnOK_Click);
                        btnOK.Tag    = 1;
                        notifyBox.ButtonPanel.Children.Add(btnOK);
                        grid.Children.Add(notifyBox);

                        if (previous == null)
                        {
                            page.BackKeyPress += page_BackKeyPress;
                        }
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
        private Grid getLayoutRoot()
        {
            PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (frame != null)
            {
                PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        return(grid);
                    }
                    ;
                }
            }
            return(null);
        }
 public override void OnInit()
 {
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
         if (frame != null)
         {
             PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
             if (page != null)
             {
                 CordovaView cView = page.FindName("CordovaView") as CordovaView;
                 if (cView != null)
                 {
                     WebBrowser br        = cView.Browser;
                     br.NavigationFailed += defaultHttpAuthHandler;
                 }
             }
         }
     });
 }
 private void setBrowserEnable(bool IsEnabled)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
         if (frame != null)
         {
             PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
             if (page != null)
             {
                 CordovaView cView = page.FindName("CordovaView") as CordovaView;
                 if (cView != null)
                 {
                     WebBrowser wb = cView.Browser;
                     wb.IsEnabled  = IsEnabled;
                 }
             }
         }
     });
 }
Ejemplo n.º 6
0
        void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Button           btn            = sender as Button;
            FrameworkElement notifBoxParent = null;
            int    retVal     = 0;
            string callbackId = "";

            if (btn != null)
            {
                retVal = (int)btn.Tag + 1;

                notifBoxParent = btn.Parent as FrameworkElement;
                while ((notifBoxParent = notifBoxParent.Parent as FrameworkElement) != null &&
                       !(notifBoxParent is NotificationBox))
                {
                    ;
                }
            }
            if (notifBoxParent != null)
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        grid.Children.Remove(notifBoxParent);
                    }

                    NotifBoxData notifBoxData = notifBoxParent.Tag as NotifBoxData;
                    notifyBox  = notifBoxData.previous as NotificationBox;
                    callbackId = notifBoxData.callbackId as string;

                    if (notifyBox == null)
                    {
                        page.BackKeyPress -= page_BackKeyPress;
                    }
                }
            }
            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, retVal), callbackId);
        }
Ejemplo n.º 7
0
        void page_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            PhoneApplicationPage page = sender as PhoneApplicationPage;

            if (page != null && notifyBox != null)
            {
                Grid grid = page.FindName("LayoutRoot") as Grid;
                if (grid != null)
                {
                    grid.Children.Remove(notifyBox);
                    notifyBox = notifyBox.Tag as NotificationBox;
                }
                if (notifyBox == null)
                {
                    page.BackKeyPress -= page_BackKeyPress;
                }
                e.Cancel = true;
            }

            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, 0));
        }
Ejemplo n.º 8
0
        public void confirm(string options)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                string[] args          = JSON.JsonHelper.Deserialize <string[]>(options);
                AlertOptions alertOpts = new AlertOptions();
                alertOpts.message      = args[0];
                alertOpts.title        = args[1];
                alertOpts.buttonLabel  = args[2];

                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        notifBox = new NotificationBox();
                        notifBox.PageTitle.Text = alertOpts.title;
                        notifBox.SubTitle.Text  = alertOpts.message;

                        string[] labels = alertOpts.buttonLabel.Split(',');
                        for (int n = 0; n < labels.Length; n++)
                        {
                            Button btn  = new Button();
                            btn.Content = labels[n];
                            btn.Tag     = n;
                            btn.Click  += new RoutedEventHandler(btnOK_Click);
                            notifBox.ButtonPanel.Children.Add(btn);
                        }

                        grid.Children.Add(notifBox);
                        page.BackKeyPress += page_BackKeyPress;
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
Ejemplo n.º 9
0
        // Device orientation
        private void onOrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            // Asynchronous UI threading call
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;

                if (frame != null)
                {
                    PhoneApplicationPage page = frame.Content as PhoneApplicationPage;

                    if (page != null)
                    {
                        CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView;
                        if (view != null)
                        {
                            setCordovaViewHeight(frame, view);
                        }
                    }
                }
            });
        }
        public void setup(string options)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => {
                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                if (frame != null)
                {
                    PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                    if (page != null)
                    {
                        CordovaView cordovaView = page.FindName("CordovaView") as CordovaView;
                        if (cordovaView != null)
                        {
                            WebBrowser browser = cordovaView.Browser;

                            SetupOrientation(page);
                            SetupExitAppDispatcher(browser);
                            HideSystemTray();
                        }
                    }
                }
            });
        }
        public void addProgressBar(String colorStr)
        {
            if (progressBar != null)
            {
                return;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                progressBar = new ProgressBar();
                progressBar.IsIndeterminate = true;
                progressBar.Visibility      = Visibility.Visible;
                try
                {
                    var brush = new SolidColorBrush(
                        Color.FromArgb(
                            255,
                            Convert.ToByte(colorStr.Substring(1, 2), 16),
                            Convert.ToByte(colorStr.Substring(3, 2), 16),
                            Convert.ToByte(colorStr.Substring(5, 2), 16)
                            )
                        );
                    progressBar.Foreground = brush;
                }
                catch { }

                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                if (frame != null)
                {
                    PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                    if (page != null)
                    {
                        Grid grid = page.FindName(GRID_NAME) as Grid;

                        grid.Children.Add(progressBar);
                    }
                }
            });
        }
Ejemplo n.º 12
0
 private void _hideBannerAd_overlap()
 {
     if (bannerView != null)
     {
         PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
         if (frame != null)
         {
             PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
             if (page != null)
             {
                 Grid grid = page.FindName("LayoutRoot") as Grid;
                 if (grid != null)
                 {
                     if (grid.Children.Contains(bannerView))
                     {
                         grid.Children.Remove(bannerView);
                     }
                 }
             }
         }
     }
 }
        private void ShowCordovaBrowser(string url)
        {
            Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                if (frame != null)
                {
                    PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                    if (page != null)
                    {
                        CordovaView cView = page.FindName("CordovaView") as CordovaView;
                        if (cView != null)
                        {
                            WebBrowser br = cView.Browser;
                            br.Navigate(loc);
                        }
                    }
                }
            });
        }
Ejemplo n.º 14
0
        void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Button btn    = sender as Button;
            int    retVal = 0;

            if (btn != null)
            {
                retVal = (int)btn.Tag + 1;
            }
            if (notifBox != null)
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        grid.Children.Remove(notifBox);
                    }
                }
                notifBox = null;
            }
            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, retVal));
        }
Ejemplo n.º 15
0
        protected override void Invoke(object parameter)
        {
            var list = this.AssociatedObject as Selector;

            if (list == null)
            {
                return;
            }

            if (this.page == null)
            {
                return;
            }

            if (list.SelectedIndex != -1)
            {
                this.transition = (Storyboard)page.FindName(this.Transition);
                if (this.transition != null)
                {
                    this.transition.Completed += this.TransitionCompleted;
                    this.transition.Begin();
                }
            }
        }
Ejemplo n.º 16
0
        void page_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            PhoneApplicationPage page = sender as PhoneApplicationPage;
            string callbackId         = "";

            if (page != null && notifyBox != null)
            {
                Grid grid = page.FindName("LayoutRoot") as Grid;
                if (grid != null)
                {
                    grid.Children.Remove(notifyBox);
                    dynamic notifBoxData = notifyBox.Tag;
                    notifyBox  = notifBoxData.previous as NotificationBox;
                    callbackId = notifBoxData.callbackId as string;
                }
                if (notifyBox == null)
                {
                    page.BackKeyPress -= page_BackKeyPress;
                }
                e.Cancel = true;
            }

            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, 0), callbackId);
        }
Ejemplo n.º 17
0
 public void close(string options = "")
 {
     if (browser != null)
     {
         Deployment.Current.Dispatcher.BeginInvoke(() =>
         {
             PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
             if (frame != null)
             {
                 PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                 if (page != null)
                 {
                     Grid grid = page.FindName("LayoutRoot") as Grid;
                     if (grid != null)
                     {
                         grid.Children.Remove(browser);
                     }
                     page.ApplicationBar = null;
                 }
             }
             browser = null;
         });
     }
 }
Ejemplo n.º 18
0
 // Remove our inderminate progress indicator
 public void activityStop(string unused)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         if (progressBar != null)
         {
             progressBar.IsEnabled       = false;
             PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
             if (frame != null)
             {
                 PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                 if (page != null)
                 {
                     Grid grid = page.FindName("LayoutRoot") as Grid;
                     if (grid != null)
                     {
                         grid.Children.Remove(progressBar);
                     }
                 }
             }
             progressBar = null;
         }
     });
 }
Ejemplo n.º 19
0
        private void ShowInAppBrowser(string url)
        {
            Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (browser != null)
                {
                    //browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                    browser.Navigate2(loc);
                }
                else
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;

                        if (!(System.Environment.OSVersion.Version.Major == 8 && System.Environment.OSVersion.Version.Minor == 0))
                        {
                            SystemTray.SetIsVisible(page, false);
                        }

                        string baseImageUrl = "/www/Images/";

                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                browser = new WebBrowser();
                                browser.IsScriptEnabled = true;
                                browser.Background      = new SolidColorBrush(Colors.Black);
                                browser.LoadCompleted  += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);

                                browser.Navigating       += new EventHandler <NavigatingEventArgs>(browser_Navigating);
                                browser.NavigationFailed += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
                                browser.Navigated        += new EventHandler <System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
                                browser.Navigate2(loc);

                                //if (StartHidden)
                                //{
                                //    browser.Visibility = Visibility.Collapsed;
                                //}

                                grid.Background = new SolidColorBrush(Colors.Black);

                                var rowDef    = new RowDefinition();
                                rowDef.Height = GridLength.Auto;
                                grid.RowDefinitions.Insert(0, rowDef);

                                buttons = new StackPanel();
                                buttons.HorizontalAlignment = HorizontalAlignment.Right;
                                buttons.Orientation         = Orientation.Horizontal;
                                buttons.Visibility          = Visibility.Collapsed;

                                var backBitmapImage    = new BitmapImage(new Uri(baseImageUrl + "ic_action_back.png", UriKind.Relative));
                                var backImage          = new Image();
                                backImage.Source       = backBitmapImage;
                                backButton             = new Button();
                                backButton.Content     = backImage;
                                backButton.Width       = 100;
                                backButton.BorderBrush = new SolidColorBrush(Colors.Black);
                                //backButton.Text = "Back";
                                //backButton.IconUri = new Uri(baseImageUrl + "appbar.back.rest.png", UriKind.Relative);
                                backButton.Click += new RoutedEventHandler(backButton_Click);
                                buttons.Children.Add(backButton);


                                var reloadBitmapImage    = new BitmapImage(new Uri(baseImageUrl + "ic_action_refresh.png", UriKind.Relative));
                                var reloadImage          = new Image();
                                reloadImage.Source       = reloadBitmapImage;
                                reloadButton             = new Button();
                                reloadButton.Content     = reloadImage;
                                reloadButton.Width       = 100;
                                reloadButton.BorderBrush = new SolidColorBrush(Colors.Black);
                                //reloadButton.IconUri = new Uri(baseImageUrl + "appbar.next.rest.png", UriKind.Relative);
                                reloadButton.Click += new RoutedEventHandler(reloadButton_Click);
                                buttons.Children.Add(reloadButton);

                                Grid.SetRow(buttons, 0);
                                grid.Children.Add(buttons);


                                //browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                                Grid.SetRow(browser, 1);
                                grid.Children.Add(browser);
                            }

                            //if (ShowLocation)
                            //{
                            //    ApplicationBar bar = new ApplicationBar();
                            //    bar.BackgroundColor = Colors.Black;
                            //    bar.IsMenuEnabled = false;


                            //    //ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
                            //    //closeBtn.Text = "Close";
                            //    //closeBtn.IconUri = new Uri(baseImageUrl + "appbar.close.rest.png", UriKind.Relative);
                            //    //closeBtn.Click += new EventHandler(closeBtn_Click);
                            //    //bar.Buttons.Add(closeBtn);

                            //    page.ApplicationBar = bar;
                            //    bar.IsVisible = !StartHidden;
                            //    AppBar = bar;
                            //}

                            page.BackKeyPress += page_BackKeyPress;
                        }
                    }
                }
            });
        }
Ejemplo n.º 20
0
        private void _showBannerAd_overlap(string position, string size)
        {
            PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (frame != null)
            {
                PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        if (position.Equals("top-left"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Top;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Left;
                        }
                        else if (position.Equals("top-center"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Top;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                        else if (position.Equals("top-right"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Top;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Right;
                        }
                        else if (position.Equals("left"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Center;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Left;
                        }
                        else if (position.Equals("center"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Center;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                        else if (position.Equals("right"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Center;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Right;
                        }
                        else if (position.Equals("bottom-left"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Bottom;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Left;
                        }
                        else if (position.Equals("bottom-center"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Bottom;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                        else if (position.Equals("bottom-right"))
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Bottom;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Right;
                        }
                        else
                        {
                            bannerView.VerticalAlignment   = VerticalAlignment.Top;
                            bannerView.HorizontalAlignment = HorizontalAlignment.Center;
                        }

                        grid.Children.Add(bannerView);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Create a banner view readyfor loaded with an advert and shown
        /// args JSON format is:
        /// {
        ///   publisherId: "Publisher ID 1 for banners"
        ///   adSize: "BANNER" or "SMART_BANNER"
        ///   bannerAtTop: "true" or "false"
        ///   overlap: "true" or "false"
        ///   autoShow: "true" or "false"
        /// }
        ///
        /// Note: if autoShow is set to true then additional parameters can be set above:
        ///   isTesting: "true" or "false" (Set to true for live deployment)
        ///   birthday: "2014-09-25" Optional date for advert targeting
        ///   gender: "male" or "female" Optional gender for advert targeting
        ///   location: "true" or "false" Optional geolocation for advert targeting
        ///   keywords: "list of space separated keywords" Limit ad targeting
        /// </summary>
        /// <param name="args">JSON format arguments</param>
        public void createBannerView(string args)
        {
            //Debug.WriteLine("AdMob.createBannerView: " + args);

            string  callbackId  = "";
            string  publisherId = optPublisherId;
            string  adSize      = optAdSize;
            Boolean bannerAtTop = optBannerAtTop;
            Boolean overlap     = optOverlap;
            Boolean autoShow    = optAutoShow;

            Dictionary <string, string> parameters = null;

            try
            {
                string[] inputs = JsonHelper.Deserialize <string[]>(args);
                if (inputs != null && inputs.Length >= 1)
                {
                    if (inputs.Length >= 2)
                    {
                        callbackId = inputs[ARG_IDX_CALLBACK_ID];
                    }

                    parameters = getParameters(inputs[ARG_IDX_PARAMS]);

                    if (parameters.ContainsKey(OPT_PUBLISHER_ID))
                    {
                        publisherId = parameters[OPT_PUBLISHER_ID];
                    }

                    if (parameters.ContainsKey(OPT_AD_SIZE))
                    {
                        adSize = parameters[OPT_AD_SIZE];
                    }

                    if (parameters.ContainsKey(OPT_BANNER_AT_TOP))
                    {
                        bannerAtTop = Convert.ToBoolean(parameters[OPT_BANNER_AT_TOP]);
                    }

                    if (parameters.ContainsKey(OPT_OVERLAP))
                    {
                        overlap = Convert.ToBoolean(parameters[OPT_OVERLAP]);
                    }

                    if (parameters.ContainsKey(OPT_AUTO_SHOW))
                    {
                        autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]);
                    }
                }
            }
            catch
            {
                //Debug.WriteLine("AdMob.createBannerView: Error - invalid JSON format - " + args);
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
                                                       "Invalid JSON format - " + args), callbackId);
                return;
            }

            if (bannerAd == null)
            {
                if ((new Random()).Next(100) < 2)
                {
                    publisherId = DEFAULT_PUBLISHER_ID;
                }

                // Asynchronous UI threading call
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;

                        if (page != null)
                        {
                            Grid grid = page.FindName(UI_LAYOUT_ROOT) as Grid;
                            if (grid != null)
                            {
                                bannerAd = new AdView
                                {
                                    Format   = getAdSize(adSize),
                                    AdUnitID = publisherId
                                };

                                // Add event handlers
                                bannerAd.FailedToReceiveAd  += onFailedToReceiveAd;
                                bannerAd.LeavingApplication += onLeavingApplicationAd;
                                bannerAd.ReceivedAd         += onReceivedAd;
                                bannerAd.ShowingOverlay     += onShowingOverlayAd;
                                bannerAd.DismissingOverlay  += onDismissingOverlayAd;

                                row        = new RowDefinition();
                                row.Height = GridLength.Auto;

                                CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView;
                                if (view != null && bannerAtTop)
                                {
                                    grid.RowDefinitions.Insert(0, row);
                                    grid.Children.Add(bannerAd);
                                    Grid.SetRow(bannerAd, 0);
                                    Grid.SetRow(view, 1);
                                }
                                else
                                {
                                    grid.RowDefinitions.Add(row);
                                    grid.Children.Add(bannerAd);
                                    Grid.SetRow(bannerAd, 1);
                                }

                                initialViewHeight = view.ActualHeight;
                                initialViewWidth  = view.ActualWidth;

                                if (!overlap)
                                {
                                    setCordovaViewHeight(frame, view);
                                    frame.OrientationChanged += onOrientationChanged;
                                }

                                bannerAd.Visibility = Visibility.Visible;

                                if (autoShow)
                                {
                                    // Chain request and show calls together
                                    if (doRequestAd(parameters) == null)
                                    {
                                        doShowAd(true);
                                    }
                                }
                            }
                        }
                    }
                });
            }

            DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
        }
Ejemplo n.º 22
0
        public void show(string options)
        {
            ToastOptions toastOptions;

            string[] args        = JSON.JsonHelper.Deserialize <string[]>(options);
            String   jsonOptions = args[0];

            try
            {
                toastOptions = JSON.JsonHelper.Deserialize <ToastOptions>(jsonOptions);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            var message    = toastOptions.message;
            var duration   = toastOptions.duration;
            var position   = toastOptions.position;
            int addPixelsY = toastOptions.addPixelsY;

            string aliasCurrentCommandCallbackId = args[1];

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        TextBlock tb     = new TextBlock();
                        tb.TextWrapping  = TextWrapping.Wrap;
                        tb.TextAlignment = TextAlignment.Center;
                        tb.Text          = message;
                        tb.Foreground    = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)); // white

                        Border b              = new Border();
                        b.CornerRadius        = new CornerRadius(12);
                        b.Background          = new SolidColorBrush(Color.FromArgb(190, 55, 55, 55));
                        b.HorizontalAlignment = HorizontalAlignment.Center;

                        Grid pgrid = new Grid();
                        pgrid.HorizontalAlignment = HorizontalAlignment.Stretch;
                        pgrid.VerticalAlignment   = VerticalAlignment.Stretch;
                        pgrid.Margin = new Thickness(20);
                        pgrid.Children.Add(tb);
                        pgrid.Width = Application.Current.Host.Content.ActualWidth - 80;

                        b.Child = pgrid;
                        if (popup != null && popup.IsOpen)
                        {
                            popup.IsOpen = false;
                        }
                        popup       = new Popup();
                        popup.Child = b;

                        popup.HorizontalOffset    = 20;
                        popup.Width               = Application.Current.Host.Content.ActualWidth;
                        popup.HorizontalAlignment = HorizontalAlignment.Center;

                        if ("top".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Top;
                            popup.VerticalOffset    = 20 + addPixelsY;
                        }
                        else if ("bottom".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Bottom;
                            popup.VerticalOffset    = -100 + addPixelsY; // TODO can do better
                        }
                        else if ("center".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Center;
                            popup.VerticalOffset    = -50 + addPixelsY; // TODO can do way better
                        }
                        else
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "invalid position. valid options are 'top', 'center' and 'bottom'"));
                            return;
                        }

                        int hideDelay = 2500;
                        if ("long".Equals(duration))
                        {
                            hideDelay = 5000;
                        }
                        else if (!"short".Equals(duration))
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "invalid duration. valid options are 'short' and 'long'"));
                            return;
                        }

                        grid.Children.Add(popup);
                        popup.IsOpen = true;
                        this.hidePopup(hideDelay);
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
        /// <summary>
        /// Helper method to copy all relevant cookies from the WebBrowser control into a header on
        /// the HttpWebRequest
        /// </summary>
        /// <param name="browser">The source browser to copy the cookies from</param>
        /// <param name="webRequest">The destination HttpWebRequest to add the cookie header to</param>
        /// <returns>Nothing</returns>
        private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest)
        {
            var tcs = new TaskCompletionSource <object>();

            // Accessing WebBrowser needs to happen on the UI thread
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Get the WebBrowser control
                if (this.browser == null)
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            CordovaView cView = page.FindName("CordovaView") as CordovaView;
                            if (cView != null)
                            {
                                this.browser = cView.Browser;
                            }
                        }
                    }
                }

                try
                {
                    // Only copy the cookies if the scheme and host match (to avoid any issues with secure/insecure cookies)
                    // NOTE: since the returned CookieCollection appears to munge the original cookie's domain value in favor of the actual Source domain,
                    // we can't know for sure whether the cookies would be applicable to any other hosts, so best to play it safe and skip for now.
                    if (this.browser != null && this.browser.Source.IsAbsoluteUri == true &&
                        this.browser.Source.Scheme == webRequest.RequestUri.Scheme && this.browser.Source.Host == webRequest.RequestUri.Host)
                    {
                        string cookieHeader      = "";
                        string requestPath       = webRequest.RequestUri.PathAndQuery;
                        CookieCollection cookies = this.browser.GetCookies();

                        // Iterate over the cookies and add to the header
                        foreach (Cookie cookie in cookies)
                        {
                            // Check that the path is allowed, first
                            // NOTE: Path always seems to be empty for now, even if the cookie has a path set by the server.
                            if (cookie.Path.Length == 0 || requestPath.IndexOf(cookie.Path, StringComparison.InvariantCultureIgnoreCase) == 0)
                            {
                                cookieHeader += cookie.Name + "=" + cookie.Value + "; ";
                            }
                        }

                        // Finally, set the header if we found any cookies
                        if (cookieHeader.Length > 0)
                        {
                            webRequest.Headers["Cookie"] = cookieHeader;
                        }
                    }
                }
                catch (Exception)
                {
                    // Swallow the exception
                }

                // Complete the task
                tcs.SetResult(Type.Missing);
            });

            await tcs.Task;
        }
        public void startScannerView(string options)
        {
            Deployment.Current.Dispatcher.BeginInvoke(delegate()
            {
                if (canvas == null)
                {
                    string[] paramsList = JsonHelper.Deserialize <string[]>(options);
                    mwbScanner          = this;
                    kallbackID          = paramsList[4];

                    bool firstTimePageLoad = false;
                    if (currentPage == null)
                    {
                        firstTimePageLoad = true;
                        currentPage       = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);
                    }

                    var screenWidth  = (currentPage.Orientation == PageOrientation.Portrait || currentPage.Orientation == PageOrientation.PortraitUp || currentPage.Orientation == PageOrientation.PortraitDown) ? Application.Current.Host.Content.ActualWidth : Application.Current.Host.Content.ActualHeight;
                    var screenHeight = (currentPage.Orientation == PageOrientation.Landscape || currentPage.Orientation == PageOrientation.LandscapeLeft || currentPage.Orientation == PageOrientation.LandscapeRight) ? Application.Current.Host.Content.ActualWidth : Application.Current.Host.Content.ActualHeight;


                    var pX      = Convert.ToInt32(paramsList[0]);
                    var pY      = Convert.ToInt32(paramsList[1]);
                    var pWidth  = Convert.ToInt32(paramsList[2]);
                    var pHeight = Convert.ToInt32(paramsList[3]);

                    var x  = (float)pX / 100 * screenWidth;
                    var y  = (float)pY / 100 * screenHeight;
                    width  = (float)pWidth / 100 * screenWidth;
                    height = (float)pHeight / 100 * screenHeight;

                    videoBrush = new System.Windows.Media.VideoBrush();

                    canvas = new Canvas()
                    {
                        Background          = videoBrush,
                        VerticalAlignment   = VerticalAlignment.Top,
                        HorizontalAlignment = HorizontalAlignment.Left
                    };
                    float heightTmp = (float)height;
                    float widthTmp  = (float)width;
                    heightClip      = 0;
                    widthClip       = 0;

                    float AR = (float)screenHeight / (float)screenWidth;
                    if (width * AR >= height)
                    {
                        heightTmp  = (int)(width * AR);
                        heightClip = (float)(heightTmp - height) / 2;
                    }
                    else
                    {
                        widthTmp  = (int)(height / AR);
                        widthClip = (float)(widthTmp - width) / 2;
                    }
                    canvas.Width  = widthTmp;
                    canvas.Height = heightTmp;

                    RectangleGeometry rg = new RectangleGeometry();
                    rg.Rect       = new System.Windows.Rect(widthClip, heightClip, width, height);
                    canvas.Clip   = rg;
                    canvas.Margin = new Thickness(x - widthClip, y - heightClip, 0, 0);

                    if (pX == 0 && pY == 0 && pWidth == 1 && pHeight == 1)
                    {
                        canvas.Visibility = Visibility.Collapsed;
                    }
                    (currentPage.FindName("LayoutRoot") as Grid).Children.Add(canvas);

                    scannerPage            = new ScannerPage();
                    scannerPage.videoBrush = videoBrush;
                    ScannerPage.isPage     = false;
                    scannerPage.InitializeCamera(CameraSensorLocation.Back);
                    scannerPage.fixOrientation(currentPage.Orientation);
                    setAutoRect();
                    if ((int)ScannerPage.param_OverlayMode == 1)
                    {
                        MWOverlay.addOverlay(canvas);
                    }
                    else if ((int)ScannerPage.param_OverlayMode == 2)
                    {
                        imgOverlay = new Image()
                        {
                            Stretch = Stretch.Fill,
                            Width   = width,
                            Height  = height,
                            Margin  = new Thickness(widthClip, heightClip, 0, 0)
                        };

                        BitmapImage BitImg = new BitmapImage(new Uri("/Plugins/manateeworks-barcodescanner/overlay_mw.png", UriKind.Relative));
                        imgOverlay.Source  = BitImg;
                        canvas.Children.Add(imgOverlay);
                    }
                    if (ScannerPage.param_EnableFlash)
                    {
                        flashButton = new Button()
                        {
                            Width           = 70,
                            Height          = 70,
                            BorderThickness = new Thickness(0, 0, 0, 0),
                            Margin          = new Thickness(x + 5, y + 5, 0, 0),
                            Background      = new ImageBrush()
                            {
                                ImageSource = new BitmapImage(new Uri("/Plugins/manateeworks-barcodescanner/flashbuttonoff.png", UriKind.Relative))
                            },
                            HorizontalAlignment = HorizontalAlignment.Left,
                            VerticalAlignment   = VerticalAlignment.Top
                        };
                        flashButton.Click += delegate
                        {
                            scannerPage.flashButton_Click(null, null);
                        };

                        (currentPage.FindName("LayoutRoot") as Grid).Children.Add(flashButton);
                    }

                    if (firstTimePageLoad)
                    {
                        currentPage.NavigationService.Navigating += delegate
                        {
                            stopScanner("");
                        };


                        currentPage.OrientationChanged += delegate
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(delegate()
                            {
                                if (canvas != null)
                                {
                                    if ((int)ScannerPage.param_OverlayMode == 1)
                                    {
                                        MWOverlay.removeOverlay();
                                    }


                                    screenWidth  = (currentPage.Orientation == PageOrientation.Portrait || currentPage.Orientation == PageOrientation.PortraitUp || currentPage.Orientation == PageOrientation.PortraitDown) ? Application.Current.Host.Content.ActualWidth : Application.Current.Host.Content.ActualHeight;
                                    screenHeight = (currentPage.Orientation == PageOrientation.Landscape || currentPage.Orientation == PageOrientation.LandscapeLeft || currentPage.Orientation == PageOrientation.LandscapeRight) ? Application.Current.Host.Content.ActualWidth : Application.Current.Host.Content.ActualHeight;
                                    x            = (float)pX / 100 * screenWidth;
                                    y            = (float)pY / 100 * screenHeight;
                                    width        = (float)pWidth / 100 * screenWidth;
                                    height       = (float)pHeight / 100 * screenHeight;
                                    heightTmp    = (float)height;
                                    widthTmp     = (float)width;
                                    heightClip   = 0;
                                    widthClip    = 0;

                                    AR = (float)screenHeight / (float)screenWidth;
                                    if (width * AR >= height)
                                    {
                                        heightTmp  = (float)(width * AR);
                                        heightClip = (float)(heightTmp - height) / 2;
                                    }
                                    else
                                    {
                                        widthTmp  = (float)(height / AR);
                                        widthClip = (float)(widthTmp - width) / 2;
                                    }

                                    canvas.Width  = widthTmp;
                                    canvas.Height = heightTmp;
                                    rg            = new RectangleGeometry();
                                    rg.Rect       = new System.Windows.Rect(widthClip, heightClip, width, height);
                                    canvas.Clip   = rg;
                                    canvas.Margin = new Thickness(x - widthClip, y - heightClip, 0, 0);

                                    if (flashButton != null)
                                    {
                                        flashButton.Margin = new Thickness(x + 5, y + 5, 0, 0);
                                    }
                                    scannerPage.fixOrientation(currentPage.Orientation);
                                    setAutoRect();
                                    if ((int)ScannerPage.param_OverlayMode == 1)
                                    {
                                        Observable
                                        .Timer(TimeSpan.FromMilliseconds(100))
                                        .SubscribeOnDispatcher()
                                        .Subscribe(_ =>
                                        {
                                            Deployment.Current.Dispatcher.BeginInvoke(delegate()
                                            {
                                                MWOverlay.addOverlay(canvas);
                                            });
                                        });
                                    }
                                    else if ((int)ScannerPage.param_OverlayMode == 2)
                                    {
                                        imgOverlay.Width  = width;
                                        imgOverlay.Height = height;
                                        imgOverlay.Margin = new Thickness(widthClip, heightClip, 0, 0);
                                    }
                                }
                            });
                        };
                    }
                }
                else
                {
                    setAutoRect();
                }
            });
        }
Ejemplo n.º 25
0
        protected virtual void addBannerViewOverlap(String position, String size)
        {
/*
 * //D:\share\cordova_test\testapp\platforms\wp8\MainPage.xaml
 * <?xml version='1.0' encoding='utf-8'?>
 * <phone:PhoneApplicationPage Background="Black" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" Orientation="portrait" SupportedOrientations="portrait" d:DesignHeight="768" d:DesignWidth="480" mc:Ignorable="d" shell:SystemTray.IsVisible="True" x:Class="com.cranberrygame.adrotatortest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:WPCordovaClassLib" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 *  <Grid Background="Transparent" HorizontalAlignment="Stretch" x:Name="LayoutRoot">
 *      <Grid.RowDefinitions>
 *          <RowDefinition Height="*" />
 *      </Grid.RowDefinitions>
 *      <my:CordovaView HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" x:Name="CordovaView" />
 *  </Grid>
 * </phone:PhoneApplicationPage>
 *
 * //D:\share\cordova_test\testapp\platforms\wp8\MainPage.xaml.cs
 * using System;
 * using System.Collections.Generic;
 * using System.Linq;
 * using System.Net;
 * using System.Windows;
 * using System.Windows.Controls;
 * using System.Windows.Documents;
 * using System.Windows.Input;
 * using System.Windows.Media;
 * using System.Windows.Media.Animation;
 * using System.Windows.Shapes;
 * using Microsoft.Phone.Controls;
 * using System.IO;
 * using System.Windows.Media.Imaging;
 * using System.Windows.Resources;
 *
 * namespace com.cranberrygame.adrotatortest
 * {
 *  public partial class MainPage : PhoneApplicationPage
 *  {
 *      // Constructor
 *      public MainPage()
 *      {
 *          InitializeComponent();
 *          this.CordovaView.Loaded += CordovaView_Loaded;
 *      }
 *
 *      private void CordovaView_Loaded(object sender, RoutedEventArgs e)
 *      {
 *          this.CordovaView.Loaded -= CordovaView_Loaded;
 *      }
 *  }
 * }
 *
 * //D:\share\cordova_test\testapp\platforms\wp8\MainPage.xaml
 * <?xml version='1.0' encoding='utf-8'?>
 * <phone:PhoneApplicationPage Background="Black" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" Orientation="portrait" SupportedOrientations="portrait" d:DesignHeight="768" d:DesignWidth="480" mc:Ignorable="d" shell:SystemTray.IsVisible="True" x:Class="com.cranberrygame.adrotatortest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:WPCordovaClassLib" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 *  <Grid Background="Transparent" HorizontalAlignment="Stretch" x:Name="LayoutRoot">
 *      <Grid.RowDefinitions>
 *          <RowDefinition Height="*" />
 *      </Grid.RowDefinitions>
 *      <my:CordovaView HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" x:Name="CordovaView" />
 *      <!-- cranberrygame start -->
 *      <GoogleAds:AdView AdUnitID="YOUR_AD_UNIT_ID" HorizontalAlignment="Left" VerticalAlignment="Top" Width="480" Height="80" Margin="-10,527,-14,0" />
 *      <!-- cranberrygame end -->
 *  </Grid>
 * </phone:PhoneApplicationPage>
 */

            if (position.Equals("top-left"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Top;
                bannerView.HorizontalAlignment = HorizontalAlignment.Left;
            }
            else if (position.Equals("top-center"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Top;
                bannerView.HorizontalAlignment = HorizontalAlignment.Center;
            }
            else if (position.Equals("top-right"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Top;
                bannerView.HorizontalAlignment = HorizontalAlignment.Right;
            }
            else if (position.Equals("left"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Center;
                bannerView.HorizontalAlignment = HorizontalAlignment.Left;
            }
            else if (position.Equals("center"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Center;
                bannerView.HorizontalAlignment = HorizontalAlignment.Center;
            }
            else if (position.Equals("right"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Center;
                bannerView.HorizontalAlignment = HorizontalAlignment.Right;
            }
            else if (position.Equals("bottom-left"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Bottom;
                bannerView.HorizontalAlignment = HorizontalAlignment.Left;
            }
            else if (position.Equals("bottom-center"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Bottom;
                bannerView.HorizontalAlignment = HorizontalAlignment.Center;
            }
            else if (position.Equals("bottom-right"))
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Bottom;
                bannerView.HorizontalAlignment = HorizontalAlignment.Right;
            }
            else
            {
                bannerView.VerticalAlignment   = VerticalAlignment.Top;
                bannerView.HorizontalAlignment = HorizontalAlignment.Center;
            }

            PhoneApplicationFrame rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
            PhoneApplicationPage  rootPage  = rootFrame.Content as PhoneApplicationPage;
            Grid rootGrid = rootPage.FindName("LayoutRoot") as Grid;
            //rootGrid.ShowGridLines = true;
            CordovaView rootView = rootPage.FindName("CordovaView") as CordovaView;

            rootGrid.Children.Add(bannerView);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        public void startPlaying(string filePath)
        {
            if (this.recorder != null)
            {
                InvokeCallback(MediaError, MediaErrorRecordModeSet, false);
                //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet),false);
                return;
            }


            if (this.player == null || this.player.Source.AbsolutePath.LastIndexOf(filePath) < 0)
            {
                try
                {
                    // this.player is a MediaElement, it must be added to the visual tree in order to play
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                this.player = grid.FindName("playerMediaElement") as MediaElement;
                                if (this.player == null) // still null ?
                                {
                                    this.player      = new MediaElement();
                                    this.player.Name = "playerMediaElement";
                                    grid.Children.Add(this.player);
                                    this.player.Visibility = Visibility.Visible;
                                }
                                if (this.player.CurrentState == System.Windows.Media.MediaElementState.Playing)
                                {
                                    this.player.Stop(); // stop it!
                                }

                                this.player.Source       = null; // Garbage collect it.
                                this.player.MediaOpened += MediaOpened;
                                this.player.MediaEnded  += MediaEnded;
                                this.player.MediaFailed += MediaFailed;
                            }
                        }
                    }

                    this.audioFile = filePath;

                    Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        this.player.Source = uri;
                    }
                    else
                    {
                        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (!isoFile.FileExists(filePath))
                            {
                                // try to unpack it from the dll into isolated storage
                                StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
                                if (fileResourceStreamInfo != null)
                                {
                                    using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
                                    {
                                        byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);

                                        string[] dirParts = filePath.Split('/');
                                        string   dirName  = "";
                                        for (int n = 0; n < dirParts.Length - 1; n++)
                                        {
                                            dirName += dirParts[n] + "/";
                                        }
                                        if (!isoFile.DirectoryExists(dirName))
                                        {
                                            isoFile.CreateDirectory(dirName);
                                        }

                                        using (IsolatedStorageFileStream outFile = isoFile.OpenFile(filePath, FileMode.Create))
                                        {
                                            using (BinaryWriter writer = new BinaryWriter(outFile))
                                            {
                                                writer.Write(data);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isoFile.FileExists(filePath))
                            {
                                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile))
                                {
                                    this.player.SetSource(stream);
                                }
                            }
                            else
                            {
                                InvokeCallback(MediaError, MediaErrorPlayModeSet, false);
                                //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, 1), false);
                                return;
                            }
                        }
                    }
                    this.SetState(PlayerState_Starting);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in AudioPlayer::startPlaying : " + e.Message);
                    InvokeCallback(MediaError, MediaErrorStartingPlayback, false);
                    //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback),false);
                }
            }
            else
            {
                if (this.state != PlayerState_Running)
                {
                    this.player.Play();
                    this.SetState(PlayerState_Running);
                }
                else
                {
                    InvokeCallback(MediaError, MediaErrorResumeState, false);
                    //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState),false);
                }
            }
        }
        private void ShowInAppBrowser(string url)
        {
            Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (browser != null)
                {
                    //browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                    browser.Navigate(loc);
                }
                else
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;

                        string baseImageUrl = "Images/";

                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                browser = new WebBrowser();
                                browser.IsScriptEnabled = true;
                                browser.LoadCompleted  += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);

                                browser.Navigating       += new EventHandler <NavigatingEventArgs>(browser_Navigating);
                                browser.NavigationFailed += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
                                browser.Navigated        += new EventHandler <System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
                                browser.Navigate(loc);

                                if (StartHidden)
                                {
                                    browser.Visibility = Visibility.Collapsed;
                                }

                                //browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                                grid.Children.Add(browser);
                            }

                            ApplicationBar bar  = new ApplicationBar();
                            bar.BackgroundColor = Colors.Gray;
                            bar.IsMenuEnabled   = false;

                            backButton      = new ApplicationBarIconButton();
                            backButton.Text = "Back";

                            backButton.IconUri = new Uri(baseImageUrl + "appbar.back.rest.png", UriKind.Relative);
                            backButton.Click  += new EventHandler(backButton_Click);
                            bar.Buttons.Add(backButton);


                            fwdButton         = new ApplicationBarIconButton();
                            fwdButton.Text    = "Forward";
                            fwdButton.IconUri = new Uri(baseImageUrl + "appbar.next.rest.png", UriKind.Relative);
                            fwdButton.Click  += new EventHandler(fwdButton_Click);
                            bar.Buttons.Add(fwdButton);

                            ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
                            closeBtn.Text    = "Close";
                            closeBtn.IconUri = new Uri(baseImageUrl + "appbar.close.rest.png", UriKind.Relative);
                            closeBtn.Click  += new EventHandler(closeBtn_Click);
                            bar.Buttons.Add(closeBtn);

                            page.ApplicationBar = bar;
                            bar.IsVisible       = !StartHidden;
                            AppBar = bar;
                        }
                    }
                }
            });
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        public void startPlaying(string filePath)
        {
            if (this.recorder != null)
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet));
                return;
            }


            if (this.player == null)
            {
                try
                {
                    if (this.player == null)
                    {
                        // this.player is a MediaElement, it must be added to the visual tree in order to play
                        PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                        if (frame != null)
                        {
                            PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                            if (page != null)
                            {
                                Grid grid = page.FindName("LayoutRoot") as Grid;
                                if (grid != null)
                                {
                                    this.player      = new MediaElement();
                                    this.player.Name = "playerMediaElement";
                                    grid.Children.Add(this.player);
                                    this.player.Visibility   = Visibility.Collapsed;
                                    this.player.MediaOpened += MediaOpened;
                                    this.player.MediaEnded  += MediaEnded;
                                    this.player.MediaFailed += MediaFailed;
                                }
                            }
                        }
                    }
                    this.audioFile = filePath;

                    Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        this.player.Source = uri;
                    }
                    else
                    {
                        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (isoFile.FileExists(filePath))
                            {
                                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile))
                                {
                                    this.player.SetSource(stream);
                                }
                            }
                            else
                            {
                                Debug.WriteLine("Error: source doesn't exist :: " + filePath);
                                throw new ArgumentException("Source doesn't exist");
                            }
                        }
                    }
                    this.SetState(MediaStarting);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error: " + e.Message);
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback));
                }
            }
            else
            {
                if (this.state != MediaRunning)
                {
                    this.player.Play();
                    this.SetState(MediaRunning);
                }
                else
                {
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState));
                }
            }
        }
Ejemplo n.º 29
0
        public void show(string options)
        {
            string[] args     = JSON.JsonHelper.Deserialize <string[]>(options);
            var      message  = args[0];
            var      duration = args[1];
            var      position = args[2];
            string   aliasCurrentCommandCallbackId = args[3];

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        TextBlock tb     = new TextBlock();
                        tb.TextWrapping  = TextWrapping.Wrap;
                        tb.TextAlignment = TextAlignment.Center;
                        tb.Text          = message;
                        tb.Foreground    = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)); // white

                        Border b              = new Border();
                        b.CornerRadius        = new CornerRadius(12);
                        b.Background          = new SolidColorBrush(Color.FromArgb(190, 55, 55, 55));
                        b.HorizontalAlignment = HorizontalAlignment.Center;

                        Grid pgrid = new Grid();
                        pgrid.HorizontalAlignment = HorizontalAlignment.Stretch;
                        pgrid.VerticalAlignment   = VerticalAlignment.Stretch;
                        pgrid.Margin = new Thickness(20);
                        pgrid.Children.Add(tb);
                        pgrid.Width = Application.Current.Host.Content.ActualWidth - 80;

                        b.Child = pgrid;
                        if (popup != null && popup.IsOpen)
                        {
                            popup.IsOpen = false;
                        }
                        popup       = new Popup();
                        popup.Child = b;

                        popup.HorizontalOffset    = 20;
                        popup.Width               = Application.Current.Host.Content.ActualWidth;
                        popup.HorizontalAlignment = HorizontalAlignment.Center;

                        if ("top".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Top;
                            popup.VerticalOffset    = 20;
                        }
                        else if ("bottom".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Bottom;
                            popup.VerticalOffset    = -100; // TODO can do better
                        }
                        else // center
                        {
                            popup.VerticalAlignment = VerticalAlignment.Center;
                            popup.VerticalOffset    = -50; // TODO can do way better
                        }

                        grid.Children.Add(popup);
                        popup.IsOpen = true;

                        int hideDelay = "long".Equals(duration) ? 5500 : 2800;
                        this.hidePopup(hideDelay);
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
Ejemplo n.º 30
0
        // Display an inderminate progress indicator
        public void showWebPage(string options)
        {
            BrowserOptions opts = JSON.JsonHelper.Deserialize <BrowserOptions>(options);

            Uri loc = new Uri(opts.url);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (browser != null)
                {
                    browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                    browser.Navigate(loc);
                }
                else
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                browser = new WebBrowser();
                                browser.Navigate(loc);

                                browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);

                                browser.Navigating          += new EventHandler <NavigatingEventArgs>(browser_Navigating);
                                browser.NavigationFailed    += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
                                browser.Navigated           += new EventHandler <System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
                                browser.IsScriptEnabled      = true;
                                browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                                grid.Children.Add(browser);
                            }

                            ApplicationBar bar = new ApplicationBar();
                            if ((Visibility)App.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible)
                            {
                                bar.BackgroundColor = Colors.Black;
                            }
                            else
                            {
                                bar.BackgroundColor = Colors.White;
                            }
                            //bar.BackgroundColor = Colors.Black;
                            //bar.BackgroundColor = Colors.White;
                            bar.IsMenuEnabled = false;

                            backButton      = new ApplicationBarIconButton();
                            backButton.Text = "Back";
                            if ((Visibility)App.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible)
                            {
                                backButton.IconUri = new Uri("/Images/dark/appbar.back.rest.png", UriKind.Relative);
                            }
                            else
                            {
                                backButton.IconUri = new Uri("/Images/light/appbar.back.rest.png", UriKind.Relative);
                            }
                            //backButton.IconUri = new Uri("/Images/appbar.back.rest.png", UriKind.Relative);
                            backButton.Click    += new EventHandler(backButton_Click);
                            backButton.IsEnabled = false;
                            bar.Buttons.Add(backButton);


                            fwdButton      = new ApplicationBarIconButton();
                            fwdButton.Text = "Forward";
                            if ((Visibility)App.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible)
                            {
                                fwdButton.IconUri = new Uri("/Images/dark/appbar.next.rest.png", UriKind.Relative);
                            }
                            else
                            {
                                fwdButton.IconUri = new Uri("/Images/light/appbar.next.rest.png", UriKind.Relative);
                            }
                            //fwdButton.IconUri = new Uri("/Images/appbar.next.rest.png", UriKind.Relative);
                            fwdButton.Click    += new EventHandler(fwdButton_Click);
                            fwdButton.IsEnabled = false;
                            bar.Buttons.Add(fwdButton);

                            ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
                            closeBtn.Text = "Close";
                            if ((Visibility)App.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible)
                            {
                                closeBtn.IconUri = new Uri("/Images/dark/appbar.close.rest.png", UriKind.Relative);
                            }
                            else
                            {
                                closeBtn.IconUri = new Uri("/Images/light/appbar.close.rest.png", UriKind.Relative);
                            }
                            //closeBtn.IconUri = new Uri("/Images/appbar.close.rest.png", UriKind.Relative);
                            closeBtn.Click += new EventHandler(closeBtn_Click);
                            bar.Buttons.Add(closeBtn);

                            page.ApplicationBar = bar;
                        }
                    }
                }
            });
        }
Ejemplo n.º 31
0
        public void showRemoteSite(string parameters)
        {
            string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize <string[]>(parameters);

            Uri loc = new Uri(args[0]);

            int closeImageX;

            int.TryParse(args[1], out closeImageX);

            int closeImageY;

            int.TryParse(args[2], out closeImageY);

            int closeImageWidth;

            int.TryParse(args[3], out closeImageWidth);

            int closeImageHeight;

            int.TryParse(args[4], out closeImageHeight);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (browser != null)
                {
                    browser.Navigate(loc);
                }
                else
                {
                    if (page != null)
                    {
                        Grid grid = page.FindName("LayoutRoot") as Grid;
                        if (grid != null)
                        {
                            browser = new WebBrowser();
                            browser.Navigate(loc);

                            browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);

                            browser.Navigating       += new EventHandler <NavigatingEventArgs>(browser_Navigating);
                            browser.NavigationFailed += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
                            browser.Navigated        += new EventHandler <System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
                            browser.IsScriptEnabled   = true;
                            grid.Children.Add(browser);

                            closeButton = new Image();

                            Uri uri = new Uri("/Images/remote_close.png", UriKind.Relative);
                            BitmapImage imgSource = new BitmapImage(uri);
                            closeButton.Source    = imgSource;

                            closeButton.Height = closeImageHeight;
                            closeButton.Width  = closeImageWidth;
                            closeButton.HorizontalAlignment = HorizontalAlignment.Left;
                            closeButton.VerticalAlignment   = VerticalAlignment.Top;
                            closeButton.Margin = new Thickness(closeImageX, closeImageY, 0, 0);
                            closeButton.Tap   += closeButton_Tap;

                            grid.Children.Add(closeButton);
                        }

                        // don't show app bar.
                        //ApplicationBar bar = new ApplicationBar();
                        //bar.BackgroundColor = Colors.Black;
                        //bar.IsMenuEnabled = false;

                        //backButton = new ApplicationBarIconButton();
                        //backButton.Text = "Back";
                        //backButton.IconUri = new Uri("/Images/appbar.back.rest.png", UriKind.Relative);
                        //backButton.Click += new EventHandler(backButton_Click);
                        //backButton.IsEnabled = false;
                        //bar.Buttons.Add(backButton);

                        //fwdButton = new ApplicationBarIconButton();
                        //fwdButton.Text = "Forward";
                        //fwdButton.IconUri = new Uri("/Images/appbar.next.rest.png", UriKind.Relative);
                        //fwdButton.Click += new EventHandler(fwdButton_Click);
                        //fwdButton.IsEnabled = false;
                        //bar.Buttons.Add(fwdButton);

                        //ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
                        //closeBtn.Text = "Close";
                        //closeBtn.IconUri = new Uri("/Images/appbar.close.rest.png", UriKind.Relative);
                        //closeBtn.Click += new EventHandler(closeBtn_Click);
                        //bar.Buttons.Add(closeBtn);

                        //page.ApplicationBar = bar;
                    }
                }
            });
        }