Example #1
0
        public Trash(ProviderTemplate template, ImageSource source)
        {
            InitializeComponent();

            this.template = (ProviderTemplate) template.Clone();
            TrashImage.Source = source;
        }
Example #2
0
        /// <summary>
        /// Change cette image avec une transition en fondu
        /// </summary>
        /// <param name="image">L'image à modifier</param>
        /// <param name="source">La source de la prochaine image</param>
        /// <param name="beginTime">Le délai en seconde après lequel la transition commence</param>
        /// <param name="fadeTime">Le durée de la transition</param>
        public static void ChangeSource(this Image image, ImageSource source, double beginTime, double fadeTime)
        {
            var fadeInAnimation = new DoubleAnimation
            {
                To = 1,
                BeginTime = TimeSpan.FromSeconds(fadeTime),
                Duration = TimeSpan.FromSeconds(beginTime)
            };

            if (image.Source != null)
            {
                var fadeOutAnimation = new DoubleAnimation
                {
                    To = 0,
                    BeginTime = TimeSpan.FromSeconds(0.05),
                    Duration = TimeSpan.FromSeconds(fadeTime)
                };

                fadeOutAnimation.Completed += (o, e) =>
                {
                    image.Source = source;
                    image.BeginAnimation(Image.OpacityProperty, fadeInAnimation);
                };

                image.BeginAnimation(Image.OpacityProperty, fadeOutAnimation);
            }
            else
            {
                image.Opacity = 0d;
                image.Source = source;
                image.BeginAnimation(Image.OpacityProperty, fadeInAnimation);
            }
        }
 void MainWindow_NewDataAvailable(ImageSource data)
 {
     this.videoControl.Dispatcher.Invoke(new Action(() =>
     {
         this.videoControl.ShowImageSource(data);
     }));
 }
 /// <summary>
 /// Defaults to the off state and the image from displayedImage
 /// </summary>
 public ImageToggle(ImageSource otherImage, ref Image displayedImage)
 {
     _img1 = otherImage;
     _img2 = displayedImage.Source;
     _displayedImage = displayedImage;
     Toggled = false;
 }
Example #5
0
        private static MemoryStream SaveDrawingImage(ImageSource drawingImage)
        {
            var image = new Image
            {
                Source = drawingImage
            };

            image.Arrange(new Rect(0, 0, drawingImage.Width, drawingImage.Height));

            var settings = Settings.Default;

            var renderTargetBitmap = new RenderTargetBitmap((int)drawingImage.Width, (int)drawingImage.Height, settings.ImageDPI, settings.ImageDPI, PixelFormats.Default);
            renderTargetBitmap.Render(image);

            Settings.Default.Save();

            var encoder = new JpegBitmapEncoder
            {
                QualityLevel = settings.JpgQuality
            };

            encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));

            var memoryStream = new MemoryStream();

            encoder.Save(memoryStream);

            return memoryStream;
        }
Example #6
0
 public ImagePackage(IImageDecoder decoder, ImageSource source, double width, double height)
 {
     this.Decoder = decoder;
     this.ImageSource = source;
     this.PixelWidth = width;
     this.PixelHeight = height;
 }
Example #7
0
        private static ImageBase GetGeneratorByType(ImageSource imageSource)
        {
            switch (imageSource)
            {
                case ImageSource.FpoImg:
                    return new FpoImg();

                case ImageSource.PlaceCage:
                    return new PlaceCage();

                case ImageSource.FillMurray:
                    return new FillMurray();

                case ImageSource.NiceNiceJpg:
                    return new NiceNiceJpg();

                case ImageSource.StevenSeGallery:
                    return new StevenSeGallery();

                case ImageSource.BaconMockup:
                    return new BaconMockup();

                //case ImageSource.Normal:
                //case ImageSource.PlaceholdIt:
                default:
                    return new PlaceholdIt();
            }            
        }
        /// <summary>
        /// constructeur
        /// </summary>
        public CreateUserViewModel(Page lkView)
        {
            _linkedView = lkView;

            _createCommand = new RelayCommand(param => CreateAccount(), param => IsValidForm());
            _imageCommand = new RelayCommand(param => SelectImage(), param => true);

            _name = "";
            _firstname = "";
            _login = "";
            _password = "";
            _confirmPassword = "";

            _availableRoleList = new List<string>();
            _availableRoleList.Add("Chirurgien");
            _availableRoleList.Add("Infirmière");
            _availableRoleList.Add("Medecin");
            _availableRoleList.Add("Radiologue");

            _role = "Chirurgien";

            _iscreatingaccount = false;
            _imagepath = "";
            _imagesrc = null;
            _waitingMessage = "";
        }
Example #9
0
        public Home()
        {
            try
            {
                this.ImageURL = new Uri(Path.Combine(Environment.CurrentDirectory, "Sample.jpg"), UriKind.Absolute).AbsolutePath;

                if (!String.IsNullOrWhiteSpace(this.ImageURL))
                {
                    this.mainPhoto = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(ImageURL);
                    this.mainPhotoIS = ToBitmapImage(mainPhoto);
                    this.LocalImagePath = ImageURL;

                    this.dpiX = 84;
                    this.dpiY = 84;

                    UpdateHistograms(null);
                    UpdateChannelPreviews(null);
                }
            }
            catch
            {
                // do nothing, user must enter a URL manualy
            }

            this.DataContext = this;

            InitializeComponent();
        }
Example #10
0
        /// <summary>
        /// Cashes original ImageSource, creates and caches greyscale ImageSource and greyscale opacity mask
        /// </summary>
        private void SetSources()
        {
            _sourceC = Source;

              try
              {
            // create and cache greyscale ImageSource
            _sourceG = new FormatConvertedBitmap(new BitmapImage(new Uri(TypeDescriptor.GetConverter(Source).ConvertTo(Source, typeof(string)) as string)),
                                             PixelFormats.Gray16, null, 0);

            // create Opacity Mask for greyscale image as FormatConvertedBitmap does not keep transparency info
            _opacityMaskG = new ImageBrush(_sourceC);
            _opacityMaskG.Opacity = 0.5;

            this.Source = IsEnabled ? _sourceC : _sourceG;
            this.OpacityMask = IsEnabled ? _opacityMaskC : _opacityMaskG;

            InvalidateProperty(IsEnabledProperty);
              }
              catch
              {
            #if DEBUG
            MessageBox.Show(String.Format("The ImageSource used cannot be greyed out.\nUse BitmapImage or URI as a Source in order to allow greyscaling.\nSource type used: {0}", Source.GetType().Name),
                        "Unsupported Source in GreyableImage", MessageBoxButton.OK, MessageBoxImage.Warning);
            #endif // DEBUG

            // in case greyscale image cannot be created set greyscale source to original Source
            _sourceG = Source;
              }
        }
        public MediaPlayerControl()
        {
            InitializeComponent();

            SoundOff = loadImageSource(Properties.Resources.SoundOffIcon);
            SoundOn = loadImageSource(Properties.Resources.SoundOnIcon);
            PlayIcon = loadImageSource(Properties.Resources.PlayIcon);
            PauseIcon = loadImageSource(Properties.Resources.PauseIcon);
            brushSoundOff = new ImageBrush();
            brushSoundOff.ImageSource = SoundOff;//loadImageSource(Properties.Resources.SoundOffIcon);
            brushSoundOn = new ImageBrush();
            brushSoundOn.ImageSource = SoundOn;//loadImageSource(Properties.Resources.SoundOnIcon);
            lblMuteSound.Background = brushSoundOn;

            brushPlayIcon = new ImageBrush();
            brushPlayIcon.ImageSource = PlayIcon;
            lblPlay.Background = brushPlayIcon;

            brushPauseIcon = new ImageBrush();
            brushPauseIcon.ImageSource = PauseIcon;

            EnableControls(false);

            soundSlider.Value = soundSlider.Maximum;
            SetControlFlow(0, 0, 0, 0);
        }
 public void NeedsToSync()
 {
     readyToSync = true;
     DEFAULT = SYNC;
     if(!transferInProgress)
         updateStatusImage(DEFAULT);
 }
 public NumericControl(Func<string, Task> sendCommandAction, ImageSource signalIcon, DataType type)
 {
     SendCommandAction = sendCommandAction;
     Type = type;
     InitializeComponent();
     SignalImg.Source = signalIcon;
 }
Example #14
0
        /// <summary>
        /// Creates a new screen
        /// </summary>
        public Screen(int width, int height, int fps)
        {
            Fps = Config.Get("Fps", fps);
            base.Width = Config.Get("ScreenWidth", width);
            base.Height = Config.Get("ScreenHeight", height);
            Trace.Info("new Screen(Fps = {0}, Width = {1}, Height = {2})", Fps, Width, Height);

            _dirty = true;
            _clipping = new Rect(0, 0, Width, Height);
            _backBuffer = new DrawingImage(_buffer = new DrawingGroup());
            _keyMapping = Module.Get<IKeyMapping>();

            (_window = new Window()
            {
                WindowStyle = WindowStyle.None,
                ResizeMode = ResizeMode.NoResize,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                Content = this,
                SizeToContent = SizeToContent.WidthAndHeight,
            }).Show();
            _window.KeyDown += _window_KeyDown;
            _window.KeyUp += _window_KeyUp;

            (_refreshTimer = new Timer(FrameTime)).Update += OnRenderCallback;
        }
 internal async Task ReLoadGravatar()
 {
     if(!String.IsNullOrEmpty(this.Email)) {
         this.FeedbackMessage.GravatarHash = GravatarHelper.CreateHash(this.Email);
         this.Gravatar = await GravatarHelper.LoadGravatar(this.FeedbackMessage.GravatarHash);
     }
 }
 public ImgView(string phoneNumber, string nickName , ImageSource imageSource, string hour)
 {
     InitializeComponent();
     this.PhoneNumber = phoneNumber;
     this.NickName = nickName;
     this.ImageSourceLink = imageSource;
     this.Hour = hour;
     
     this.imgField.Source = ImageSourceLink;
     string from = PhoneNumber;
     if (string.IsNullOrEmpty(nickName))
     {
         from = PhoneNumber;
     }
     else
     {
         from = PhoneNumber + " - " + nickName;
         
     }
    
     Helpers.parseEmjoi(from, this.fromfd);
     this.phoneField.Foreground = NumberPropList.Instance.getPhoneColor(phoneNumber);
     this.hourField.Text = Hour;
     this.HorizontalAlignment = HorizontalAlignment.Left;
     buildImgView(this);
     this.phoneField.Width = Helpers.MeasureString(from, this.phoneField.FontFamily, this.phoneField.FontStyle, this.phoneField.FontWeight, this.phoneField.FontStretch, this.phoneField.FontSize).Width + 50;
     
 }
Example #17
0
 void imageSource_NewDataAvailable(ImageSource data)
 {
     this.videoControl.Dispatcher.BeginInvoke(new Action(() =>
     {
         this.videoControl.ShowImageSource(data);
     }));
 }
Example #18
0
        public static LoginData ShowDialog(String title, String header, String info,
            String userNameText, String userName, ImageSource icon, SkinBundle bundle, Func<String, String, bool> validateUser)
        {
            LoginDialogEx dlg = new LoginDialogEx(validateUser, bundle)
                {
                    Title = title,
                    hInfo =
                        {
                            HeaderContent = header,
                            DescriptionText = info
                        }
                };
            if (bundle != null)
            {
                bundle.SetBundle(dlg);
            }

            if (userNameText != null)
                dlg.lblUserName.Content = userNameText;
            dlg.txtUsername.Text = userName;
            if (icon != null)
                dlg.Icon = icon;

            if (dlg.ShowDialog().GetValueOrDefault(false))
                return new LoginData(dlg.txtUsername.Text, dlg.txtPassword.Password);
            else
                return null;
        }
        private void CoerceOptimalImageForSize(Size size)
        {
            if (_optimalImageForSize != null)
                return;
            var frame = Source as BitmapFrame;
            var num1 = (int) size.LogicalToDeviceUnits().Width;
            var num2 = -1;
            if (frame != null)
            {
                if (frame.Decoder == null) return;
                foreach (var bitmapFrame in frame.Decoder.Frames)
                {
                    var pixelWidth = bitmapFrame.PixelWidth;
                    if (pixelWidth == num1)
                    {
                        _optimalImageForSize = bitmapFrame;
                        break;
                    }
                    if (pixelWidth > num1)
                    {
                        if (num2 >= num1 && pixelWidth >= num2) continue;
                        num2 = pixelWidth;
                        _optimalImageForSize = bitmapFrame;
                    }
                    else if (pixelWidth > num2)
                    {
                        num2 = pixelWidth;
                        _optimalImageForSize = bitmapFrame;
                    }
                }
            }
            else
                _optimalImageForSize = Source;

        }
Example #20
0
 /// <summary>
 /// Overlay the full screen view of the image
 /// </summary>
 private void OnDisplayFullImage(object sender, RoutedEventArgs e)
 {
     // Always go to normal state before a transition
     this.SelectedImage = ((ContentControl)e.OriginalSource).Content as ImageSource;
     VisualStateManager.GoToElementState(OverlayGrid, NormalState, false);
     VisualStateManager.GoToElementState(OverlayGrid, FadeInTransitionState, false);
 }
		public async Task<Windows.UI.Xaml.Media.ImageSource> LoadImageAsync(ImageSource imagesoure, CancellationToken cancellationToken = new CancellationToken())
		{
			var imageLoader = imagesoure as UriImageSource;
			if (imageLoader?.Uri == null)
				return null;

			Stream streamImage = await imageLoader.GetStreamAsync(cancellationToken);
			if (streamImage == null || !streamImage.CanRead)
			{
				return null;
			}

			using (IRandomAccessStream stream = streamImage.AsRandomAccessStream())
			{
				try
				{
					var image = new BitmapImage();
					await image.SetSourceAsync(stream);
					return image;
				}
				catch (Exception ex)
				{
					Debug.WriteLine(ex);

					// Because this literally throws System.Exception
					// According to https://msdn.microsoft.com/library/windows/apps/jj191522
					// this can happen if the image data is bad or the app is close to its 
					// memory limit
					return null;
				}
			}
		}
Example #22
0
 private void SetCover(ImageSource img)
 {
     Dispatcher.BeginInvoke(new Action(delegate
     {
         Cover.Source = img;
     }));
 }
Example #23
0
        public PhotoThread( ImageSource src, DateTime dateTime )
        {
            InitializeComponent ();

            Content = src;
            Date = dateTime;
        }
 public void ShowImageSource(ImageSource source)
 {
     this.videoImage.Dispatcher.Invoke(new Action(() =>
     {
         this.videoImage.Source = source;
     }));
 }
Example #25
0
		public static void SetImageBrush(ImageBrush brush, ImageSource imageSource)
		{
			if (brush == null)
				return;

			brush.ImageSource = imageSource;
		}
Example #26
0
		public SearchBarControl ()
		{
			InitializeComponent ();
			DataContext = this;

			SearchBar.GotKeyboardFocus += (o, e) => {
				if (searchText == placeholderText)
					SearchText = string.Empty;
			};
			IdeApp.Workbench.RootWindow.SetFocus += (o, e) =>
			{
				Keyboard.ClearFocus();
				IdeApp.Workbench.RootWindow.Present();
			};

			searchIcon = Stock.SearchboxSearch.GetImageSource (Xwt.IconSize.Small);
			searchIconHovered = Xwt.Drawing.Image.FromResource (typeof(IdeApp), "searchbox-search-win-24~hover.png").WithSize (Xwt.IconSize.Small).GetImageSource ();
			searchIconPressed = Xwt.Drawing.Image.FromResource (typeof(IdeApp), "searchbox-search-win-24~pressed.png").WithSize (Xwt.IconSize.Small).GetImageSource ();
			clearIcon = ((MonoDevelop.Core.IconId)"md-searchbox-clear").GetImageSource (Xwt.IconSize.Small);
			clearIconHovered = Xwt.Drawing.Image.FromResource (typeof(IdeApp),"searchbox-clear-win-24~hover.png").WithSize (Xwt.IconSize.Small).GetImageSource ();
			clearIconPressed = Xwt.Drawing.Image.FromResource (typeof(IdeApp), "searchbox-clear-win-24~pressed.png").WithSize (Xwt.IconSize.Small).GetImageSource ();
			SearchIcon.Image = searchIcon;
			SearchIcon.ImageHovered = searchIconHovered;
			SearchIcon.ImagePressed = searchIconPressed;
			SearchIcon.Focusable = false;
		}
        public RadFixedDocument CreateDocument()
        {
            RadFixedDocument document = new RadFixedDocument();
            RadFixedPage page = document.Pages.AddPage();
            page.Size = new Size(600, 800);
            this.editor = new FixedContentEditor(page);
            this.editor.Position.Translate(40, 50);
            using (Stream stream = FileHelper.GetSampleResourceStream("banner.png"))
            {
                ImageSource imageSource = new ImageSource(stream, ImageQuality.High);
                editor.DrawImage(imageSource, new Size(530, 80));
            }

            editor.Position.Translate(ExampleDocumentSizes.DefaultLeftIndent, 160);
            double maxWidth = page.Size.Width - ExampleDocumentSizes.DefaultLeftIndent * 2;

            this.DrawDescription(maxWidth);

            using (editor.SaveProperties())
            {
                using (editor.SavePosition())
                {
                    this.DrawFunnelFigure();
                }
            }

            return document;
        }
 public void load_image(object arg, DoWorkEventArgs e)
 {
     int contribution_id = (int)e.Argument;
     if (!window_manager.downloaded_contributions.Contains(contribution_id))
     {
         naturenet_dataclassDataContext db = new naturenet_dataclassDataContext();
         var result1 = from c in db.Contributions
                       where c.id == contribution_id
                       select c;
         if (result1.Count() != 0)
         {
             Contribution contrib = result1.First<Contribution>();
             bool result = file_manager.download_file_from_googledirve(contrib.media_url, contribution_id);
             if (result) window_manager.downloaded_contributions.Add(contribution_id);
         }
     }
     try
     {
         ImageSource src = new BitmapImage(new Uri(configurations.GetAbsoluteContributionPath() + contribution_id.ToString() + ".jpg"));
         src.Freeze();
         the_image = src;
         //window_manager.contributions.Add(contribution_id, src);
         e.Result = (object)contribution_id;
     }
     catch (Exception)
     {
         /// write log
         e.Result = -1;
     }
 }
Example #29
0
      public Dial_ViewImagen(ImageSource imagen){
          InitializeComponent();
          this.img_documento.Source = imagen;
 
          this.vb_contenido.Width = imagen.Width;
          this.vb_contenido.Height = imagen.Height;
      }
        public CompareResultWindow(string filePath, ImageSource avatar, string name, string compareResult, bool equal)
        {
            InitializeComponent();

            stayTime = GetStayTime();

            lblName.Content = name;
            lblResult.Content = compareResult;
            imgsnap.Source = filePath.FileToByte().ToImageSource();
            imgAvatar.Source = avatar;

            if (equal)
            {
                lblResult.Foreground = Brushes.Green;
                imgResult.Source = new BitmapImage(new Uri(okImageSource, UriKind.Relative));
            }
            else
            {
                lblResult.Foreground = Brushes.Red;
                imgResult.Source = new BitmapImage(new Uri(errorImageSource, UriKind.Relative));
            }

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(stayTime);
                Application.Current.Dispatcher.Invoke(() =>
                {
                    this.Close();
                });
            });
        }
Example #31
0
 private void loadApplicationImages()
 {
     imgBookmark.Source = ImageSource.FromResource("MEDictionary.Images.bookmark.png");
     imgEnglish.Source  = ImageSource.FromResource("MEDictionary.Images.underline.png");
     imgMarathi.Source  = ImageSource.FromResource("MEDictionary.Images.underline.png");
 }
Example #32
0
        //the function manage the search bar
        #region TextBox-TextChanged-txtAuto
        private void txtAuto_TextChanged(object sender, TextChangedEventArgs e)
        {
            string         NormaltypedString = txtAuto.Text;
            string         typedString       = NormaltypedString.ToLower();
            List <ListApp> listApps          = new List <ListApp>();
            bool           found             = false;

            listApps.Clear();
            int itemCounter = 0;

            if (!nameList.Contains(NormaltypedString))
            {
                foreach (string item in nameList)
                {
                    string lowerItem = item.ToLower();
                    if (!string.IsNullOrEmpty(typedString))
                    {
                        found = false;
                        if (lowerItem.StartsWith(typedString))
                        {
                            found = true;
                        }
                        else
                        {
                            foreach (string word in lowerItem.Split(' '))
                            {
                                if (word.StartsWith(typedString))
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (found && itemCounter < 4 && !addedNames.Contains(item))
                        {
                            try
                            {
                                ImageSource icon = Icon.ExtractAssociatedIcon(pathList[nameList.IndexOf(item)]).ToImageSource();
                                listApps.Add(new ListApp(item, icon));
                                //listApps.Add(new ListApp(item, iconsList[nameList.IndexOf(item)]));
                                itemCounter++;
                            }
                            catch
                            {
                                Console.WriteLine("Couldn't get icon");
                            }
                        }
                    }
                }
            }

            if (listApps.Count > 0)
            {
                lbSuggestion.ItemsSource = listApps;
                lbSuggestion.Visibility  = Visibility.Visible;
            }
            else if (txtAuto.Text.Equals(""))
            {
                lbSuggestion.Visibility  = Visibility.Collapsed;
                lbSuggestion.ItemsSource = null;
            }
            else
            {
                lbSuggestion.Visibility  = Visibility.Collapsed;
                lbSuggestion.ItemsSource = null;
            }
        }
Example #33
0
 //the function creates the define button
 private void DefineButton_Click(object sender, RoutedEventArgs e)
 {
     if (File.Exists(txtAuto.Text))
     {
         string[] appsLines = System.IO.File.ReadAllLines(Globals.APPS_PATH);
         int      count     = 0;
         string   name      = "";
         bool     inApps    = false;
         foreach (string line in appsLines)
         {
             if (count % 2 == 0)
             {
                 name = line;
             }
             else
             {
                 if (line == txtAuto.Text)
                 {
                     inApps = true;
                     break;
                 }
             }
             count++;
         }
         if (inApps)
         {
             int         index = nameList.IndexOf(name);
             ImageSource icon  = Icon.ExtractAssociatedIcon(pathList[index]).ToImageSource();
             //DefineWindow window1 = new DefineWindow(name, iconsList[index], "");
             DefineWindow2 window1 = new DefineWindow2(name, icon, "");
             window1.ShowDialog();
             if (window1.saveButton.Content.ToString() == "1")
             {
                 Console.WriteLine("1");
                 DefinedNames();
                 LoadImages();
             }
             txtAuto.Text = "";
         }
         else
         {
             string        path    = txtAuto.Text;
             Icon          icon    = Icon.ExtractAssociatedIcon(path);
             string        appName = System.IO.Path.GetFileNameWithoutExtension(path);
             DefineWindow2 window1 = new DefineWindow2(appName, icon.ToImageSource(), txtAuto.Text);
             window1.ShowDialog();
             if (window1.saveButton.Content.ToString() == "1")
             {
                 Console.WriteLine("1");
                 DefinedNames();
                 LoadImages();
             }
             txtAuto.Text        = "";
             txtAuto.BorderBrush = System.Windows.Media.Brushes.Gray;
         }
     }
     else if (nameList.Contains(txtAuto.Text))
     {
         int         index = nameList.IndexOf(txtAuto.Text);
         ImageSource icon  = Icon.ExtractAssociatedIcon(pathList[index]).ToImageSource();
         //DefineWindow window1 = new DefineWindow(txtAuto.Text, iconsList[index], "");
         DefineWindow2 window1 = new DefineWindow2(txtAuto.Text, icon, "");
         window1.ShowDialog();
         if (window1.saveButton.Content.ToString() == "1")
         {
             Console.WriteLine("1");
             DefinedNames();
             LoadImages();
         }
         txtAuto.Text        = "";
         txtAuto.BorderBrush = System.Windows.Media.Brushes.Gray;
     }
     else
     {
         txtAuto.BorderBrush = System.Windows.Media.Brushes.Red;
     }
 }
Example #34
0
        public GSDetailsC(string testCV)
        {
            InitializeComponent();

            ChallengeValue = testCV;

            ToDoItem = new ToDoItem();

            ViewModel = new ItemDetailViewModel();

            // first set of five...
            if (ChallengeValue == "Turn off Faucet")
            {
                imgChallenge.Source   = ImageSource.FromFile("WaterFaucetLS.jpg");
                lblGreenShoots.Text   = "Turn off Faucet";
                lblTurnOffFaucet.Text = "Eight gallons of water a day can be saved by shutting off faucet when brushing teeth; similarly, lots of water can be conserved while washing hands - turn off tap for 20 seconds while scrubbing with soap;";
            }

            if (ChallengeValue == "Unplug Appliances")
            {
                imgChallenge.Source   = ImageSource.FromFile("UnplugAppliances.jpg");
                lblGreenShoots.Text   = "Unplug Appliances";
                lblTurnOffFaucet.Text = "Household appliances waste energy even if not turned on; instead of leaving coffee makers, toasters, lamps plugged in - make small effort to unplug if not being utilized;";
            }

            if (ChallengeValue == "Cold Water Laundry")
            {
                imgChallenge.Source   = ImageSource.FromFile("CWL.jpg");
                lblGreenShoots.Text   = "Cold Water Laundry";
                lblTurnOffFaucet.Text = "About 90% of energy used by a washing machine goes towards heating water; to save energy, wash laundry on cold water setting for at least one load a week; plus, cold water may be better for clothes - can remove many stains from clothing;";
            }

            if (ChallengeValue == "Air Dry Cycle")
            {
                imgChallenge.Source   = ImageSource.FromFile("AirDryLS.jpg");
                lblGreenShoots.Text   = "Air Dry Cycle";
                lblTurnOffFaucet.Text = "Consider selecting an air-dry cycle to dry dishes; this will save 15 percent of dishwasher's energy use; if this option is not available on dishwasher, open door to let dishes dry once load has finished washing;";
            }

            if (ChallengeValue == "Eco-Friendly Products")
            {
                imgChallenge.Source   = ImageSource.FromFile("EFP.jpg");
                lblGreenShoots.Text   = "Eco-Friendly Products";
                lblTurnOffFaucet.Text = "When it comes to household products, shopping eco-friendly goes a long way; instead of single-use, disposable items, look for green products that are reusable, sustainably sourced, or made of recycled materials;";
            }

            // second set of five...
            if (ChallengeValue == "Cloth Towels")
            {
                imgChallenge.Source   = ImageSource.FromFile("CTLS.jpg");
                lblGreenShoots.Text   = "Cloth Towels";
                lblTurnOffFaucet.Text = "It is certainly cheaper to hold onto a cloth towel than to buy a new roll of paper towels every week;";
            }

            if (ChallengeValue == "Water Bottles")
            {
                imgChallenge.Source   = ImageSource.FromFile("WaterBottles300x200.jpg");
                lblGreenShoots.Text   = "Water Bottles";
                lblTurnOffFaucet.Text = "Replace regular single use plastic bottles with some of plastic, glass, and stainless steel reusable water bottles that are all the rage;";
            }

            if (ChallengeValue == "Turn off Lights")
            {
                imgChallenge.Source   = ImageSource.FromFile("LightsLS.jpg");
                lblGreenShoots.Text   = "Turn off Lights";
                lblTurnOffFaucet.Text = "Turning off lights if not home, or even not in a room, can significantly cut down how much energy is utilized;";
            }

            if (ChallengeValue == "Don't Idle Car")
            {
                imgChallenge.Source   = ImageSource.FromFile("IdleCarLS.jpg");
                lblGreenShoots.Text   = "Don't Idle Car";
                lblTurnOffFaucet.Text = "If idling in car for more than 2 minutes, turn off engine; this way, car is only releasing emissions while driving;";
            }

            if (ChallengeValue == "Reusable Cups")
            {
                imgChallenge.Source   = ImageSource.FromFile("RCLS.jpg");
                lblGreenShoots.Text   = "Reusable Cups";
                lblTurnOffFaucet.Text = "Bring a reusable coffee mug to regular coffee shop and ask to put coffee in there - chains like Starbucks and Dunkin will give you a discount;";
            }

            // third set of five...
            if (ChallengeValue == "Rain Water")
            {
                imgChallenge.Source   = ImageSource.FromFile("RainWaterBase.jpg");
                lblGreenShoots.Text   = "Rain Water";
                lblTurnOffFaucet.Text = "Invest in a rainwater collection system; non-drinking water can be utilized in many ways - like cleaning, watering plants;";
            }

            if (ChallengeValue == "Reuseable Batteries")
            {
                imgChallenge.Source   = ImageSource.FromFile("ReuseBatteriesBase.jpg");
                lblGreenShoots.Text   = "Reuseable Batteries";
                lblTurnOffFaucet.Text = "Running out of batteries? late night drugstore runs for replacements can be curtailed by using reusable batteries instead;";
            }

            if (ChallengeValue == "Fix Leaky Faucet")
            {
                imgChallenge.Source   = ImageSource.FromFile("FixLeakyFaucetBase.jpg");
                lblGreenShoots.Text   = "Fix Leaky Faucet";
                lblTurnOffFaucet.Text = "Tiny drops of water add up when it comes to a water bill; tighten up a drippy faucet - cut down on consumption of water;";
            }

            if (ChallengeValue == "Take Stairs")
            {
                imgChallenge.Source   = ImageSource.FromFile("TakeStairsBase.jpg");
                lblGreenShoots.Text   = "Take Stairs";
                lblTurnOffFaucet.Text = "Taking stairs cuts down on required energy to power an elevator - plus, it is a great workout;";
            }

            if (ChallengeValue == "Ditch Plastic Straws")
            {
                imgChallenge.Source   = ImageSource.FromFile("DitchPS.jpg");
                lblGreenShoots.Text   = "Ditch Plastic Straws";
                lblTurnOffFaucet.Text = "Americans use 500 million plastic straws each day; replace plastic straws with a set of reusables - made from stainless steel, silicone, bamboo; sea turtles will thank you;";
            }

            // fourth set of five...
            if (ChallengeValue == "Carbon Footprint")
            {
                imgChallenge.Source   = ImageSource.FromFile("CarbonFootprintBase.jpg");
                lblGreenShoots.Text   = "Carbon Footprint";
                lblTurnOffFaucet.Text = "Calculate carbon footprint - determining amount of CO2 produced through daily routines is a first step; warning: results come with a little sense of guilt;";
            }

            if (ChallengeValue == "Car @ Home")
            {
                imgChallenge.Source   = ImageSource.FromFile("CarAtHomeBase.jpg");
                lblGreenShoots.Text   = "Car @ Home";
                lblTurnOffFaucet.Text = "Leave car @ home - it has never been easier to ditch a car; organize a carpool with co-workers, use a rideshare app, take public transit - or be most health-conscious, and ride a bike; less cars on road not only means less air pollution, it also means less traffic; not to mention saved gas money :)";
            }

            if (ChallengeValue == "Green Makeover")
            {
                imgChallenge.Source   = ImageSource.FromFile("GreenMakeoverBase.jpg");
                lblGreenShoots.Text   = "Green Makeover";
                lblTurnOffFaucet.Text = "Give home a green makeover - going green does not necessarily require solar panels; little switches such as buying energy-efficient light bulbs that can save a few dollars in long run;";
            }

            if (ChallengeValue == "Fix Something")
            {
                imgChallenge.Source   = ImageSource.FromFile("FixSomethingBase.jpg");
                lblGreenShoots.Text   = "Fix Something";
                lblTurnOffFaucet.Text = "There is no reason to throw away something that's on fritz; online tutorials, apps such as TaskRabbit have made it possible to salvage malfunctioning products - without having to shell out money for a replacement;";
            }

            if (ChallengeValue == "Junk Mail")
            {
                imgChallenge.Source   = ImageSource.FromFile("JunkMailBase.jpg");
                lblGreenShoots.Text   = "Junk Mail";
                lblTurnOffFaucet.Text = "Unsubscribe from junk mail; it is time to save some trees, get name off mailing lists once and for all; also, opting out of a printed phone directory might be worth considering;";
            }

            // fifth set of five...
            if (ChallengeValue == "Go Paperless")
            {
                imgChallenge.Source   = ImageSource.FromFile("GoPaperlessBase.jpg");
                lblGreenShoots.Text   = "Go Paperless";
                lblTurnOffFaucet.Text = "Everything is online; think about how much paper can be saved by getting bank statements, bills sent electronically - and paid same way; same deal with event, travel tickets; most places don't require physical copies;";
            }

            if (ChallengeValue == "Switch to E-Books")
            {
                imgChallenge.Source   = ImageSource.FromFile("EbooksBase.jpg");
                lblGreenShoots.Text   = "Switch to E-Books";
                lblTurnOffFaucet.Text = "Switch to e-books - turn page with a single swipe; sure, there is a certain excitement that comes along with cracking open a new book - there is also a certain satisfaction that comes from sliding fingers across a screen; publishers offer interactive editions when an e-book is purchased;";
            }

            if (ChallengeValue == "Unplug at Night")
            {
                imgChallenge.Source   = ImageSource.FromFile("UnplugNightBase.jpg");
                lblGreenShoots.Text   = "Unplug at Night";
                lblTurnOffFaucet.Text = "Similar to kitchen, household appliances - it helps to get into practice of powering down electronics overnight; it is worth noting devices are wasting energy even if not turned on; best way to maximize energy efficiency is to unplug, shutdown;";
            }

            if (ChallengeValue == "Recycle Electronics")
            {
                imgChallenge.Source   = ImageSource.FromFile("RecycleElectronicsBase.jpg");
                lblGreenShoots.Text   = "Recycle Electronics";
                lblTurnOffFaucet.Text = "An old iPhone does not need to collect dust in a drawer - and does not need to go in trash; phones, other electronics can be brought to special centers in any area - and some places have buyback programs;";
            }

            if (ChallengeValue == "Add Plants to Home")
            {
                imgChallenge.Source   = ImageSource.FromFile("AddPlantsHomeBase.jpg");
                lblGreenShoots.Text   = "Add Plants to Home";
                lblTurnOffFaucet.Text = "Bringing a little greenery into a home can help regulate temperature through moisture released into air; this helps reduce energy required to heat, cool a home - plus, they look good!";
            }
        }
Example #35
0
        /// <summary>
        /// Initializes a new instance of class.
        /// </summary>
        /// <param name="model">Instance we want to display</param>
        public MediaDetailsView(int ItemID, InventoryMedia model)
        {
            string SelectedFilename = "";

            // Bind our BindingContext
            Model = model;

            NavigationPage.SetHasNavigationBar(this, true);

            InitializeComponent();
            //
            // Select Photo Button
            btnSelectPhoto.Clicked += async(sender, e) =>
            {
                if (!CrossMedia.Current.IsPickPhotoSupported)
                {
                    await DisplayAlert("Pick Photo", ":( Pick Photo not avaialble.", "OK");

                    return;
                }
                var file = await CrossMedia.Current.PickPhotoAsync();

                if (file == null)
                {
                    return;
                }
                //
                imgPhoto.Source = ImageSource.FromStream(() =>
                {
                    var stream       = file.GetStream();
                    SelectedFilename = file.Path;
                    file.Dispose();
                    //
                    return(stream);
                });
            };
            btnTakePhoto.Clicked += async(sender, args) =>
            {
                if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                {
                    await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");

                    return;
                }

                var file = await CrossMedia.Current.TakePhotoAsync(new Media.Plugin.Abstractions.StoreCameraMediaOptions
                {
                    Directory = "Sample",
                    Name      = "rcinventory.jpg"
                });

                if (file == null)
                {
                    return;
                }

                await DisplayAlert("File Location", file.Path, "OK");

                imgPhoto.Source = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    file.Dispose();
                    model.Filename = file.Path;
                    return(stream);
                });
            };
            //
            // Save Button
            btnSaveM.Clicked += (sender, e) =>
            {
                model.ItemID       = ItemID;
                model.Filename     = SelectedFilename;
                model.MediaType    = "Image";
                model.DateTaken    = DTPicker.Date;
                model.DefaultMedia = true;
                int mediaID = App.Database.SaveMedia(Model);
                Navigation.PopAsync();
            };
            //
            // Cancel Button
            btnCancelM.Clicked += (sender, e) =>
            {
                Navigation.PopAsync();
            };
            //
            // Delete Button
            btnDeleteM.Clicked += (sender, e) =>
            {
                App.Database.DeleteMedia(Model.ID);
                Navigation.PopAsync();
            };
        }
Example #36
0
 public WindowService <T> SetIcon(ImageSource icon)
 {
     _icon = icon;
     return(this);
 }
Example #37
0
 public async Task <ImageSource> GetImageUser(string uri) =>
 await Task.Factory.StartNew(() => ImageSource.FromUri(new Uri(uri)));
Example #38
0
        function GetSeperateTags()
        {
            var tree = serviceResponse.Split('>');
            //List<StringList> stringLists = new List<StringList>();
            //var stree = "{\"data\":[{\"Name\":\"\" },{\"Name\":\"\" }]}";
            var stree = "{\"data\":[";//{\"Name\":\"\" },{\"Name\":\"\" }]}

            foreach (var item in tree)
            {
                if (item.ToLower().Contains("img") || item.ToLower().Contains("image"))
                {
                    if (item.Contains("src"))
                    {
                        var _item = (item.Contains("\"")) ? item.Replace("\"", "\\\"") : item;
                        _item  = (_item.Contains("\n")) ? _item.Replace("\n", "") : _item;
                        stree += "{\"Name\":\"" + _item + ">\" },";
                        //stringLists.Add()
                        //obtData.Add(item, HTMLAttributes(item)["src"]);
                    }
                }
            }
            stree  = stree.Remove(stree.Length - 1);
            stree += "]}";

            var           jsonString    = Newtonsoft.Json.JsonConvert.DeserializeObject <HTMLSet>(stree);
            List <string> imagesURLList = new List <string>();

            foreach (var item in jsonString.data)
            {
                var attrs = HTMLAttributes(item.Name);
                foreach (var attr in attrs)
                {
                    if (attr.Key == "src")
                    {
                        imagesURLList.Add(attr.Value);
                        try
                        {
                            Image image = new Image();
                            image.Source = ImageSource.FromUri(new Uri(attr.Value));

                            //galleryImageItem.Image_Source = ImageSource.FromStream(() =>
                            //{
                            //    return new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File));
                            //});
                            //galleryImageItem.ImageStream = new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File));
                            //using(var stream = new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File)))
                            //{
                            //    galleryImageItem.ImageStream = stream;
                            //}

                            stackImageHolder.Children.Add(image);
                        }
                        catch (Exception ex)
                        {
                            var msg = ex.Message + "\n" + ex.StackTrace;
                            System.Diagnostics.Debug.WriteLine(msg);
                        }
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine(stree);
        }
Example #39
0
        async void ButtonClickedEvent(object sender, System.EventArgs e)
        {
            try
            {
                //var _url = "https://www.pexels.com/search/beauty/";
                var _url        = "https://www.pexels.com/search/";
                var _methodName = "beauty";
                var url         = (!string.IsNullOrEmpty(entryURL.Text)) ? entryURL.Text : _url;
                using (IWebServices webServices = new WebServices())
                {
                    var response = await webServices.GetHTMLFromURL(_url, _methodName);

                    serviceResponse = response.ToString();
                }
                //labelJSONStringData.Text = serviceResponse;
                var tree = serviceResponse.Split('>');
                //List<StringList> stringLists = new List<StringList>();
                //var stree = "{\"data\":[{\"Name\":\"\" },{\"Name\":\"\" }]}";
                var stree = "{\"data\":[";//{\"Name\":\"\" },{\"Name\":\"\" }]}
                foreach (var item in tree)
                {
                    if (item.ToLower().Contains("img") || item.ToLower().Contains("image"))
                    {
                        if (item.Contains("src"))
                        {
                            var _item = (item.Contains("\"")) ? item.Replace("\"", "\\\"") : item;
                            _item  = (_item.Contains("\n")) ? _item.Replace("\n", "") : _item;
                            stree += "{\"Name\":\"" + _item + ">\" },";
                            //stringLists.Add()
                            //obtData.Add(item, HTMLAttributes(item)["src"]);
                        }
                    }
                }
                stree  = stree.Remove(stree.Length - 1);
                stree += "]}";

                var           jsonString    = Newtonsoft.Json.JsonConvert.DeserializeObject <HTMLSet>(stree);
                List <string> imagesURLList = new List <string>();
                foreach (var item in jsonString.data)
                {
                    var attrs = HTMLAttributes(item.Name);
                    foreach (var attr in attrs)
                    {
                        if (attr.Key == "src")
                        {
                            imagesURLList.Add(attr.Value);
                            try
                            {
                                Image image = new Image();
                                image.Source = ImageSource.FromUri(new Uri(attr.Value));

                                //galleryImageItem.Image_Source = ImageSource.FromStream(() =>
                                //{
                                //    return new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File));
                                //});
                                //galleryImageItem.ImageStream = new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File));
                                //using(var stream = new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File)))
                                //{
                                //    galleryImageItem.ImageStream = stream;
                                //}

                                stackImageHolder.Children.Add(image);
                            }
                            catch (Exception ex)
                            {
                                var msg = ex.Message + "\n" + ex.StackTrace;
                                System.Diagnostics.Debug.WriteLine(msg);
                            }
                        }
                    }
                }
                System.Diagnostics.Debug.WriteLine(stree);
                //var ress = HTMLAttributes(serviceResponse)["src"];
            }
            catch (Exception ex)
            {
                var msg = ex.Message + "\n" + ex.StackTrace;
                System.Diagnostics.Debug.WriteLine(msg);
            }
        }
        ContentPage BuildMenu()
        {
            if (_menu != null)
            {
                return(_menu);
            }

            var layout = new Grid
            {
                VerticalOptions   = LayoutOptions.Fill,
                HorizontalOptions = LayoutOptions.Fill,
                ColumnDefinitions = new ColumnDefinitionCollection {
                    new ColumnDefinition(), new ColumnDefinition()
                }
            };

            var col1 = new StackLayout();

            layout.Children.Add(col1);
            Grid.SetColumn(col1, 0);

            var col2 = new StackLayout();

            layout.Children.Add(col2);
            Grid.SetColumn(col2, 1);

            col1.Children.Add(MenuButton(nameof(Image), () => new Image {
                Source = ImageSource.FromFile("oasis.jpg")
            }));
            col1.Children.Add(MenuButton(nameof(Frame), () => new Frame {
                BackgroundColor = Color.DarkGoldenrod
            }));
            col1.Children.Add(MenuButton(nameof(Entry), () => new Entry()));
            col1.Children.Add(MenuButton(nameof(Editor), () => new Editor()));
            col1.Children.Add(MenuButton(nameof(Button), () => new Button {
                Text = "Test"
            }));
            col1.Children.Add(MenuButton(nameof(Label), () => new Label
            {
                LineBreakMode = LineBreakMode.WordWrap,
                Text          = "Lorem ipsum dolor sit amet"
            }));
            col1.Children.Add(MenuButton(nameof(SearchBar), () => new SearchBar()));

            col2.Children.Add(MenuButton(nameof(DatePicker), () => new DatePicker()));
            col2.Children.Add(MenuButton(nameof(TimePicker), () => new TimePicker()));

            var slider = new Slider();

            slider.On <iOS>().SetUpdateOnTap(true);
            col2.Children.Add(MenuButton(nameof(Slider), () => slider));

            col2.Children.Add(MenuButton(nameof(Switch), () => new Switch()));
            col2.Children.Add(MenuButton(nameof(Stepper), () => new Stepper()));
            col2.Children.Add(MenuButton(nameof(BoxView), () => new BoxView {
                BackgroundColor = Color.DarkMagenta, WidthRequest = 100, HeightRequest = 100
            }));

            return(new ContentPage {
                Content = layout
            });
        }
Example #41
0
        public async System.Threading.Tasks.Task <bool> SaveImage(string strDir, string fileName, ImageSource imageinfo)
        {
            bool rest = await DependencyService.Get <IPicture>().SaveImage(strDir, fileName, imageinfo);

            return(rest);
        }
Example #42
0
        public async Task <DataResolverResult> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            ImageSource source = parameters.Source;

            if (!string.IsNullOrWhiteSpace(parameters.LoadingPlaceholderPath) && parameters.LoadingPlaceholderPath == identifier)
            {
                source = parameters.LoadingPlaceholderSource;
            }
            else if (!string.IsNullOrWhiteSpace(parameters.ErrorPlaceholderPath) && parameters.ErrorPlaceholderPath == identifier)
            {
                source = parameters.ErrorPlaceholderSource;
            }

            var resolvedData = await(Configuration.DataResolverFactory ?? new DataResolverFactory())
                               .GetResolver(identifier, source, parameters, Configuration)
                               .Resolve(identifier, parameters, token).ConfigureAwait(false);

            if (resolvedData?.Stream == null)
            {
                throw new FileNotFoundException(identifier);
            }

            var svg = new SKSvg()
            {
                ThrowOnUnsupportedElement = false,
            };
            SKPicture picture;

            if (ReplaceStringMap == null || ReplaceStringMap.Count == 0)
            {
                using (var svgStream = resolvedData.Stream)
                {
                    picture = svg.Load(svgStream);
                }
            }
            else
            {
                using (var svgStream = resolvedData.Stream)
                    using (var reader = new StreamReader(svgStream))
                    {
                        var inputString = await reader.ReadToEndAsync();

                        foreach (var map in ReplaceStringMap
                                 .Where(v => v.Key.StartsWith("regex:")))
                        {
                            inputString = Regex.Replace(inputString, map.Key.Substring(6), map.Value);
                        }

                        var builder = new StringBuilder(inputString);

                        foreach (var map in ReplaceStringMap
                                 .Where(v => !v.Key.StartsWith("regex:", StringComparison.OrdinalIgnoreCase)))
                        {
                            builder.Replace(map.Key, map.Value);
                        }

                        using (var svgFinalStream = new MemoryStream(Encoding.UTF8.GetBytes(builder.ToString())))
                        {
                            picture = svg.Load(svgFinalStream);
                        }
                    }
            }

            double sizeX = 0;
            double sizeY = 0;

            if (VectorWidth <= 0 && VectorHeight <= 0)
            {
                if (picture.CullRect.Width > 0)
                {
                    sizeX = picture.CullRect.Width;
                }
                else
                {
                    sizeX = 300;
                }

                if (picture.CullRect.Height > 0)
                {
                    sizeY = picture.CullRect.Height;
                }
                else
                {
                    sizeY = 300;
                }
            }
            else if (VectorWidth > 0 && VectorHeight > 0)
            {
                sizeX = VectorWidth;
                sizeY = VectorHeight;
            }
            else if (VectorWidth > 0)
            {
                sizeX = VectorWidth;
                sizeY = (VectorWidth / picture.CullRect.Width) * picture.CullRect.Height;
            }
            else
            {
                sizeX = (VectorHeight / picture.CullRect.Height) * picture.CullRect.Width;
                sizeY = VectorHeight;
            }

            if (UseDipUnits)
            {
                sizeX = sizeX.DpToPixels();
                sizeY = sizeY.DpToPixels();
            }

            lock (_encodingLock)
            {
                using (var bitmap = new SKBitmap(new SKImageInfo((int)sizeX, (int)sizeY)))
                    //using (var bitmap = new SKBitmap((int)sizeX, (int)sizeY))
                    using (var canvas = new SKCanvas(bitmap))
                        using (var paint = new SKPaint())
                        {
                            canvas.Clear(SKColors.Transparent);
                            float scaleX = (float)sizeX / picture.CullRect.Width;
                            float scaleY = (float)sizeY / picture.CullRect.Height;
                            var   matrix = SKMatrix.MakeScale(scaleX, scaleY);

                            canvas.DrawPicture(picture, ref matrix, paint);
                            canvas.Flush();

                            using (var image = SKImage.FromBitmap(bitmap))
                                //using (var data = image.Encode(SKImageEncodeFormat.Png, 100))  //TODO disabled because of https://github.com/mono/SkiaSharp/issues/285
                                using (var data = image.Encode())
                                {
                                    var stream = new MemoryStream();
                                    data.SaveTo(stream);
                                    stream.Position = 0;
                                    resolvedData.ImageInformation.SetType(ImageInformation.ImageType.SVG);
                                    return(new DataResolverResult(stream, resolvedData.LoadingResult, resolvedData.ImageInformation));
                                }
                        }
            }
        }
Example #43
0
 public MainButtonViewModel(ButtonDTO button, ButtonConfigurationDTO buttonConfiguration, ImageSource mainImage, ImageSource selectedImage, Action <string> showCategoryAction)
 {
     _button = button;
     _buttonConfiguration = buttonConfiguration;
     _mainImage           = mainImage;
     _selectedImage       = selectedImage;
     CurrentImage         = _mainImage;
     CurrentTextColor     = TextColor;
     _showCategoryAction  = showCategoryAction;
 }
Example #44
0
 public void SetImage(String path)
 {
     this._image     = null;
     this._imagePath = path;
     this.OnPropertyChanged("Image");
 }
        private void Load()
        {
            bool           nadjeno  = true;
            StreamReader   sr       = null;
            OpenFileDialog openFile = null;
            string         line;

            while (nadjeno)
            {
                openFile        = new OpenFileDialog();
                openFile.Title  = "Open Text File";
                openFile.Filter = "TXT files|*.txt";
                if (openFile.ShowDialog() == true)
                {
                    try
                    {
                        sr = new StreamReader(openFile.FileName);
                    }
                    catch (SecurityException ex)
                    {
                        MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
                                        $"Details:\n\n{ex.StackTrace}");
                    }
                }
                else
                {
                    System.Environment.Exit(1);
                }


                string line1 = File.ReadLines(openFile.FileName).First();
                if (!(line1.Equals("MAP-EVENTS")))
                {
                    MessageBoxResult result = MessageBox.Show("Not Supported File");
                }
                else
                {
                    nadjeno = false;
                }
            }

            sr.ReadLine();
            int i = 0;

            ListaEtiketa.Etikete = new Dictionary <string, Etiketa>();
            ListaTipManifestacijecs.TipoviManifestacija = new Dictionary <string, TipManifestacije>();
            ListaManifestacija.Manifestacije            = new Dictionary <string, Manifestacija>();
            while ((line = sr.ReadLine()) != null)
            {
                if (line == "")
                {
                    i++;
                    if (sr.ReadLine() != null && i < 3)
                    {
                        line = sr.ReadLine();
                    }
                }
                if (i == 0)
                {
                    string[] et    = line.Split('|');
                    Color    color = (Color)ColorConverter.ConvertFromString(et[2]);
                    Etiketa  novaE = new Etiketa(et[0], color, et[1], new SolidColorBrush(color));
                    ListaEtiketa.Etikete.Add(et[0], novaE);
                }
                else if (i == 1)
                {
                    string[]    et    = line.Split('|');
                    ImageSource slika = null;
                    slika = new BitmapImage(new Uri(et[3]));
                    TipManifestacije tipM = new TipManifestacije(et[0], et[1], et[2], slika);
                    ListaTipManifestacijecs.TipoviManifestacija.Add(et[0], tipM);
                }
                else
                {
                    bool          a = true;
                    Manifestacija m = null;
                    //line = sr.ReadLine();
                    while (a)
                    {
                        if (line == null)
                        {
                            ListaManifestacija.Manifestacije.Add(m.ID, m);
                            return;
                        }
                        string[] manif = line.Split('|');

                        ImageSource slika = null;
                        slika = new BitmapImage(new Uri(manif[10]));
                        TipManifestacije tipM  = ListaTipManifestacijecs.TipoviManifestacija[manif[11]];
                        string[]         koord = manif[15].Split(',');
                        Point            tacka = new Point(Double.Parse(koord[0]), Double.Parse(koord[1]));
                        m = new Manifestacija(manif[0], manif[1], manif[2], manif[3], manif[4], Boolean.Parse(manif[5]), Boolean.Parse(manif[6]), Boolean.Parse(manif[7]), int.Parse(manif[8]), manif[9], slika,
                                              tipM, tacka);
                        m.Etikete = new List <Etiketa>();
                        while ((line = sr.ReadLine()) != null)
                        {
                            if ((line.StartsWith(manif[0] + "#E")))
                            {
                                string[] l1  = line.Split('|');
                                Etiketa  et1 = ListaEtiketa.Etikete[l1[1]];
                                m.Etikete.Add(et1);
                            }
                            else
                            {
                                ListaManifestacija.Manifestacije.Add(m.ID, m);
                                break;
                            }
                        }
                    }
                }
            }
        }
Example #46
0
        public Piece(ImageSource imageSource, double x, double y, int rows, int columns, bool isShadow, int index, double scale)
        {
            int Width = (int)imageSource.Width / columns;
            int Height = (int)imageSource.Height / rows;

            this.ImageUri = imageUri;            
            this.X = x;
            this.Y = y;            
            this.Index = index;

            this.ScaleTransform = new ScaleTransform() { ScaleX = 1.0, ScaleY = 1.0 };
            
            path = new Path
            {
                Stroke = new SolidColorBrush(Colors.Gray),
                StrokeThickness = 0
            };      
            shadowPath = new Path
            {
                Stroke = new SolidColorBrush(Colors.Black),
                StrokeThickness = 2 * scale
            };          

            var imageScaleTransform = ScaleTransform;
            
            path.Fill = new ImageBrush//пазл замальовуватиметься частинами оригінльного зображення
            {
                ImageSource = imageSource,
                Stretch = Stretch.UniformToFill,               
                //viewport встановлює координати відрисування viewbox'a 
                Viewport = new Rect(0, 0, Width, Height),
                ViewportUnits = BrushMappingMode.Absolute,
                Viewbox = new Rect(//в залежності від того, що за пазл вирізається, йому надається вигляд замальовки
                    x * Width,
                    y * Height,
                    Width,
                    Height),
                ViewboxUnits = BrushMappingMode.Absolute,
                Transform = imageScaleTransform
            };
                       

            GeometryGroup gg = new GeometryGroup();
            gg.Children.Add(new RectangleGeometry(new Rect(0, 0, Width, Height)));                                
            path.Data = gg;
            shadowPath.Data = gg;

            var rt = new RotateTransform
            { 
                CenterX = 3,
                CenterY = 3,
                Angle = 0
            };

            tt1 = new TranslateTransform
            { 
                X = -1,
                Y = -1
            };                                  
            
            tg1.Children.Add(tt1);
            tg1.Children.Add(rt);

            path.RenderTransform = tg1;

            tt2 = new TranslateTransform()
            {
                X = -1,
                Y = -1
            };

            tg2.Children.Add(tt2);
            tg2.Children.Add(rt);

            shadowPath.RenderTransform = tg2;

                                
            this.Width = Width * scale;
            this.Height = Height * scale;

            if (isShadow)
                this.Children.Add(shadowPath);
            else
                this.Children.Add(path);    
        }                            
Example #47
0
 public async Task MockDatatest()
 {
     LoadingForyou = true;
     LoadingTopic = true;
     LoadingLatest = true;
     LoadingFollowing = true;
     LoadingHot = true;
     await Task.Delay(1000);
     ListData = new ObservableCollection<DataTest>()
       {
               new DataTest
               {
                   Title = "American Black Bear ttttttttttttttttttt",
                   BookmarkShow=true,
                   Expire= DateTime.Now,
                   Detail = "The American black bear is a medium-sized bear native to North America. It is the continent's smallest and most widely distributed bear species. American black bears are omnivores, with their diets varying greatly depending on season and Expire. They typically live in largely forested areas, but do leave forests in search of food. Sometimes they become attracted to human communities because of the immediate availability of food. The American black bear is the world's most common bear species.",
                   Image ="javascript96crop.png",
                   TopicName="Foods"
                   //Image = "https://upload.wikimedia.org/wikipedia/commons/0/08/01_Schwarzbär.jpg"
               },
               new DataTest
               {
                   Title = "Asian Black Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The Asian black bear, also known as the moon bear and the white-chested bear, is a medium-sized bear species native to Asia and largely adapted to arboreal life. It lives in the Himalayas, in the northern parts of the Indian subcontinent, Korea, northeastern China, the Russian Far East, the Honshū and Shikoku islands of Japan, and Taiwan. It is classified as vulnerable by the International Union for Conservation of Nature (IUCN), mostly because of deforestation and hunting for its body parts.",
                   //Image ="duck.jpg"
                   TopicName="Tech",
                   Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Ursus_thibetanus_3_%28Wroclaw_zoo%29.JPG/180px-Ursus_thibetanus_3_%28Wroclaw_zoo%29.JPG"))
               },
               new DataTest
               {
                   Title = "Brown Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The brown bear is a bear that is found across much of northern Eurasia and North America. In North America the population of brown bears are often called grizzly bears. It is one of the largest living terrestrial members of the order Carnivora, rivaled in size only by its closest relative, the polar bear, which is much less variable in size and slightly larger on average. The brown bear's principal range includes parts of Russia, Central Asia, China, Canada, the United States, Scandinavia and the Carpathian region, especially Romania, Anatolia and the Caucasus. The brown bear is recognized as a national and state animal in several European countries.",
                   //Image ="duck.jpg"
                   TopicName="HOT",
                   Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/Kamchatka_Brown_Bear_near_Dvuhyurtochnoe_on_2015-07-23.jpg/320px-Kamchatka_Brown_Bear_near_Dvuhyurtochnoe_on_2015-07-23.jpg"))
               },
               new DataTest
               {
                   Title = "Grizzly-Polar Bear Hybrid",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "A grizzly–polar bear hybrid is a rare ursid hybrid that has occurred both in captivity and in the wild. In 2006, the occurrence of this hybrid in nature was confirmed by testing the DNA of a unique-looking bear that had been shot near Sachs Harbour, Northwest Territories on Banks Island in the Canadian Arctic. The number of confirmed hybrids has since risen to eight, all of them descending from the same female polar bear.",
                   //Image ="duck.jpg"
                   Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/Grolar.JPG/276px-Grolar.JPG"))
               },
               new DataTest
               {
                   Title = "Sloth Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The sloth bear is an insectivorous bear species native to the Indian subcontinent. It is listed as Vulnerable on the IUCN Red List, mainly because of habitat loss and degradation. It has also been called labiated bear because of its long lower lip and palate used for sucking insects. Compared to brown and black bears, the sloth bear is lankier, has a long, shaggy fur and a mane around the face, and long, sickle-shaped claws. It evolved from the ancestral brown bear during the Pleistocene and through convergent evolution shares features found in insect-eating mammals.",
                   Image ="duck.jpg"
                   // Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Sloth_Bear_Washington_DC.JPG/320px-Sloth_Bear_Washington_DC.JPG"))
               },
               new DataTest
               {
                   Title = "Sun Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The sun bear is a bear species occurring in tropical forest habitats of Southeast Asia. It is listed as Vulnerable on the IUCN Red List. The global population is thought to have declined by more than 30% over the past three bear generations. Suitable habitat has been dramatically reduced due to the large-scale deforestation that has occurred throughout Southeast Asia over the past three decades. The sun bear is also known as the honey bear, which refers to its voracious appetite for honeycombs and honey.",
                    Image ="javascript96crop.png"
                   //Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Sitting_sun_bear.jpg/319px-Sitting_sun_bear.jpg"))
               },
               new DataTest
               {
                   Title = "Polar Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The polar bear is a hypercarnivorous bear whose native range lies largely within the Arctic Circle, encompassing the Arctic Ocean, its surrounding seas and surrounding land masses. It is a large bear, approximately the same size as the omnivorous Kodiak bear. A boar (adult male) weighs around 350–700 kg (772–1,543 lb), while a sow (adult female) is about half that size. Although it is the sister species of the brown bear, it has evolved to occupy a narrower ecological niche, with many body characteristics adapted for cold temperatures, for moving across snow, ice and open water, and for hunting seals, which make up most of its diet. Although most polar bears are born on land, they spend most of their time on the sea ice. Their scientific Title means maritime bear and derives from this fact. Polar bears hunt their preferred food of seals from the edge of sea ice, often living off fat reserves when no sea ice is present. Because of their dependence on the sea ice, polar bears are classified as marine mammals.",
                   Image ="duck.jpg"
                  // Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/6/66/Polar_Bear_-_Alaska_%28cropped%29.jpg"))
               },
               new DataTest
               {
                   Title = "Spectacled Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The spectacled bear, also known as the Andean bear or Andean short-faced bear and locally as jukumari (Aymara), ukumari (Quechua) or ukuku, is the last remaining short-faced bear. Its closest relatives are the extinct Florida spectacled bear, and the giant short-faced bears of the Middle to Late Pleistocene age. Spectacled bears are the only surviving species of bear native to South America, and the only surviving member of the subfamily Tremarctinae. The species is classified as Vulnerable by the IUCN because of habitat loss.",
                   Image ="duck.jpg"
                  // Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Spectacled_Bear_-_Houston_Zoo.jpg/264px-Spectacled_Bear_-_Houston_Zoo.jpg"))
               },
               new DataTest
               {
                   Title = "Short-faced Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The short-faced bears is an extinct bear genus that inhabited North America during the Pleistocene epoch from about 1.8 Mya until 11,000 years ago. It was the most common early North American bear and was most abundant in California. There are two recognized species: Arctodus pristinus and Arctodus simus, with the latter considered to be one of the largest known terrestrial mammalian carnivores that has ever existed. It has been hypothesized that their extinction coincides with the Younger Dryas period of global cooling commencing around 10,900 BC.",
                    Image ="duck.jpg"
                   //Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/ArctodusSimusSkeleton.jpg/320px-ArctodusSimusSkeleton.jpg"))
               },
               new DataTest
               {
                   Title = "California Grizzly Bear",
                   BookmarkShow=true,
                   Expire = DateTime.Now,
                   Detail = "The California grizzly bear is an extinct subspecies of the grizzly bear, the very large North American brown bear. Grizzly could have meant grizzled (that is, with golden and grey tips of the hair) or fear-inspiring. Nonetheless, after careful study, naturalist George Ord formally classified it in 1815 – not for its hair, but for its character – as Ursus horribilis (terrifying bear). Genetically, North American grizzlies are closely related; in size and coloring, the California grizzly bear was much like the grizzly bear of the southern coast of Alaska. In California, it was particularly admired for its beauty, size and strength. The grizzly became a symbol of the Bear Flag Republic, a moniker that was attached to the short-lived attempt by a group of American settlers to break away from Mexico in 1846. Later, this rebel flag became the basis for the state flag of California, and then California was known as the Bear State.",
                   Image ="duck.jpg"
                   // Image = ImageSource.FromUri(new Uri("https://upload.wikimedia.org/wikipedia/commons/d/de/Monarch_the_bear.jpg"))
               }
           };
    var ListDataTe = ListData.Select(d => new DataTest()
     {
         BookmarkShow=false,
         Detail=d.Detail,
         Expire=d.Expire,
         Image=d.Image,
         Title=d.Title
     }).ToList();
     this.ListDataTest = new ObservableCollection<DataTest>(ListDataTe);
     ListDataTop3 = new ObservableCollection<DataTest>();
     for (int i = 0; i < 3; i++)
     {
         ListDataTop3.Add(ListData[i]);
     }
     LoadingForyou = false;
     await Task.Delay(500);
     LoadingTopic = false;
     await Task.Delay(500);
     LoadingLatest = false;
     await Task.Delay(500); 
     LoadingHot = false;
     await Task.Delay(500);
     LoadingFollowing = false;
 }
Example #48
0
 private AchievementViewModel(IAchievement achievement, ImageSource image)
 {
     ItemTappedCommand = new Command(x => NavigateToAchievementDetails());
     Achievement       = achievement;
     Image             = image;
 }
Example #49
0
        /// <summary>
        /// 將圖片上傳到後端 Web API 主機上
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task 拍照與上傳(string action)
        {
            #region 拍照與上傳
            // https://github.com/jamesmontemagno/MediaPlugin
            // https://github.com/dsplaisted/PCLStorage
            // 進行 Plugin.Media 套件的初始化動作
            await CrossMedia.Current.Initialize();

            // 確認這個裝置是否具有拍照的功能
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await _dialogService.DisplayAlertAsync("No Camera", ":( No camera available.", "OK");

                return;
            }

            // 啟動拍照功能,並且儲存到指定的路徑與檔案中
            MediaFile file;
            if (action == "TakePhoto")
            {
                file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Directory          = "Sample",
                    Name               = "Sample.jpg",
                    CompressionQuality = 92,
                    PhotoSize          = Plugin.Media.Abstractions.PhotoSize.Full,
                });
            }
            else
            {
                file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
                {
                    CompressionQuality = 92,
                    PhotoSize          = PhotoSize.Full,
                });
            }
            if (file == null)
            {
                return;
            }


            // 讀取剛剛拍照的檔案內容,轉換成為 ImageSource,如此,就可以顯示到螢幕上了
            // 要這麼做的話,是因為圖片檔案是儲存在手機端的永久儲存體中,不是隨著專案安裝時候,就部署上去的
            // 因此,需要透過 ImageSource.FromStream 來讀取圖片檔案內容,產生出 ImageSource 物件,
            // 再透過資料繫節綁訂到 View 上的 Image 控制項
            MyImageSource = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                return(stream);
            });

            #region 將剛剛拍照的檔案,上傳到網路伺服器上

            using (UserDialogs.Instance.Loading($"請稍後,上傳照片中...", null, null, true, MaskType.Black))
            {
                fooAPIResult = await PCLGlobalHelper.foo使用者工作內容Repository.UploadImageAsync(file);
            }
            if (fooAPIResult.Success == true)
            {
                var fooUserTasks = UpdateUserTasks(CurrentUserTasksVM).Clone();
                fooUserTasks.Status   = Models.TaskStatus.UPLOAD_IMAGE;
                fooUserTasks.PhotoURL = fooAPIResult.Payload as string;
                using (UserDialogs.Instance.Loading($"請稍後,更新工作內容中...", null, null, true, MaskType.Black))
                {
                    fooAPIResult = await PCLGlobalHelper.foo使用者工作內容Repository.PutAsync(fooUserTasks);
                }
                if (fooAPIResult.Success == true)
                {
                    using (UserDialogs.Instance.Loading($"請稍後,取得該使用者的派工資料中...", null, null, true, MaskType.Black))
                    {
                        fooAPIResult = await PCLGlobalHelper.foo使用者工作內容Repository.GetDateRangeAsync(CurrentUserTasksVM.Account);
                    }

                    if (fooAPIResult.Success == true)
                    {
                        await ViewModelInit();

                        _eventAggregator.GetEvent <TaskRefreshEventEvent>().Publish(new TaskRefreshEventPayload
                        {
                            Account = CurrentUserTasksVM.Account,
                        });
                    }
                    else
                    {
                        await _dialogService.DisplayAlertAsync("警告", fooAPIResult.Message, "確定");
                    }
                }
                else
                {
                    await _dialogService.DisplayAlertAsync("警告", fooAPIResult.Message, "確定");
                }
            }
            else
            {
            }
            #endregion
            #endregion
        }
Example #50
0
        public MainWindow()
        {
            InitializeComponent();



            dt.Tick    += new EventHandler(dt_Tick);
            dt.Interval = new TimeSpan(0, 0, 0, 0, 1);

            sw.Start();
            dt.Start();


            //global vars
            Application.Current.Properties["Turn"] = 1;

            Application.Current.Properties["P1PawnsCaptured"]   = 0;
            Application.Current.Properties["P1KnightsCaptured"] = 0;
            Application.Current.Properties["P1BishopsCaptured"] = 0;
            Application.Current.Properties["P1RooksCaptured"]   = 0;
            Application.Current.Properties["P1QueensCaptured"]  = 0;
            Application.Current.Properties["P2PawnsCaptured"]   = 0;
            Application.Current.Properties["P2KnightsCaptured"] = 0;
            Application.Current.Properties["P2BishopsCaptured"] = 0;
            Application.Current.Properties["P2RooksCaptured"]   = 0;
            Application.Current.Properties["P2QueensCaptured"]  = 0;

            //Background color brushes
            Brush color1 = Brushes.White;
            Brush color2 = Brushes.Black;
            Brush color3 = Brushes.Red;

            //Player 1 pieces
            h1.Type = "P1Rook";
            g1.Type = "P1Knight";
            f1.Type = "P1Bishop";
            e1.Type = "P1King";
            d1.Type = "P1Queen";
            c1.Type = "P1Bishop";
            b1.Type = "P1Knight";
            a1.Type = "P1Rook";
            a2.Type = "P1Pawn";            b2.Type = "P1Pawn";            c2.Type = "P1Pawn";            d2.Type = "P1Pawn";
            e2.Type = "P1Pawn";            f2.Type = "P1Pawn";            g2.Type = "P1Pawn";            h2.Type = "P1Pawn";

            //Player 2 pieces
            a8.Type = "P2Rook";
            g8.Type = "P2Knight";
            f8.Type = "P2Bishop";
            e8.Type = "P2King";
            d8.Type = "P2Queen";
            c8.Type = "P2Bishop";
            b8.Type = "P2Knight";
            a8.Type = "P2Rook";
            h8.Type = "P2Rook";
            a7.Type = "P2Pawn";            b7.Type = "P2Pawn";            c7.Type = "P2Pawn";            d7.Type = "P2Pawn";
            e7.Type = "P2Pawn";            f7.Type = "P2Pawn";            g7.Type = "P2Pawn";            h7.Type = "P2Pawn";

            foreach (Chess.pieceButton button in board.Children)
            {
                //Set initial game pieces, resource names need to be bound to vars
                if (button.Type.Equals("P1Pawn"))
                {
                    img          = ((Image)this.Resources["P1Pawn"]).Source;
                    button.Image = img;
                    button.Text  = "pawn";
                }
                else if (button.Type.Equals("P1Rook"))
                {
                    img          = ((Image)this.Resources["P1Rook"]).Source;
                    button.Image = img;
                    button.Text  = "rook";
                }
                else if (button.Type.Equals("P2Rook"))
                {
                    img          = ((Image)this.Resources["P2Rook"]).Source;
                    button.Image = img;
                    button.Text  = "rook";
                }
                else if (button.Type.Equals("P2Pawn"))
                {
                    img          = ((Image)this.Resources["P2Pawn"]).Source;
                    button.Image = img;
                    button.Text  = "pawn";
                }
                else if (button.Type.Equals("P1Bishop"))
                {
                    img          = ((Image)this.Resources["P1Bishop"]).Source;
                    button.Image = img;
                    button.Text  = "bishop";
                }
                else if (button.Type.Equals("P2Bishop"))
                {
                    img          = ((Image)this.Resources["P2Bishop"]).Source;
                    button.Image = img;
                    button.Text  = "bishop";
                }
                else if (button.Type.Equals("P2Knight"))
                {
                    img          = ((Image)this.Resources["P2Knight"]).Source;
                    button.Image = img;
                    button.Text  = "knight";
                }
                else if (button.Type.Equals("P1Knight"))
                {
                    img          = ((Image)this.Resources["P1Knight"]).Source;
                    button.Image = img;
                    button.Text  = "knight";
                }
                else if (button.Type.Equals("P2Queen"))
                {
                    img          = ((Image)this.Resources["P2Queen"]).Source;
                    button.Image = img;
                    button.Text  = "queen";
                }
                else if (button.Type.Equals("P2King"))
                {
                    img          = ((Image)this.Resources["P2King"]).Source;
                    button.Image = img;
                    button.Text  = "king";
                }
                else if (button.Type.Equals("P1Queen"))
                {
                    img          = ((Image)this.Resources["P1Queen"]).Source;
                    button.Image = img;
                    button.Text  = "queen";
                }
                else if (button.Type.Equals("P1King"))
                {
                    img          = ((Image)this.Resources["P1King"]).Source;
                    button.Image = img;
                    button.Text  = "king";
                }

                //setup board
                letter = button.Name.Substring(0, 1);
                number = button.Name.Substring(1);
                if (((letter.Equals("a") || letter.Equals("c") || letter.Equals("e") || letter.Equals("g")) &&
                     (number.Equals("8") || number.Equals("6") || number.Equals("4") || number.Equals("2"))) ||
                    ((letter.Equals("b") || letter.Equals("d") || letter.Equals("f") || letter.Equals("h")) &&
                     (number.Equals("7") || number.Equals("5") || number.Equals("3") || number.Equals("1"))))
                {
                    button.BackgroundColor = color1;
                    button.originalColor   = color1;
                }
                else
                {
                    button.BackgroundColor = color2;
                    button.originalColor   = color2;
                }


                //start of game look, can be changed into start/load option before aneabling this

                button.Opacity = 0.75;

                if (button.Type.Contains("P1"))
                {
                    button.Opacity = 1.0;
                }
            }
        }
        private async void SetImageAndRun()
        {
            try
            {
                ResultIsVisible    = false;
                IndicatorIsRunning = true;
                ResultFontSize     = 16;
                var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);

                if (cameraStatus != PermissionStatus.Granted)
                {
                    var semaphore = new SemaphoreSlim(1, 1);
                    semaphore.Wait();
                    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Camera);

                    cameraStatus = results[Permission.Camera];
                    semaphore.Release();
                }
                if (cameraStatus == PermissionStatus.Granted)
                {
                    await CrossMedia.Current.Initialize();

                    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                    {
                        ResultText = ":( No camera available.";
                    }
                    else
                    {
                        var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                        {
                            Directory = "SampleDirectory",
                            Name      = "test.jpg"
                        });

                        if (file == null)
                        {
                            return;
                        }

                        ImageSource = ImageSource.FromFile(file.Path);
                        var temp = await MakePredictionRequest(file.Path);


                        Vision t = new Vision();
                        ResultText = await t.MakeSomeSummary(file.GetStream());



                        file.Dispose();
                    }
                }
                ResultIsVisible    = true;
                IndicatorIsRunning = false;
            }
            catch (Exception ex)
            {
                ResultIsVisible    = true;
                IndicatorIsRunning = false;
                ResultText         = ex.ToString();
            }
        }
Example #52
0
 public void SetImage(string path)
 {
     _image     = null;
     _imagePath = path;
     RaisePropertiesChanged("Image");
 }
Example #53
0
 public ImageSerializeModel(ViewModel viewmodel)
 {
     BroweImage1 = viewmodel.ModelList[0].Name;
     BroweImage2 = viewmodel.ModelList[1].Name;
     BroweImage3 = viewmodel.ModelList[2].Name;
 }
Example #54
0
 internal PicImpl(Size size, ImageSource imageSource)
 {
     Size = size;
     Source = imageSource;
 }
        public async void getReminder()
        {
            // Grab user ID to send as a get message for user reminders
            string userId = Preferences.Get("user_id", "no address found");

            // Set up new HttpClientHandler and its credentials so we can perform the web request
            HttpClientHandler clientHandler = new HttpClientHandler();

            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return(true); };

            // Create new httpClient using our client handler created above
            HttpClient httpClient = new HttpClient(clientHandler);

            String apiUrl     = "https://habitathomeownerbuddy.azurewebsites.net/api/MaintenanceReminderAPI/" + userId;
            String postApiUrl = "https://habitathomeownerbuddy.azurewebsites.net/api/MaintenanceReminderAPI";

            // Create new URI with the API url so we can perform the web request
            var uri = new Uri(string.Format(apiUrl, string.Empty));

            // Grab the current users information to call the post method for checking all user due dates
            MobileUsers user = new MobileUsers();

            user.FName = Preferences.Get("user_first_name", "no first name found");
            user.Lname = Preferences.Get("user_last_name", "no last name found");
            user.Code  = Preferences.Get("user_home_code", "no home code found");
            string regDate = DateTime.Today.ToString("MM/dd/yyyy");

            user.date = regDate;

            string JSONresult = JsonConvert.SerializeObject(user);

            Console.WriteLine(JSONresult);
            var content = new StringContent(JSONresult, Encoding.UTF8, "application/json");

            HttpResponseMessage postResponse = await httpClient.PostAsync(postApiUrl, content);

            // Check if the POST web request was successful
            if (postResponse.IsSuccessStatusCode)
            {
                // Get web request response and store it
                var getResponse = await httpClient.GetAsync(uri);

                // Check if the GET web request was successful
                if (getResponse.IsSuccessStatusCode)
                {
                    // Get the JSON object returned from the web request
                    var userContent = await getResponse.Content.ReadAsStringAsync();

                    var reminders = JsonConvert.DeserializeObject <List <ReminderModel> >(userContent);

                    ImageSource OverDueIcon = ImageSource.FromResource("HOB_Mobile.Resources.over_due.png");
                    ImageSource ToDoIcon    = ImageSource.FromResource("HOB_Mobile.Resources.to_do_icon.png");
                    ImageSource DoneIcon    = ImageSource.FromResource("HOB_Mobile.Resources.done_icon.png");

                    var OverDues = new List <ReminderModel>();
                    var ToDos    = new List <ReminderModel>();
                    var Dones    = new List <ReminderModel>();

                    foreach (ReminderModel reminder in reminders)
                    {
                        if (reminder.completed.Equals("Due"))
                        {
                            reminder.icon = ToDoIcon;
                            ToDos.Add(reminder);
                        }
                        else if (reminder.completed.Equals("Completed"))
                        {
                            reminder.icon = DoneIcon;
                            Dones.Add(reminder);
                        }
                        else if (reminder.completed.Equals("Overdue"))
                        {
                            reminder.icon = OverDueIcon;
                            OverDues.Add(reminder);
                        }
                        else
                        {
                            // Not in season so don't display
                        }
                    }

                    OverDues = OverDues.OrderBy(o => o.dueDate).ToList();

                    ToDos = ToDos.OrderBy(td => td.dueDate).ToList();

                    Dones = Dones.OrderByDescending(d => d.lastCompleted).ToList();

                    if (OverDues.Count.Equals(0))
                    {
                        pastdues.Text = "You have no overdue tasks";
                        OverDueFrame.HeightRequest = 10;
                    }
                    else
                    {
                        OverDue.ItemsSource = OverDues;
                    }

                    if (ToDos.Count.Equals(0))
                    {
                        todos.Text = "You have no maintenance tasks to do";
                        ToDoFrame.HeightRequest = 10;
                    }
                    else
                    {
                        ToDo.ItemsSource = ToDos;
                    }

                    if (Dones.Count.Equals(0))
                    {
                        finished.Text           = "You haven't done any maintenance tasks yet";
                        DoneFrame.HeightRequest = 10;
                    }
                    else
                    {
                        Done.ItemsSource = Dones;
                    }
                }
                else
                {
                    // This prints to the Visual Studio Output window
                    Debug.WriteLine("Response not successful");
                }
            }
            else
            {
                // This prints to the Visual Studio Output window
                Debug.WriteLine("Response not successful");
            }
        }
        internal static MasterSessionModel GetMasterMock(string name, int volume, bool muteState, ImageSource imageSource)
        {
            var sessionVolumeMock   = new Mock <IAudioSessionVolume>();
            var masterVolumeHandler = new Mock <IMasterVolumeNotificationHandler>();

            return(new MasterSessionModel
                       (name, name, volume, muteState,
                       imageSource, sessionVolumeMock.Object, masterVolumeHandler.Object));
        }
Example #57
0
        public async Task <ObservableCollection <CompanyModel> > GetCompany()
        {
            try
            {
                //string ftpServerIP = "115.115.196.30";
                //string ftpUserID = "suvendu";
                //string ftpPassword = "******";

                //string filename = "ftp://" + ftpServerIP + "//Upload//";



                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(GlobalData.gblApiAdress);
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                //response = client.GetAsync("api/CompanyAPI/GetCompany?id=" + Id + "").Result;
                response = client.GetAsync("api/CompanyAPI/GetCompany").Result;
                if (response.IsSuccessStatusCode)
                {
                    data        = JsonConvert.DeserializeObject <CompanyModel[]>(await response.Content.ReadAsStringAsync());
                    CompanyData = new List <CompanyModel>();
                    for (int i = 0; i < data.Length; i++)
                    {
                        int    croId     = Convert.ToInt32(data[i].COMPANY_ID);
                        string NAME      = data[i].NAME;
                        string ADDRESS_1 = data[i].ADDRESS_1;
                        string ADDRESS_2 = data[i].ADDRESS_2;
                        string CITY      = data[i].CITY;
                        SelectedCompany.NAME = data[i].NAME;;
                        _ListGrid_Temp.Add(new CompanyModel
                        {
                            ADDRESS_1 = ADDRESS_1,
                            NAME      = NAME,
                            CITY      = CITY,
                            ADDRESS_2 = ADDRESS_2,
                        });
                        App.Current.Properties["Company_Id"]       = Convert.ToInt32(data[i].COMPANY_ID);
                        App.Current.Properties["Company_Name"]     = data[i].NAME;
                        App.Current.Properties["Company_Email"]    = data[i].EMAIL;
                        App.Current.Properties["Company_Address1"] = data[i].ADDRESS_1;
                        App.Current.Properties["Company_Address2"] = data[i].ADDRESS_2;
                        App.Current.Properties["Company_Mobile"]   = data[i].MOBILE_NUMBER;
                        App.Current.Properties["Company_Phone"]    = data[i].PHONE_NUMBER;
                        App.Current.Properties["Company_Pin"]      = data[i].PIN;


                        if (data[i].IMAGE_PATH != null)
                        {
                            //var fr = filename + data[i].IMAGE_PATH;

                            //var imageFile = new System.IO.FileInfo(data[i].IMAGE_PATH);
                            //string file = imageFile.Name;
                            var applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);


                            // get your 'Uploaded' folder
                            var dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(applicationPath, "uploaded"));
                            //if (!dir.Exists)
                            //    dir.Create();
                            // Copy file to your folder
                            //imageFile.CopyTo(System.IO.Path.Combine(dir.FullName, file), true);
                            string path1 = System.IO.Path.Combine(dir.FullName + "\\", data[i].IMAGE_PATH);

                            // FtpDown(path1, file);

                            IMAGE_PATH1 = new BitmapImage(new Uri(path1));
                            //App.Current.Properties["ItemViewImg"] = IMAGE_PATH1;
                        }
                    }
                }
                //ListGrid = _ListGrid_Temp;
                //return new ObservableCollection<CompanyModel>(_ListGrid_Temp);
            }
            catch (Exception ex)
            {
            }
            ListGrid = _ListGrid_Temp;
            return(new ObservableCollection <CompanyModel>(_ListGrid_Temp));
        }
Example #58
0
        private static void ImageLocationPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var speakerControl = (ViewItemCustomControl)bindable;

            speakerControl.ImageControl.Source = ImageSource.FromFile((string)newValue);
        }
Example #59
0
        public JobListItemCell()
        {
            StyleId = "disclosure";

            Image = new Image();
            Image.Source = ImageSource.FromFile("floorplan.jpg");

            NameLabel = new Label()
            {
                FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                VerticalTextAlignment = TextAlignment.Center,
                LineBreakMode = LineBreakMode.TailTruncation
            };
            NameLabel.SetBinding(
                Label.TextProperty,
                new Binding("Name"));

            StatusLabel = new Label()
            {
                TextColor = Color.Silver,
                FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)),
                VerticalTextAlignment = TextAlignment.Center,
                HorizontalTextAlignment = TextAlignment.End,
                LineBreakMode = LineBreakMode.TailTruncation,
            };
            StatusLabel.SetBinding(
                Label.TextProperty,
                new Binding("Status"));

            CreateTimeLabel = new Label()
            {
                TextColor = Color.Silver,
                FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
                VerticalTextAlignment = TextAlignment.Center,
                HorizontalTextAlignment = TextAlignment.End,
                LineBreakMode = LineBreakMode.TailTruncation
            };
            //CreateTimeLabel.SetBinding(
            //    Label.TextProperty,
            //    new Binding(path: "CreateTime",stringFormat:"g"));

            LocationLabel = new Label()
            {
                TextColor = Color.Silver,
                FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)),
                VerticalTextAlignment = TextAlignment.Start,
                LineBreakMode = LineBreakMode.WordWrap,
            };
            //LocationLabel.SetBinding(
            //    Label.TextProperty,
            //    new Binding("Location"));

            var contentView = new ContentView();
            contentView.Padding = new Thickness(8, 8, 16, 0);

            RelativeLayout layout = new RelativeLayout();

            layout.Children.Add(
                view: Image,
                xConstraint: Constraint.RelativeToParent(parent => 0),
                yConstraint: Constraint.RelativeToParent(parent => 0),
                widthConstraint: Constraint.RelativeToParent(parent => parent.Height),
                heightConstraint: Constraint.RelativeToParent(parent => parent.Height));

            layout.Children.Add(
                view:NameLabel,
                xConstraint: Constraint.RelativeToView(Image, (rl, v) => v.Bounds.Right + margin),
                yConstraint: Constraint.RelativeToParent(parent => 0),
                widthConstraint: Constraint.RelativeToView(Image, (rl, v) => rl.Width - v.Width - rightWidth),
                heightConstraint: Constraint.RelativeToParent(parent => parent.Height / 2));


            layout.Children.Add(
                view: StatusLabel,
                xConstraint: Constraint.RelativeToParent(parent => parent.Bounds.Right - rightWidth),
                yConstraint: Constraint.RelativeToParent(parent => 0),
                widthConstraint: Constraint.RelativeToParent(parent => rightWidth),
                heightConstraint: Constraint.RelativeToParent(parent => parent.Height / 2));


            layout.Children.Add(
                view: LocationLabel,
                xConstraint: Constraint.RelativeToView(Image, (rl, v) => v.Bounds.Right + margin),
                yConstraint: Constraint.RelativeToParent(parent => parent.Height / 2),
                widthConstraint: Constraint.RelativeToView(Image, (rl, v) => rl.Width - v.Width - 120),
                heightConstraint: Constraint.RelativeToParent(parent => parent.Height / 2));

            layout.Children.Add(
                view: CreateTimeLabel,
                xConstraint: Constraint.RelativeToParent(parent => parent.Bounds.Right - 120),
                yConstraint: Constraint.RelativeToParent(parent => parent.Height / 2),
                widthConstraint: Constraint.RelativeToParent(parent => 120),
                heightConstraint: Constraint.RelativeToParent(parent => parent.Height / 2));

            // Assign the relativeLayout to Content of contentView
            // This lets us take advantage of ContentView's padding.
            contentView.Content = layout;

            // assign contentView to the View property
            View = contentView;
        }
Example #60
0
        private async void ChangeImageMethod()
        {
            await CrossMedia.Current.Initialize();

            if (CrossMedia.Current.IsCameraAvailable &&
                CrossMedia.Current.IsTakePhotoSupported)
            {
                var source = await Application.Current.MainPage.DisplayActionSheet(
                    "¿De donde quieres tomar la imagen?",
                    "Cancelar",
                    null,
                    "Desde la galería",
                    "Desde la cámara");

                if (source == "Cancelar")
                {
                    this.file = null;
                    return;
                }

                if (source == "Desde la cámara")
                {
                    try
                    {
                        this.file = await CrossMedia.Current.TakePhotoAsync(
                            new StoreCameraMediaOptions
                        {
                            Directory = "Sample",
                            Name      = "test.jpg",
                            PhotoSize = PhotoSize.Small,
                        }
                            );
                    }
                    catch (Exception ex)
                    {
                        await Application.Current.MainPage.DisplayAlert(
                            "Mensaje",
                            "No tienes permisos! Ve a los ajustes de la aplicacion, y habilita la camara.",
                            "Ok");

                        return;
                    }
                }
                else
                {
                    try
                    {
                        this.file = await CrossMedia.Current.PickPhotoAsync();
                    }
                    catch (Exception ex)
                    {
                        await Application.Current.MainPage.DisplayAlert(
                            "Mensaje",
                            "No tienes permisos! Ve a los ajustes de la aplicacion, y habilita la camara.",
                            "Ok");

                        return;
                    }
                }
            }
            else
            {
                try
                {
                    this.file = await CrossMedia.Current.PickPhotoAsync();
                }
                catch (Exception ex)
                {
                    await Application.Current.MainPage.DisplayAlert(
                        "Mensaje",
                        "No tienes permisos! Ve a los ajustes de la aplicacion, y habilita la camara.",
                        "Ok");

                    return;
                }
            }

            if (this.file != null)
            {
                this.ImageSource = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    return(stream);
                });
            }
        }