public GoalsMainPage()
        {

            NavigationPage.SetHasNavigationBar(this, false);
            masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
            progressBar = DependencyService.Get<IProgressBar>();


            this.Appearing += OnAppearing;
			mainTitleBar = new GemsPageTitleBar(Color.FromRgb(8, 135, 224), "Goals & Dreams", Color.White, "", true);
            mainTitleBar.imageAreaTapGestureRecognizer.Tapped += OnImageAreaTapGestureRecognizerTapped;


            masterScroll = new ScrollView();
            masterScroll.WidthRequest = App.screenWidth - 20;
            masterScroll.HeightRequest = App.screenHeight * 85 / 100;
            masterScroll.BackgroundColor = Color.FromRgb( 244, 244, 244 );
			masterScroll.IsClippedToBounds = true;

            masterStack = new StackLayout();
            masterStack.Orientation = StackOrientation.Vertical;
            masterStack.BackgroundColor = Color.FromRgb(244, 244, 244);
            masterStack.Spacing = 0;
            //masterStack.Padding = new Thickness( 10, 10, 10, 10 );




        }
        public ApplicationSettingsPage()
        {

            NavigationPage.SetHasNavigationBar(this, false);
            masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            screenWidth = App.screenWidth;
            mainTitleBar = new PurposeColorTitleBar(Color.FromRgb(8, 135, 224), "Purpose Color", Color.Black, "back", true);
            mainTitleBar.imageAreaTapGestureRecognizer.Tapped += imageAreaTapGestureRecognizer_Tapped;
            subTitleBar = new PurposeColorBlueSubTitleBar(Constants.SUB_TITLE_BG_COLOR, "Application Settings",false, true);

            subTitleBar.BackButtonTapRecognizer.Tapped += (s, e) =>
            {
                App.masterPage.IsPresented = !App.masterPage.IsPresented;
            };
            progressBar = DependencyService.Get<IProgressBar>();

            signOutButton = new Button
            {
                Text = "Sign out",
                TextColor = Color.White,
                BorderColor = Color.Transparent,
                BorderWidth = 0,
                BackgroundColor = Constants.BLUE_BG_COLOR
            };

			profileButton = new Button
			{
				Text = "Profile settings",
				TextColor = Color.White,
				BorderColor = Color.Transparent,
				BorderWidth = 0,
				BackgroundColor = Constants.BLUE_BG_COLOR
			};

            changePassword = new Button
            {
                Text = "Change password",
                TextColor = Color.White,
                BorderColor = Color.Transparent,
                BorderWidth = 0,
                BackgroundColor = Constants.BLUE_BG_COLOR
            };

            signOutButton.WidthRequest = screenWidth * 80 / 100;
            changePassword.WidthRequest = screenWidth * 80 / 100;
			profileButton.WidthRequest = screenWidth * 80 / 100;

            masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
            masterLayout.AddChildToLayout(subTitleBar, 0, Device.OnPlatform(9, 10, 10));
			masterLayout.AddChildToLayout(profileButton, 10, 20);
			masterLayout.AddChildToLayout(changePassword, 10, Device.OnPlatform(30, 30,28));
			//masterLayout.AddChildToLayout( signOutButton, 10, Device.OnPlatform(40, 40,38));
            signOutButton.Clicked += OnSignOutButtonClicked;
            changePassword.Clicked += ChangePassword_Clicked;
			profileButton.Clicked += ProfileButton_Clicked;

            Content = masterLayout;
        }
		private void DownloadJsonDefinitions(Specification spec, IProgressBar pbar)
		{
			using (var client = new WebClient())
			{
				var html = client.DownloadString(spec.GithubListingUrl);
				FindJsonFilesOnListing(spec, html, pbar);
			}
		}
		private void WriteEndpointFile(Specification spec, string s, IProgressBar pbar)
		{
			var rawFile = spec.GithubDownloadUrl(s);
			using (var client = new WebClient())
			{
				var fileName = rawFile.Split('/').Last();
				var json = client.DownloadString(rawFile);
				WriteToEndpointsFolder(spec.FolderOnDisk, fileName, json);
				pbar.Tick($"Downloading {fileName}");
			}
		}
Esempio n. 5
0
        public void AddItem(string item, string name, IProgressBar progress)
        {
            if (Running) throw new Exception("Resource Downloader was already started.");

            string resourceUrl = UrlResourceName(category, item, name);

            Downloader downloader = new Downloader();
            downloader.Open("GET", new Uri(resourceUrl, UriKind.RelativeOrAbsolute));

            Descriptor descriptor = new Descriptor(this, downloader, progress);
            descriptors.Add(resourceUrl, descriptor);
        }
		private void FindJsonFilesOnListing(Specification spec, string html, IProgressBar pbar)
		{
			if (!Directory.Exists(CodeConfiguration.RestSpecificationFolder)) Directory.CreateDirectory(CodeConfiguration.RestSpecificationFolder);

			var dom = CQ.Create(html);

			WriteToEndpointsFolder(spec.FolderOnDisk, "root.html", html);

			var endpoints = dom[".js-navigation-open"]
				.Select(s => s.InnerText)
				.Where(s => !string.IsNullOrEmpty(s) && s.EndsWith(".json"))
				.ToList();

			using (var subBar = pbar.Spawn(endpoints.Count, "fetching individual json files", SubProgressBarOptions))
				endpoints.ForEach(s => WriteEndpointFile(spec, s, subBar));
		}
Esempio n. 7
0
        /// <summary>
        /// Сархивировать файлы в MemoryStream
        /// </summary>
        /// <param name="attachments">Список файлов</param>
        /// <returns>Поток данных</returns>
        public static MemoryStream CreateZipAttachement(List<string> attachments)
        {
            _progressZip = FormProgressBar.GetInstance ("Packing log file...");
            MemoryStream st = new MemoryStream ();
            ZipFile zip = new ZipFile ();

            lock (_progressZip) {
                foreach (string file in attachments)
                    try {
                        zip.AddFile (file, "");
                    } catch {
                    }
                _progressZip.ShowProgressBar (delegate() {
                    zip.Save (st); });
            }

            _progressZip.Dispose ();
            _progressZip = null;
            return st;
        }
Esempio n. 8
0
        async Task <Tuple <bool, ImportStats> > ProcessSetlistPage(Artist artist, HttpResponseMessage res, PerformContext ctx, IProgressBar prog)
        {
            var body = await res.Content.ReadAsStringAsync();

            Relisten.Vendor.SetlistFm.SetlistsRootObject root = null;
            try
            {
                root = JsonConvert.DeserializeObject <Relisten.Vendor.SetlistFm.SetlistsRootObject>(
                    body,
                    new Vendor.SetlistFm.TolerantListConverter <Vendor.SetlistFm.Song>(),
                    new Vendor.SetlistFm.TolerantListConverter <Vendor.SetlistFm.Set>(),
                    new Vendor.SetlistFm.TolerantListConverter <Vendor.SetlistFm.Setlist>(),
                    new Vendor.SetlistFm.TolerantSetsConverter()
                    );
            }
            catch (JsonReaderException e)
            {
                ctx?.WriteLine("Failed to parse {0}:\n{1}", res.RequestMessage.RequestUri.ToString(), body);
                throw e;
            }

            var stats = new ImportStats();

            var count = 1;

            foreach (var setlist in root.setlist)
            {
                if (setlist.sets.set.Count > 0)
                {
                    Stopwatch s = new Stopwatch();
                    s.Start();

                    // ctx?.WriteLine("Indexing setlist: {0}/{1}...", artist.name, setlist.eventDate);

                    try
                    {
                        var thisStats = await ProcessSetlist(artist, setlist);

                        s.Stop();
                        // ctx?.WriteLine("...success in {0}! Stats: {1}", s.Elapsed, thisStats);

                        stats += thisStats;
                    }
                    catch (Exception e)
                    {
                        s.Stop();
                        ctx?.WriteLine("{0}/{1}...failed in {2}! Stats: {3}", artist.name, setlist.eventDate, s.Elapsed, e.Message);

                        throw e;
                    }

                    prog?.SetValue(((100.0 * (root.page - 1) * root.itemsPerPage) + count * 1.0) / root.total);

                    count++;
                }
            }

            var hasMorePages = root.page < Math.Ceiling(1.0 * root.total / root.itemsPerPage);

            return(new Tuple <bool, ImportStats>(hasMorePages, stats));
        }
Esempio n. 9
0
        /// <summary>
        /// Import Equipment Attachments
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="fileLocation"></param>
        /// <param name="systemId"></param>
        public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId)
        {
            // check the start point. If startPoint == sigId then it is already completed
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BcBidImport.SigId, NewTable);

            if (startPoint == BcBidImport.SigId)    // This means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***");
                return;
            }

            int maxEquipAttachIndex = 0;

            if (dbContext.HetEquipmentAttachment.Any())
            {
                maxEquipAttachIndex = dbContext.HetEquipmentAttachment.Max(x => x.EquipmentAttachmentId);
            }

            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                // create progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer ser                      = new XmlSerializer(typeof(ImportModels.EquipAttach[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream             = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                ImportModels.EquipAttach[] legacyItems = (ImportModels.EquipAttach[])ser.Deserialize(memoryStream);

                int ii = startPoint;

                // skip the portion already processed
                if (startPoint > 0)
                {
                    legacyItems = legacyItems.Skip(ii).ToArray();
                }

                Debug.WriteLine("Importing Equipment Attachment Data. Total Records: " + legacyItems.Length);

                foreach (ImportModels.EquipAttach item in legacyItems.WithProgress(progress))
                {
                    // see if we have this one already. We used old combine because item.Equip_Id is not unique
                    string oldKeyCombined = (item.Equip_Id ?? 0 * 100 + item.Attach_Seq_Num ?? 0).ToString();

                    HetImportMap importMap = dbContext.HetImportMap.AsNoTracking()
                                             .FirstOrDefault(x => x.OldTable == OldTable &&
                                                             x.OldKey == oldKeyCombined);

                    // new entry
                    if (importMap == null && item.Equip_Id > 0)
                    {
                        HetEquipmentAttachment instance = null;
                        CopyToInstance(dbContext, item, ref instance, systemId, ref maxEquipAttachIndex);
                        ImportUtility.AddImportMap(dbContext, OldTable, oldKeyCombined, NewTable, instance.EquipmentAttachmentId);
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    if (++ii % 1000 == 0)
                    {
                        try
                        {
                            ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, ii.ToString(), BcBidImport.SigId, NewTable);
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                try
                {
                    performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                    ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BcBidImport.SigId.ToString(), BcBidImport.SigId, NewTable);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    string temp = string.Format("Error saving data (EquipmentAttachmentIndex: {0}): {1}", maxEquipAttachIndex, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
		async void DetailsTapgesture_Tapped (object sender, EventArgs e)
		{
			try {
				if(progressBar == null)
				progressBar = DependencyService.Get<IProgressBar>();

				progressBar.ShowProgressbar("Retriving details");

				string btnId = "0";

				try {
					var senderType = sender.GetType();
					if (senderType == typeof(CustomLayout))
					{
						btnId = (sender as CustomLayout).ClassId;
					}
					else if(senderType == typeof(Image))
					{
						btnId = (sender as Image).ClassId;
					}
					else if(senderType == typeof(StackLayout))
					{
						btnId = (sender as StackLayout).ClassId;
					}
				} catch (Exception ) {
					
				}

				if(btnId == "0")
				{
					progressBar.HideProgressbar();
					return;
				}
				selectedGem = btnId;

				if (App.isEmotionsListing) {
					try {
						SelectedEventDetails eventDetails = await ServiceHelper.GetSelectedEventDetails(btnId);
						if (eventDetails != null)
						{

							List<string> listToDownload = new List<string>();

							foreach (var eventi in eventDetails.event_media) 
							{
								if(string.IsNullOrEmpty(eventi.event_media))
								{
									continue;
								}

								if (eventi.media_type == "png" || eventi.media_type == "jpg" || eventi.media_type == "jpeg") 
								{

									listToDownload.Add(Constants.SERVICE_BASE_URL+eventi.event_media);
									string fileName = System.IO.Path.GetFileName(eventi.event_media);
									eventi.event_media = App.DownloadsPath + fileName;
								}
								else
								{
									eventi.event_media = Constants.SERVICE_BASE_URL + eventi.event_media ;
								}
							}

							if (listToDownload != null && listToDownload.Count > 0) {
								IDownload downloader = DependencyService.Get<IDownload>();
								//progressBar.ShowProgressbar("loading details..");
								await downloader.DownloadFiles(listToDownload);

							}

							DetailsPageModel model = new DetailsPageModel();
							model.actionMediaArray = null;
							model.eventMediaArray = eventDetails.event_media;
							model.goal_media = null;
							model.Media = null;
							model.NoMedia = null;
							model.pageTitleVal = "Event Details";
							model.titleVal = eventDetails.event_title;
							model.description = eventDetails.event_details;
							model.gemType = GemType.Event;
							model.gemId = btnId;
							if (progressBar != null) {
								progressBar.HideProgressbar();
							}
							isLoadingFromDetailsPage = true;

							await Navigation.PushAsync(new GemsDetailsPage(model));
							eventDetails = null;
						}
					} catch (Exception ) {
						
					}
				}
				else
				{
					//-- call service for Action details
					try {

						SelectedActionDetails actionDetails = await ServiceHelper.GetSelectedActionDetails(btnId);

						List<string> listToDownload = new List<string>();

						foreach (var action in actionDetails.action_media) 
						{
							if( string.IsNullOrEmpty(action.action_media))
							{
								continue;
							}

							if (action.media_type == "png" || action.media_type == "jpg" || action.media_type == "jpeg")
							{

								listToDownload.Add(Constants.SERVICE_BASE_URL+action.action_media);
								string fileName = System.IO.Path.GetFileName(action.action_media);
								action.action_media = App.DownloadsPath + fileName;
							}
							else
							{
								action.action_media = Constants.SERVICE_BASE_URL + action.action_media;
							}
						}

						if (listToDownload != null && listToDownload.Count > 0) {
							IDownload downloader = DependencyService.Get<IDownload>();
							//progressBar.ShowProgressbar("loading details..");
							await downloader.DownloadFiles(listToDownload);
							//progressBar.HideProgressbar();
						}

						if (actionDetails != null) {
							DetailsPageModel model = new DetailsPageModel();
							model.actionMediaArray = actionDetails.action_media;
							model.eventMediaArray = null;
							model.goal_media = null;
							model.Media = null;
							model.NoMedia = null;
							model.pageTitleVal = "Action Details";
							model.titleVal = actionDetails.action_title;
							model.description = actionDetails.action_details;
							model.gemType = GemType.Action;
							model.gemId = btnId;
							if (progressBar != null) {
								progressBar.HideProgressbar();
							}
							isLoadingFromDetailsPage = true;

							await Navigation.PushAsync(new GemsDetailsPage(model));
							actionDetails = null;
						}
					} catch (Exception ) {
						
					}
				}
				progressBar.HideProgressbar();
			}
			catch (Exception ex)
			{
				if (progressBar != null) {
					progressBar.HideProgressbar();
				}
				var test = ex.Message;
			}
		}
 public void Dispose()
 {
     masterLayout = null;
     progressBar = null;
     listContainer = null;
     gemsList = null;
     mainTitleBar = null;
     masterScroll = null;
     masterStack = null;
     headingLayout = null;
     gemsGoalsObject = null;
     pendingGoalsObject = null;
     GC.Collect();
 }
Esempio n. 12
0
        /// <summary>
        /// Import Local Areas
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="fileLocation"></param>
        /// <param name="systemId"></param>
        public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId)
        {
            // check the start point. If startPoint ==  sigId then it is already completed
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BCBidImport.SigId);

            if (startPoint == BCBidImport.SigId)    // this means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***");
                return;
            }

            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                // create Processer progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer       ser          = new XmlSerializer(typeof(ImportModels.Area[]), new XmlRootAttribute(rootAttr));
                MemoryStream        memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                ImportModels.Area[] legacyItems  = (ImportModels.Area[])ser.Deserialize(memoryStream);

                int ii = startPoint;

                // skip the portion already processed
                if (startPoint > 0)
                {
                    legacyItems = legacyItems.Skip(ii).ToArray();
                }

                foreach (Area item in legacyItems.WithProgress(progress))
                {
                    LocalArea localArea = null;

                    // see if we have this one already
                    ImportMap importMap = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == OldTable && x.OldKey == item.Area_Id.ToString());

                    if (dbContext.LocalAreas.Count(x => String.Equals(x.Name, item.Area_Desc.Trim(), StringComparison.CurrentCultureIgnoreCase)) > 0)
                    {
                        localArea = dbContext.LocalAreas.FirstOrDefault(x => x.Name.ToUpper() == item.Area_Desc.Trim().ToUpper());
                    }

                    // new entry
                    if (importMap == null || dbContext.LocalAreas.Count(x => String.Equals(x.Name, item.Area_Desc.Trim(), StringComparison.CurrentCultureIgnoreCase)) == 0)
                    {
                        if (item.Area_Id > 0)
                        {
                            CopyToInstance(dbContext, item, ref localArea, systemId);
                            ImportUtility.AddImportMap(dbContext, OldTable, item.Area_Id.ToString(), NewTable, localArea.Id);
                        }
                    }
                    else // update
                    {
                        localArea = dbContext.LocalAreas.FirstOrDefault(x => x.Id == importMap.NewKey);

                        // record was deleted
                        if (localArea == null)
                        {
                            CopyToInstance(dbContext, item, ref localArea, systemId);

                            // update the import map
                            importMap.NewKey = localArea.Id;
                            dbContext.ImportMaps.Update(importMap);
                        }
                        else // ordinary update
                        {
                            CopyToInstance(dbContext, item, ref localArea, systemId);

                            // touch the import map
                            importMap.LastUpdateTimestamp = DateTime.UtcNow;
                            dbContext.ImportMaps.Update(importMap);
                        }
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    if (++ii % 250 == 0)
                    {
                        try
                        {
                            ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, ii.ToString(), BCBidImport.SigId);
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                try
                {
                    performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                    ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BCBidImport.SigId.ToString(), BCBidImport.SigId);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    performContext.WriteLine("Error saving data " + e.Message);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
            }
        }
		async void GoalsListingBtnTapgesture_Tapped (object sender, EventArgs e)
		{
			try {
				if (!App.isEmotionsListing) {
					return;
				}
				if (progressBar == null) {
					progressBar = DependencyService.Get<IProgressBar>();
				}

				progressBar.ShowProgressbar ("Loading gems..");

				if (actionsWithImage == null) 
				{
					actionsWithImage = await ServiceHelper.GetAllActionsWithImage ();

					if (actionsWithImage == null) 
					{
						var success = await DisplayAlert (Constants.ALERT_TITLE, "Error in fetching GEMS", Constants.ALERT_OK, Constants.ALERT_RETRY);
						if (!success) {
							GoalsListingBtnTapgesture_Tapped(goalsButton, null);
							return;
						}
						else 
						{
							if (Device.OS != TargetPlatform.WinPhone)
							{
								actionsWithImage = await App.Settings.GetAllActionWithImage();
							}
						}
					}
					else
					{
						if (Device.OS != TargetPlatform.WinPhone)
						{
							await App.Settings.SaveActionsWithImage(actionsWithImage);
						}
					}
				}
				progressBar.HideProgressbar ();
				// do list the actions.....//
				bool isSuccess = await AddActionsToView(0, true);
				if (isSuccess) 
				{
					App.isEmotionsListing = false;
					await masterScroll.ScrollToAsync(0,0, true);
					#region button color
					// hide emotions & show goals , change selection buttons color
					Color goalBtnClr = goalsButton.BackgroundColor;
					goalsButton.BackgroundColor = emotionsButtion.BackgroundColor;
					emotionsButtion.BackgroundColor = goalBtnClr;
					Color golsTxtClr = goalsAndDreamsLabel.TextColor;
					goalsAndDreamsLabel.TextColor = emotionLabel.TextColor;
					emotionLabel.TextColor = golsTxtClr;
					#endregion
				}

			} catch (Exception ex) {
				var test = ex.Message;
				progressBar.HideProgressbar ();
			}

		}
        public FeelingsSecondPage()
        {
            progressBar = DependencyService.Get<IProgressBar>();
            NavigationPage.SetHasNavigationBar(this, false);
            masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
            //deviceSpec = DependencyService.Get<IDeviceSpec>();
			AddEventsSituationsOrThoughts.feelingSecondPage = this;
            this.Appearing += FeelingsSecondPage_Appearing;
            actionPreviewListSource = new ObservableCollection<PreviewItem>();

            mainTitleBar = new PurposeColorTitleBar(Color.FromRgb(8, 135, 224), "Purpose Color", Color.Black, "back", true);
            mainTitleBar.imageAreaTapGestureRecognizer.Tapped += imageAreaTapGestureRecognizer_Tapped;

            subTitleBar = new PurposeColorSubTitleBar(Constants.SUB_TITLE_BG_COLOR, "Emotional Awareness");
            subTitleBar.BackButtonTapRecognizer.Tapped += OnBackButtonTapRecognizerTapped;
            subTitleBar.NextButtonTapRecognizer.Tapped += NextButtonTapRecognizer_Tapped;
            screenHeight = App.screenHeight;
            screenWidth = App.screenWidth;
			aePicker = null;
			actionlist = null;

            Label firstLine = new Label();
            firstLine.Text = "Does being";
            firstLine.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            firstLine.TextColor = Color.FromRgb(40, 47, 50);
            firstLine.HeightRequest = screenHeight * 15 / 100;
            firstLine.HorizontalOptions = LayoutOptions.Center;
            firstLine.WidthRequest = screenWidth;
            firstLine.XAlign = TextAlignment.Center;

            Label secondLine = new Label();
            secondLine.Text = App.SelectedEmotion;
            secondLine.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            secondLine.FontAttributes = FontAttributes.Italic;
            secondLine.TextColor = Constants.BLUE_BG_COLOR;//Color.FromRgb(40, 47, 50);
            secondLine.HeightRequest = screenHeight * 15 / 100;
            secondLine.HorizontalOptions = LayoutOptions.Center;
            secondLine.WidthRequest = screenWidth;
            secondLine.XAlign = TextAlignment.Center;

            Label thirdLine = new Label();
            thirdLine.Text = "support your goals and dreams?";
            thirdLine.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            thirdLine.TextColor = Color.FromRgb(40, 50, 50);
            thirdLine.HeightRequest = screenHeight * 11 / 100;
            thirdLine.HorizontalOptions = LayoutOptions.Center;
            thirdLine.WidthRequest = screenWidth;
            thirdLine.XAlign = TextAlignment.Center;


            goalsAndDreamsPickerButton = new PurposeColor.interfaces.CustomImageButton();
            goalsAndDreamsPickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", @"/Assets/select_box_whitebg.png");
            goalsAndDreamsPickerButton.Text = "Goals & Dreams";
            goalsAndDreamsPickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            goalsAndDreamsPickerButton.TextOrientation = interfaces.TextOrientation.Left;
            goalsAndDreamsPickerButton.FontSize = 17;
            goalsAndDreamsPickerButton.TextColor = Color.Gray;
            goalsAndDreamsPickerButton.WidthRequest = screenWidth * 90 / 100;

            goalsAndDreamsPickerButton.Clicked += OnGoalsPickerButtonClicked;


            actionPickerButton = new CustomImageButton();
            actionPickerButton.IsVisible = false;
            actionPickerButton.BackgroundColor = Color.FromRgb(30, 126, 210);
            actionPickerButton.Text = "Add Supporting Actions";
            actionPickerButton.TextColor = Color.White;

            actionPickerButton.TextOrientation = TextOrientation.Middle;
            actionPickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            // actionPickerButton.TextOrientation = interfaces.TextOrientation.Left;
            actionPickerButton.WidthRequest = screenWidth * 90 / 100;

            actionPickerButton.Clicked += OnActionPickerButtonClicked;


            if (App.screenDensity > 1.5)
            {
                firstLine.FontSize = Device.OnPlatform(20, 20, 30);
                secondLine.FontSize = Device.OnPlatform(20, 22, 30);
                thirdLine.FontSize = Device.OnPlatform(20, 20, 30);
                actionPickerButton.FontSize = 17;
                actionPickerButton.HeightRequest = screenHeight * 6 / 100;
                goalsAndDreamsPickerButton.HeightRequest = screenHeight * 6 / 100;
            }
            else
            {
                firstLine.FontSize = Device.OnPlatform(16, 18, 26);
                secondLine.FontSize = Device.OnPlatform(16, 20, 26);
                thirdLine.FontSize = Device.OnPlatform(16, 18, 26);
                actionPickerButton.FontSize = 15;
                actionPickerButton.HeightRequest = screenHeight * 9 / 100;
                goalsAndDreamsPickerButton.HeightRequest = screenHeight * 9 / 100;
            }

            slider = new CustomSlider
            {
                Minimum = -2,
                Maximum = 2,
                WidthRequest = screenWidth * 90 / 100
            };
            slider.StopGesture = GetstopGetsture;


            //Image sliderDivider1 = new Image();
            //sliderDivider1.Source = "drag_sepeate.png";


            //Image sliderDivider2 = new Image();
            //sliderDivider2.Source = "drag_sepeate.png";


            //Image sliderDivider3 = new Image();
            //sliderDivider3.Source = "drag_sepeate.png";

            //Image sliderBG = new Image();
            //sliderBG.Source = "drag_bg.png";

            this.Appearing += FeelingNowPage_Appearing;

            masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
            masterLayout.AddChildToLayout(subTitleBar, 0, Device.OnPlatform(9, 10, 9));
            masterLayout.AddChildToLayout(firstLine, 0, 20);
            masterLayout.AddChildToLayout(secondLine, 0, 25);
            masterLayout.AddChildToLayout(thirdLine, 0, 30);
            //masterLayout.AddChildToLayout(sliderBG, 7, 45);
            masterLayout.AddChildToLayout(slider, 5, Device.OnPlatform(37, 35, 34));
            /*  masterLayout.AddChildToLayout(sliderDivider1, 30, 45.5f);
              masterLayout.AddChildToLayout(sliderDivider2, 50, 45.5f);
              masterLayout.AddChildToLayout(sliderDivider3, 70, 45.5f);*/
            masterLayout.AddChildToLayout(goalsAndDreamsPickerButton, 5, Device.OnPlatform(50, 50, 45));
            masterLayout.AddChildToLayout(actionPickerButton, 5, Device.OnPlatform(65, 65, 55));


            listContainer = new StackLayout();
            listContainer.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            listContainer.WidthRequest = screenWidth * 90 / 100;
            listContainer.HeightRequest = screenHeight * 20 / 100;
            listContainer.ClassId = "preview";

            actionPreviewListView = new ListView();
            actionPreviewListView.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            actionPreviewListView.ItemTemplate = new DataTemplate(typeof(ActionPreviewCellItem));
            ActionPreviewCellItem.mainPage = this;
            actionPreviewListView.SeparatorVisibility = SeparatorVisibility.None;
            actionPreviewListView.Opacity = 1;
            actionPreviewListView.ItemsSource = actionPreviewListSource;
            listContainer.Children.Add(actionPreviewListView);
            masterLayout.AddChildToLayout(listContainer, 5, Device.OnPlatform(73, 73, 64));

            Content = masterLayout;

        }
Esempio n. 15
0
        /// <summary>
        /// Downloads terms from the <paramref name="dataSource"/> and saves them to <paramref name="outFile"/>
        /// </summary>
        public async Task DownloadAndSaveAsync(ISecondarySource dataSource, string dataUrl, string outFile, string asin, string tld, bool includeTopics, IProgressBar progress, CancellationToken token = default)
        {
            var terms = (await dataSource.GetTermsAsync(dataUrl, asin, tld, includeTopics, progress, token)).ToArray();

            if (terms.Length == 0)
            {
                throw new Exception($"No terms were found on {dataSource.Name}");
            }
            XmlUtil.SerializeToFile(terms, outFile);
        }
        public GemsDetailsPage( DetailsPageModel model )
        {
			try
			{
				NavigationPage.SetHasNavigationBar(this, false);
				detailsPageModel = model;
				masterLayout = new CustomLayout();
				masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
				masterScroll = new ScrollView();
				masterScroll.BackgroundColor = Color.FromRgb(244, 244, 244);
				masterScroll.IsClippedToBounds = true;
				progressBar = DependencyService.Get<IProgressBar>();
				masterStack = new CustomLayout();
				//masterStack.Orientation = StackOrientation.Vertical;
				masterStack.BackgroundColor = Color.FromRgb(244, 244, 244);
				mediaList = model.eventMediaArray;
				actionMediaList = model.actionMediaArray;
				CurrentGemId = model.gemId;
				CurrentGemType = model.gemType;
				User user = null;
				App.GemDeleted = false;

				try
				{
					user = App.Settings.GetUser();
				}
				catch (Exception ex)
				{
					var test = ex.Message;
				}
				if (string.IsNullOrEmpty (model.pageTitleVal)) {
					model.pageTitleVal = "GEM Details";
				}
				mainTitleBar = new PurposeColorTitleBar(Color.FromRgb(8, 135, 224), "Purpose Color", Color.Black, "back", true);
				mainTitleBar.imageAreaTapGestureRecognizer.Tapped += OnImageAreaTapGestureRecognizerTapped;
				subTitleBar = new PurposeColorSubTitleBar(Constants.SUB_TITLE_BG_COLOR, model.pageTitleVal, false);
				subTitleBar.BackButtonTapRecognizer.Tapped += async (object sender, EventArgs e) =>
				{
					try
					{
						await Navigation.PopAsync();
					}
					catch (Exception){
					}
				};


				this.Appearing += GemsDetailsPage_Appearing;

				Label pageTitle = new Label();
				pageTitle.Text = model.titleVal;//model.pageTitleVal;
				pageTitle.TextColor = Color.Black;
				pageTitle.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
				pageTitle.FontAttributes = FontAttributes.Bold;
				pageTitle.WidthRequest = App.screenWidth * 80 / 100;
				pageTitle.HeightRequest = 50;
				pageTitle.XAlign = TextAlignment.Start;
				pageTitle.YAlign = TextAlignment.Start;
				pageTitle.FontSize = Device.OnPlatform(15, 20, 15);

				StackLayout emptyLayout = new StackLayout();
				emptyLayout.BackgroundColor = Color.Transparent;
				emptyLayout.WidthRequest = App.screenWidth * 90 / 100;
				emptyLayout.HeightRequest = 30;

				#region TOOLS LAYOUT

				StackLayout toolsLayout = new StackLayout();
				toolsLayout.Spacing = App.screenWidth * .10;
				toolsLayout.Orientation = StackOrientation.Horizontal;
				toolsLayout.HorizontalOptions = LayoutOptions.Center;
				toolsLayout.HeightRequest = App.screenHeight * .05;
				toolsLayout.Padding = new Thickness(10, 5, 10, 10);
				toolsLayout.ClassId = "ToolsLayout";

				favoriteButton = new Image();
				favoriteButton.Source = Device.OnPlatform("favoriteIcon.png", "favoriteIcon.png", "//Assets//favoriteIcon.png");
				favoriteButton.WidthRequest = Device.OnPlatform(15, 15, 15);
				favoriteButton.HeightRequest = Device.OnPlatform(15, 15, 15);
				favoriteButton.VerticalOptions = LayoutOptions.Center;
				favoriteButtonTap = new TapGestureRecognizer();
				favoriteButtonTap.Tapped += FavoriteButtonTapped;
				favoriteButton.GestureRecognizers.Add(favoriteButtonTap);

				favoriteLabel = new Label
				{
					Text = "Favorite",
					FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
					TextColor = Color.Gray,
					VerticalOptions = LayoutOptions.Center,
					FontSize = Device.OnPlatform(12,12,15)
				};
				favoriteLabel.GestureRecognizers.Add(favoriteButtonTap);
				toolsLayout.Children.Add( new StackLayout{Children = {favoriteButton,favoriteLabel}, Orientation = StackOrientation.Horizontal, Spacing = 5});

				//toolsLayout.Children.Add(favoriteButton);
				//toolsLayout.Children.Add(favoriteLabel);

				if (user.AllowCommunitySharing)
				{
					shareButton = new Image();
					shareButton.Source = Device.OnPlatform("share.png", "share.png", "//Assets//share.png");
					shareButton.WidthRequest = Device.OnPlatform(15, 15, 15);
					shareButton.HeightRequest = Device.OnPlatform(15, 15, 15);
					shareButton.VerticalOptions = LayoutOptions.Center;
					shareLabel = new Label
					{
						Text = "Share",
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						TextColor = Color.Gray,
						VerticalOptions = LayoutOptions.Center,
						FontSize = Device.OnPlatform(12,12,15)
					};
					shareButtonTap = new TapGestureRecognizer();
					shareButtonTap.Tapped += ShareButtonTapped;
					shareButton.GestureRecognizers.Add(shareButtonTap);
					shareLabel.GestureRecognizers.Add(shareButtonTap);
					toolsLayout.Children.Add(new StackLayout{Children = {shareButton,shareLabel}, Orientation = StackOrientation.Horizontal, Spacing = 5});
					//toolsLayout.Children.Add(shareLabel);
				}



				Image commentButton = new Image();
				commentButton.Source = Device.OnPlatform("icon_cmnt.png", "icon_cmnt.png", "//Assets//icon_cmnt.png");
				commentButton.WidthRequest = Device.OnPlatform(15, 15, 15);
				commentButton.HeightRequest = Device.OnPlatform(15, 15, 15);
				commentButton.VerticalOptions = LayoutOptions.Center;
				commentsLabel = new Label
				{
					Text = "Comments",
					VerticalOptions = LayoutOptions.Center,
					FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
					TextColor = Color.Gray,
					FontSize = Device.OnPlatform(12,12,15),
					ClassId = "CommentLabel"
				};

				commentButtonTap = new TapGestureRecognizer();
				commentButtonTap.Tapped += CommentButtonTapped;
				commentButton.GestureRecognizers.Add(commentButtonTap);
				commentsLabel.GestureRecognizers.Add(commentButtonTap);

				toolsLayout.Children.Add( new StackLayout{Children = {commentButton,commentsLabel}, Orientation = StackOrientation.Horizontal, Spacing = 5});
				//toolsLayout.Children.Add(commentButton);
				//toolsLayout.Children.Add(commentsLabel);

				#endregion

				#region  title, description
				title = new Label ();
				title.Text = model.titleVal;
				title.TextColor = Color.Black;
				title.WidthRequest = App.screenWidth * 90 / 100;
				title.FontSize = Device.OnPlatform (12, 12, 12);
				title.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;

				description = new Label ();
				description.WidthRequest = App.screenWidth * .75;
				description.Text = model.description;
				description.TextColor = Color.Black;
				description.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;

				Image menuButton = new Image
				{
					Source = Device.OnPlatform("downarrow.png", "downarrow.png", "//Assets//downarrow.png"),
					HorizontalOptions = LayoutOptions.End,
					BackgroundColor = Color.Transparent,
					WidthRequest = Device.OnPlatform(25, 25, 60),
					HeightRequest = Device.OnPlatform(25, 25, 40),
					Aspect = Aspect.AspectFit
				};

				TapGestureRecognizer editMenuGesture = new TapGestureRecognizer();
				editMenuGesture.Tapped += GemMenuButton_Clicked;
				menuButton.GestureRecognizers.Add(editMenuGesture);

				masterStack.AddChildToLayout(pageTitle, 2, Device.OnPlatform(0,1,1));
				masterStack.AddChildToLayout(menuButton, Device.OnPlatform(87, 90, 99), Device.OnPlatform(0,1,1));
				//masterStack.AddChildToLayout(title,1,Device.OnPlatform(3,7,7));
				#endregion

				StackLayout bottomAndLowerControllStack = new StackLayout
				{
					Orientation = StackOrientation.Vertical,
					BackgroundColor = Color.Transparent,
					Spacing = 1,
					Padding = 0,// new Thickness(0, 0, 0, 5),
					WidthRequest = App.screenWidth,// * .90,
					ClassId= "BottomNlowerStack"
				};
				bottomAndLowerControllStack.Children.Add(new StackLayout { Padding = new Thickness(6, 0, 0, 5), Children = { description } });

				#region MEDIA LIST

				if (mediaList != null)
				{
					for (int index = 0; index < mediaList.Count; index++)
					{
						TapGestureRecognizer videoTap = new TapGestureRecognizer();
						videoTap.Tapped += OnEventVideoTapped;
						bool isValidUrl = (mediaList[index].event_media != null && !string.IsNullOrEmpty(mediaList[index].event_media)) ? true : false;
						string source = (isValidUrl) ? model.Media + mediaList[index].event_media : Device.OnPlatform("noimage.png", "noimage.png", "//Assets//noimage.png");
						string fileExtenstion = Path.GetExtension(source);
						bool isImage = (fileExtenstion == ".png" || fileExtenstion == ".jpg" || fileExtenstion == ".jpeg") ? true : false;
						//img.WidthRequest = App.screenWidth;// * 50 / 100;
						Image img = new Image();

						if(isImage)
							img.HeightRequest = App.screenWidth * 1.1;
						else
						{
							img.HeightRequest = App.screenWidth;
						}
						
						//img.MinimumHeightRequest = App.screenWidth;
						//img.MinimumWidthRequest = App.screenWidth;

						img.Aspect = Aspect.AspectFill;
						img.ClassId = null;
						if (mediaList[index] != null && mediaList[index].media_type == "mp4")
						{
							img.ClassId = source;
							source = Constants.SERVICE_BASE_URL + mediaList[index].video_thumb;
						}
						else if (mediaList[index] != null && (mediaList[index].media_type == "3gpp" || mediaList[index].media_type == "aac") )
						{
							img.ClassId = source;
							source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
						}
						else if (mediaList[index] != null && mediaList[index].media_type == "wav")
						{
							img.ClassId = source;
							source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
						}
						img.Source = source;
						img.GestureRecognizers.Add(videoTap);

						var indicator = new ActivityIndicator { Color = new Color(.5), };
						indicator.SetBinding(ActivityIndicator.IsRunningProperty, "IsLoading");
						indicator.BindingContext = img;
						masterStack.AddChildToLayout(indicator, 40, Device.OnPlatform(50,40,40));
						if (isValidUrl)
						{

							if (mediaList[index] != null && mediaList[index].media_type == "mp4")
							{
								Grid grid = new Grid
								{
									VerticalOptions = LayoutOptions.FillAndExpand,
									HorizontalOptions = LayoutOptions.FillAndExpand,
									RowDefinitions = 
									{
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },

									},
									ColumnDefinitions = 
									{
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },

									}
									};

								Image play = new Image();
								play.Source = "video_play.png";
								play.Aspect = Aspect.AspectFit;
								play.WidthRequest = 75;
								play.HeightRequest = 75;
								play.HorizontalOptions = LayoutOptions.Center;
								play.VerticalOptions = LayoutOptions.Center;
								play.ClassId =  mediaList[index].event_media ;
								play.GestureRecognizers.Add(videoTap);

								BoxView box = new BoxView();
								box.BackgroundColor = Color.Red;
								box.WidthRequest = 100;
								box.HeightRequest = 100;

								grid.Children.Add( img, 0, 0 );
								Grid.SetColumnSpan(img, 3);
								Grid.SetRowSpan( img, 3 );
								grid.Children.Add(play, 1, 1);
								bottomAndLowerControllStack.Children.Add(grid);
							}
							else
							{
								bottomAndLowerControllStack.Children.Add(img);
							}
						}


					}
				}

				if (actionMediaList != null)
				{
					for (int index = 0; index < actionMediaList.Count; index++)
					{
						TapGestureRecognizer videoTap = new TapGestureRecognizer();
						videoTap.Tapped += OnActionVideoTapped;

						Image img = new Image();
						bool isValidUrl = (actionMediaList[index].action_media != null && !string.IsNullOrEmpty(actionMediaList[index].action_media)) ? true : false;
						string source = (isValidUrl) ? model.Media + actionMediaList[index].action_media : Device.OnPlatform("noimage.png", "noimage.png", "//Assets//noimage.png");
						string fileExtenstion = Path.GetExtension(source);
						bool isImage = (fileExtenstion == ".png" || fileExtenstion == ".jpg" || fileExtenstion == ".jpeg") ? true : false;
						//img.WidthRequest = App.screenWidth;// * 50 / 100;
						if(isImage)
							img.HeightRequest = App.screenWidth * 1.1;
						else
						{
							img.HeightRequest = App.screenWidth;
						}
						
						img.Aspect = Aspect.AspectFill;
						img.ClassId = null;
						if (actionMediaList[index] != null && actionMediaList[index].media_type == "mp4")
						{
							img.ClassId = source;
							source = Constants.SERVICE_BASE_URL + actionMediaList[index].video_thumb;
						}
						else if (actionMediaList[index] != null && (actionMediaList[index].media_type == "3gpp" || actionMediaList[index].media_type == "aac"))
						{
							img.ClassId = source;
							source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
						}
						else if (actionMediaList[index] != null && actionMediaList[index].media_type == "wav")
						{
							img.ClassId = source;
							source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
						}
						img.Source = source;
						img.GestureRecognizers.Add(videoTap);
						var indicator = new ActivityIndicator { Color = new Color(.5), };
						indicator.SetBinding(ActivityIndicator.IsRunningProperty, "IsLoading");
						indicator.BindingContext = img;
						masterStack.AddChildToLayout(indicator, 40, Device.OnPlatform(50,40,40));
						if (isValidUrl)
						{
							if (actionMediaList[index] != null && actionMediaList[index].media_type == "mp4")
							{
								Grid grid = new Grid
								{
									VerticalOptions = LayoutOptions.FillAndExpand,
									HorizontalOptions = LayoutOptions.FillAndExpand,
									RowDefinitions = 
									{
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },

									},
									ColumnDefinitions = 
									{
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },

									}
									};

								Image play = new Image();
								play.Source = "video_play.png";
								play.Aspect = Aspect.AspectFit;
								play.WidthRequest = 75;
								play.HeightRequest = 75;
								play.HorizontalOptions = LayoutOptions.Center;
								play.VerticalOptions = LayoutOptions.Center;
								play.ClassId =  actionMediaList[index].action_media ;
								play.GestureRecognizers.Add(videoTap);

								BoxView box = new BoxView();
								box.BackgroundColor = Color.Red;
								box.WidthRequest = 100;
								box.HeightRequest = 100;

								grid.Children.Add( img, 0, 0 );
								Grid.SetColumnSpan(img, 3);
								Grid.SetRowSpan( img, 3 );
								grid.Children.Add(play, 1, 1);
								bottomAndLowerControllStack.Children.Add(grid);
							}
							else
							{
								bottomAndLowerControllStack.Children.Add(img);
							}
						}
					}
				}


				if (model.goal_media != null)
				{
					ScrollView imgScrollView = new ScrollView();
					imgScrollView.Orientation = ScrollOrientation.Horizontal;

					//StackLayout horizmgConatiner = new StackLayout();
					// horizmgConatiner.Orientation = StackOrientation.Horizontal;

					for (int index = 0; index < model.goal_media.Count; index++)
					{
						TapGestureRecognizer videoTap = new TapGestureRecognizer();
						videoTap.Tapped += OnActionVideoTapped;

						Image img = new Image();
						bool isValidUrl = (model.goal_media[index].goal_media != null && !string.IsNullOrEmpty(model.goal_media[index].goal_media)) ? true : false;
						string source = (isValidUrl) ?  model.goal_media[index].goal_media : Device.OnPlatform("noimage.png", "noimage.png", "//Assets//noimage.png");
						string fileExtenstion = Path.GetExtension(source);
						bool isImage = (fileExtenstion == ".png" || fileExtenstion == ".jpg" || fileExtenstion == ".jpeg") ? true : false;
						//img.WidthRequest = App.screenWidth;// * 50 / 100;
						if(isImage)
							img.HeightRequest = App.screenWidth * 1.1;
						else
						{
							img.HeightRequest = App.screenWidth;
						}
						
						img.Aspect = Aspect.AspectFill;
						img.ClassId = null;
						if (model.goal_media[index] != null && model.goal_media[index].media_type == "mp4")
						{

							source = Constants.SERVICE_BASE_URL +  model.goal_media[index].video_thumb;
							img.ClassId = source;
						}
						else if (model.goal_media[index] != null && (model.goal_media[index].media_type == "3gpp" || model.goal_media[index].media_type == "aac"))
						{
							img.ClassId = source;
							source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
						}
						else if (model.goal_media[index] != null && model.goal_media[index].media_type == "wav")
						{
							img.ClassId = source;
							source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
						}
						img.Source = source;
						img.GestureRecognizers.Add(videoTap);
						var indicator = new ActivityIndicator { Color = new Color(.5), };
						indicator.SetBinding(ActivityIndicator.IsRunningProperty, "IsLoading");
						indicator.BindingContext = img;
						masterStack.AddChildToLayout(indicator, 40, Device.OnPlatform(50,40,40));
						// horizmgConatiner.Children.Add(img);
						if( isValidUrl )
						{
							if ( model.goal_media[index]!= null &&  model.goal_media[index].media_type == "mp4")
							{
								Grid grid = new Grid
								{
									VerticalOptions = LayoutOptions.FillAndExpand,
									HorizontalOptions = LayoutOptions.FillAndExpand,
									RowDefinitions = 
									{
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },
										new RowDefinition { Height = new GridLength( App.screenWidth / 3 ) },

									},
									ColumnDefinitions = 
									{
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },
										new ColumnDefinition { Width = new GridLength( App.screenWidth / 3 ) },

									}
									};

								Image play = new Image();
								play.Source = "video_play.png";
								play.Aspect = Aspect.AspectFit;
								play.WidthRequest = 75;
								play.HeightRequest = 75;
								play.HorizontalOptions = LayoutOptions.Center;
								play.VerticalOptions = LayoutOptions.Center;
								play.ClassId =   Constants.SERVICE_BASE_URL +  model.goal_media[index].goal_media ;
								play.GestureRecognizers.Add(videoTap);

								BoxView box = new BoxView();
								box.BackgroundColor = Color.Red;
								box.WidthRequest = 100;
								box.HeightRequest = 100;

								grid.Children.Add( img, 0, 0 );
								Grid.SetColumnSpan(img, 3);
								Grid.SetRowSpan( img, 3 );
								grid.Children.Add(play, 1, 1);
								//horizmgConatiner.Children.Add(grid);
								bottomAndLowerControllStack.Children.Add(grid);
							}
							else
							{
								//horizmgConatiner.Children.Add(img);
								bottomAndLowerControllStack.Children.Add(img);
							}
						}

					}

					// imgScrollView.Content = horizmgConatiner;
					// bottomAndLowerControllStack.Children.Add(imgScrollView);
				}

				#endregion

				//masterStack.AddChildToLayout(toolsLayout,1,65);
				//masterStack.AddChildToLayout(emptyLayout,1,75);
				bottomAndLowerControllStack.Children.Add(toolsLayout);
				bottomAndLowerControllStack.Children.Add(emptyLayout);
				if (model.titleVal.Length < 25) {
					masterStack.AddChildToLayout (bottomAndLowerControllStack, 0, 8);
				} else {
					masterStack.AddChildToLayout (bottomAndLowerControllStack, 0, 11);
				}

				StackLayout spaceOffsetlayout = new StackLayout();
				spaceOffsetlayout.WidthRequest = App.screenWidth * 50 / 100;
				spaceOffsetlayout.HeightRequest = Device.OnPlatform(100, 100, 250);
				spaceOffsetlayout.BackgroundColor = Color.Transparent;
				//masterStack.AddChildToLayout(spaceOffsetlayout, 1, 85);
				bottomAndLowerControllStack.Children.Add(spaceOffsetlayout);

				masterScroll.HeightRequest = App.screenHeight - 20;
				masterScroll.WidthRequest = App.screenWidth; //App.screenWidth * 90 / 100;

				masterScroll.Content = masterStack;

				masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
				masterLayout.AddChildToLayout(subTitleBar, 0, Device.OnPlatform(9, 10, 10));
				masterLayout.AddChildToLayout(masterScroll,0, Device.OnPlatform(16,18,18));

				#region CUSTOM LIST MENU

				//new CustomListViewItem { EmotionID = item.EmotionId.ToString(), Name = item.EmpotionName, SliderValue = item.EmotionValue  }

				#endregion

				Content = masterLayout;
			} 
			catch (Exception ex)
			{
				Debug.WriteLine ( ex.Message );
			}
        }
        public void Dispose()
        {
            masterScroll = null;
            Content = null;
            masterLayout = null;
			progressBar = null;
			masterStack = null;
			title = null;
			description = null;
			mediaList = null;
			actionMediaList = null;
			this.Content = null;
			shareLabel = null;
            if (shareButtonTap != null)
            {
                shareButtonTap.Tapped -= ShareButtonTapped;
                shareButtonTap = null;
            }
            if (commentButtonTap!= null)
            {
                commentButtonTap.Tapped -= CommentButtonTapped;
                favoriteButtonTap.Tapped -= FavoriteButtonTapped;
                commentButtonTap = null;
                favoriteButtonTap = null;
            }
			

			GC.Collect ();
        }
		//public GemsDetailsPage(List<EventMedia> mediaArray, List<ActionMedia> actionMediaArray, string pageTitleVal, string titleVal, string desc, string Media, string NoMedia, string gemId, GemType gemType)
		public CommunityGems(DetailsPageModel model)
		{
			NavigationPage.SetHasNavigationBar(this, false);
			masterLayout = new CustomLayout();
			masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
			masterScroll = new ScrollView();
			masterScroll.IsClippedToBounds = true;
			masterScroll.BackgroundColor = Color.FromRgb(244, 244, 244);
			progressBar = DependencyService.Get<IProgressBar>();
			currentUser = App.Settings.GetUser ();

			modelObject = model;
			CurrentGemId = model.gemId;
			CurrentGemType = model.gemType;

			cancelToken = new CancellationTokenSource ();
			mainTitleBar = new PurposeColorTitleBar(Color.FromRgb(8, 135, 224), "Purpose Color", Color.Black, "back", false);
			mainTitleBar.imageAreaTapGestureRecognizer.Tapped += OnImageAreaTapGestureRecognizerTapped;
			subTitleBar = new CommunityGemSubTitleBar(Constants.SUB_TITLE_BG_COLOR, Constants.COMMUNITY_GEMS, true);
			subTitleBar.myGemsTapRecognizer.Tapped += async (object sender, EventArgs e) => 
			{
				IProgressBar progress = DependencyService.Get<IProgressBar>();
				progress.ShowProgressbar( "Loading Mygems.." );

				CommunityGemsObject myGems = await ServiceHelper.GetMyGemsDetails();
				if( myGems != null )
				{
					//communityGems = null;
					Navigation.PushAsync( new MyGemsPage( myGems ) );
					myGemsCount = myGems.resultarray.Count;
				}

				progress.HideProgressbar();

				/*	masterStack.Children.Clear();
				masterStackLayout.Children.Clear();
				masterScroll.Content = null;

				RenderGems( communityGems );*/


			};
			subTitleBar.BackButtonTapRecognizer.Tapped += async (object sender, EventArgs e) =>
			{
				try
				{
					App.masterPage.IsPresented = !App.masterPage.IsPresented;
				}
				catch (Exception)
				{
				}
			};


			this.Appearing += OnAppearing;




			Label pageTitle = new Label();
			pageTitle.Text = model.pageTitleVal;
			pageTitle.TextColor = Color.Black;
			pageTitle.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			pageTitle.FontAttributes = FontAttributes.Bold;
			pageTitle.WidthRequest = App.screenWidth * 80 / 100;
			pageTitle.HeightRequest = 50;
			pageTitle.XAlign = TextAlignment.Start;
			pageTitle.YAlign = TextAlignment.Start;
			pageTitle.FontSize = Device.OnPlatform(15, 20, 15);

			BoxView emptyLayout = new BoxView();
			emptyLayout.BackgroundColor = Color.Transparent;
			emptyLayout.WidthRequest = App.screenWidth * 90 / 100;
			emptyLayout.HeightRequest = 30;

			masterStackLayout = new StackLayout();
			masterStackLayout.Orientation = StackOrientation.Vertical;

			TapGestureRecognizer chatTap = new TapGestureRecognizer ();
			Image chat = new Image ();
			chat.Source = "chat.png";
			chat.Aspect = Aspect.Fill;
			chat.WidthRequest = App.screenWidth * 16 / 100;
			chat.HeightRequest = App.screenWidth * 12 / 100;
			chat.GestureRecognizers.Add ( chatTap );
			chatTap.Tapped += async (object sender, EventArgs e) => 
			{
				await Navigation.PushAsync( new ChatPage() );
			};

			masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
			masterLayout.AddChildToLayout(chat, 80, 1);
			masterLayout.AddChildToLayout(subTitleBar, 0, Device.OnPlatform(9, 10, 10));
			masterLayout.AddChildToLayout(masterScroll, -1, 18);

			masterScroll.Scrolled += OnMasterScrollScrolled;

			Content = masterLayout;
		}
		public void Dispose()
		{
			masterLayout = null;
			progressBar = null;
			//masterStack = null;
			title = null;
			description = null;
			mediaList = null;
			shareLabel = null;
			if (shareButtonTap != null)
			{
				shareButtonTap.Tapped -= OnShareButtonTapped;
				shareButtonTap = null;
			}
			if (commentButtonTap != null)
			{
				commentButtonTap.Tapped -= OnCommentButtonTapped;
				commentButtonTap = null;
				likeButtonTap = null;
			}

			gemMenuContainer = null;
			modelObject = null;
			masterStackLayout = null;
			communityGems = null;
			GC.Collect();
		}
Esempio n. 20
0
        public ClusterOutput Run(List<string> structs)
        {
            maxProgress=5;
            currentProgress=0;
            if (hConcensus)
            {
                maxProgress++;
                consensus = new HammingConsensus(dMeasure.dirName, null, false, input.consensusProfile);
                progressObject = consensus;
                consensus.InitMeasure();
                currentProgress += 1.0 / maxProgress;
            }
            jury = new jury1D();
            progressObject = jury;
            currentProgress += 1.0 / maxProgress;
            progressObject = null;
            jury.PrepareJury(dMeasure.dirName, dMeasure.alignFile, input.jury1DProfileFast);
            currentProgress += 1.0 / maxProgress;
            ClusterOutput clOut = new ClusterOutput();



            root.setStruct = structs;
//            if(hConcensus)
//                consensus.ToConsensusStates(structs);
                     
            FastCluster(root);
            maxV = initNodesNum;
            while (st.Count>0 && (leaves.Count+st.Count)<initNodesNum)
            {
                st.Sort(
                        delegate(HClusterNode p1, HClusterNode p2)
                        {                                        
                            return p2.setStruct.Count.CompareTo(p1.setStruct.Count);
                        }             
                );

                HClusterNode node = st[0];
                st.RemoveAt(0);
                FastCluster(node);
                currentV += leaves.Count + st.Count;
            }
            currentV = maxV;
            currentProgress+=1.0/maxProgress;
            while (st.Count > 0)
            {
                HClusterNode node = st[0];
                st.RemoveAt(0);
                leaves.Add(node);
            }
            MakeDendrogs(linkage);
            currentProgress+=1.0/maxProgress;
            PrepareList();
            root = ConnectDendrogs(linkage);
            root.levelDist = root.SearchMaxDist();
            root.realDist = dMeasure.GetRealValue(root.levelDist);
            //CheckRefDistances();
            //dendrogList = RearangeDendrogram(root);
            //root = ConnectDendrogs();
            clOut.hNode = root;
            currentProgress+=1.0/maxProgress;
            return clOut;
        }
Esempio n. 21
0
        public static void DoPartialCheck(Dictionary <string, TableMetaData> tables, GlobalConfiguration config, IProgressBar progress = null)
        {
            if (string.IsNullOrWhiteSpace(config.PartialCheck_DAL_Path))
            {
                return;
            }
            var partial_path  = Path.Combine(config.PartialCheck_DAL_Path, "partial");
            var partial_files = Directory.GetFiles(partial_path);
            var list          = InnerCheckPartial(tables, partial_files, config);

            if (list.Count > 0)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("以下字段可能有问题:");
                list.ForEach(p => Console.WriteLine(p));
                Console.ResetColor();
            }
            else
            {
                Console.WriteLine("检测完毕");
            }
        }
        public async Task <IEnumerable <Term> > GetTermsAsync(string dataUrl, string asin, string tld, bool includeTopics, IProgressBar progress, CancellationToken cancellationToken = default)
        {
            _logger.Log("Downloading Shelfari page...");
            var terms = new List <Term>();

            if (sourceHtmlDoc == null)
            {
                sourceHtmlDoc = await _httpClient.GetPageAsync(dataUrl, cancellationToken);
            }

            //Constants for wiki processing
            var sections = new Dictionary <string, string>
            {
                { "WikiModule_Characters", "character" },
                { "WikiModule_Organizations", "topic" },
                { "WikiModule_Settings", "topic" },
                { "WikiModule_Glossary", "topic" }
            };

            foreach (var header in sections.Keys)
            {
                var characterNodes =
                    sourceHtmlDoc.DocumentNode.SelectNodes("//div[@id='" + header + "']//ul[@class='li_6']/li");
                if (characterNodes == null)
                {
                    continue;                         //Skip section if not found on page
                }
                foreach (var li in characterNodes)
                {
                    var tmpString = li.InnerText;
                    //Create term as either character/topic
                    var newTerm = new Term
                    {
                        Type = sections[header]
                    };
                    if (tmpString.Contains(":"))
                    {
                        newTerm.TermName = tmpString.Substring(0, tmpString.IndexOf(":", StringComparison.Ordinal));
                        newTerm.Desc     = tmpString.Substring(tmpString.IndexOf(":", StringComparison.Ordinal) + 1).Replace("&amp;", "&").Trim();
                    }
                    else
                    {
                        newTerm.TermName = tmpString;
                    }
                    newTerm.DescSrc = "shelfari";
                    //Use either the associated shelfari URL of the term or if none exists, use the book's url
                    newTerm.DescUrl = li.InnerHtml.IndexOf("<a href", StringComparison.Ordinal) == 0
                        ? li.InnerHtml.Substring(9, li.InnerHtml.IndexOf("\"", 9, StringComparison.Ordinal) - 9)
                        : dataUrl;
                    if (header == "WikiModule_Glossary")
                    {
                        newTerm.MatchCase = false;
                    }
                    //Default glossary terms to be case insensitive when searching through book
                    if (terms.Select(t => t.TermName).Contains(newTerm.TermName))
                    {
                        _logger.Log("Duplicate term \"" + newTerm.TermName + "\" found. Ignoring this duplicate.");
                    }
                    else
                    {
                        terms.Add(newTerm);
                    }
                }
            }
            return(terms);
        }
Esempio n. 23
0
 public ScaleScanner(string path, IProgressBar progressbar) : base(path, progressbar)
 {
     BuildRegex();
 }
        public async Task <IEnumerable <NotableClip> > GetNotableClipsAsync(string url, HtmlDocument srcDoc = null, IProgressBar progress = null, CancellationToken cancellationToken = default)
        {
            if (srcDoc == null)
            {
                srcDoc = await _httpClient.GetPageAsync(url, cancellationToken);
            }
            var quoteNodes = srcDoc.DocumentNode.SelectNodes("//div[@id='WikiModule_Quotations']/div/ul[@class='li_6']/li");

            if (quoteNodes == null)
            {
                return(Enumerable.Empty <NotableClip>());
            }

            return(quoteNodes
                   .Select(quoteNode => quoteNode.SelectSingleNode(".//blockquote"))
                   .Where(node => node != null)
                   .Select(node => node.InnerText)
                   .Select(quote => Regex.Replace(quote, "^(&ldquo;){1,2}", ""))
                   .Select(quote => Regex.Replace(quote, "(&rdquo;){1,2}$", ""))
                   .Select(quote => new NotableClip
            {
                Text = quote,
                Likes = 0
            }));
        }
Esempio n. 25
0
        public async Task GenerateNewFormatData(IProgressBar progress, CancellationToken token = default)
        {
            try
            {
                await _dataSource.GetExtrasAsync(curBook, progress, token);

                curBook.Series = await _dataSource.GetSeriesInfoAsync(curBook.DataUrl, token);

                if (curBook.Series == null || curBook.Series.Total == 0)
                {
                    _logger.Log("The book was not found to be part of a series.");
                }
                else if (curBook.Series.Next == null && curBook.Series.Position != curBook.Series.Total.ToString())// && !curBook.Series.Position?.Contains(".") == true)
                {
                    _logger.Log("An error occurred finding the next book in series. The book may not be part of a series, or it is the latest release.");
                }
                else
                {
                    await ExpandSeriesMetadata(curBook.Series, token);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("(404)"))
                {
                    _logger.Log("An error occurred finding next book in series: Goodreads URL not found.\r\n" +
                                "If reading from a file, you can switch the source to Goodreads to specify a URL, then switch back to File.");
                }
                else
                {
                    _logger.Log("An error occurred finding next book in series: " + ex.Message + "\r\n" + ex.StackTrace);
                }
                throw;
            }

            // TODO: Refactor next/previous series stuff
            if (curBook.Series?.Next == null)
            {
                try
                {
                    var seriesResult = await _amazonClient.DownloadNextInSeries(curBook.Asin, token);

                    switch (seriesResult?.Error?.ErrorCode)
                    {
                    case "ERR004":
                        _logger.Log("According to Amazon, this book is not part of a series.");
                        break;

                    case "ERR000":
                        if (curBook.Series == null)
                        {
                            curBook.Series = new SeriesInfo();
                        }
                        curBook.Series.Next =
                            new BookInfo(seriesResult.NextBook.Title.TitleName,
                                         Functions.FixAuthor(seriesResult.NextBook.Authors.FirstOrDefault()?.AuthorName),
                                         seriesResult.NextBook.Asin);
                        var response = await _amazonInfoParser.GetAndParseAmazonDocument(curBook.Series.Next.AmazonUrl, token);

                        response.ApplyToBookInfo(curBook.Series.Next);
                        break;
                    }
                }
                catch
                {
                    // Ignore
                }
            }

            if (curBook.Series != null)
            {
                _logger.Log($"\nSeries URL: {curBook.Series.Url}");
                if (!string.IsNullOrEmpty(curBook.Series.Name))
                {
                    _logger.Log($"This is book {curBook.Series.Position} of {curBook.Series.Total} in the {curBook.Series.Name} series");
                }
                if (curBook.Series.Previous != null)
                {
                    _logger.Log($"Preceded by: {curBook.Series.Previous.Title}");
                }
                if (curBook.Series.Next != null)
                {
                    _logger.Log($"Followed by: {curBook.Series.Next.Title}\n");
                }
            }

            try
            {
                if (!await _dataSource.GetPageCountAsync(curBook, token))
                {
                    if (!Properties.Settings.Default.pageCount)
                    {
                        _logger.Log("No page count found on Goodreads");
                    }
                    _logger.Log("Attempting to estimate page count...");
                    _logger.Log(Functions.GetPageCount(curBook.RawmlPath, curBook));
                }
            }
            catch (Exception ex)
            {
                _logger.Log("An error occurred while searching for or estimating the page count: " + ex.Message + "\r\n" + ex.StackTrace);
                throw;
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Gather the list of quotes & number of times they've been liked -- close enough to "x paragraphs have been highlighted y times" from Amazon
        /// </summary>
        public async Task <IEnumerable <NotableClip> > GetNotableClipsAsync(string url, HtmlDocument srcDoc = null, IProgressBar progress = null, CancellationToken cancellationToken = default)
        {
            if (srcDoc == null)
            {
                srcDoc = await _httpClient.GetPageAsync(url, cancellationToken);
            }
            var quoteNode = srcDoc.DocumentNode.SelectSingleNode("//div[@class='h2Container gradientHeaderContainer']/h2/a[starts-with(.,'Quotes from')]");

            if (quoteNode == null)
            {
                return(null);
            }
            var quoteURL = $"https://www.goodreads.com{quoteNode.GetAttributeValue("href", "")}?page={{0}}";

            progress?.Set(0, 1);

            var quoteBag    = new ConcurrentBag <IEnumerable <NotableClip> >();
            var initialPage = await _httpClient.GetPageAsync(string.Format(quoteURL, 1), cancellationToken);

            // check how many pages there are (find previous page button, get parent div, take all children of that, 2nd last one should be the max page count
            var maxPageNode = initialPage.DocumentNode.SelectSingleNode("//span[contains(@class,'previous_page')]/parent::div/*[last()-1]");

            if (!int.TryParse(maxPageNode?.InnerHtml, out var maxPages))
            {
                maxPages = 1;
            }

            IEnumerable <NotableClip> ParseQuotePage(HtmlDocument quoteDoc)
            {
                var tempNodes = quoteDoc.DocumentNode.SelectNodes("//div[@class='quotes']/div[@class='quote']");

                return(tempNodes?.Select(node =>
                {
                    var quoteMatch = Regex.Match(node.InnerText, "&ldquo;(.*?)&rdquo;", RegexOptions.Compiled);
                    var likesMatch = Regex.Match(node.SelectSingleNode(".//div[@class='right']/a")?.InnerText ?? "",
                                                 @"(\d+) likes", RegexOptions.Compiled);
                    if (!quoteMatch.Success || !likesMatch.Success)
                    {
                        return null;
                    }
                    return new NotableClip
                    {
                        Text = quoteMatch.Groups[1].Value,
                        Likes = int.Parse(likesMatch.Groups[1].Value)
                    };
                }).Where(quote => quote != null));
            }

            quoteBag.Add(ParseQuotePage(initialPage));
            progress?.Set(1, maxPages);
            await Enumerable.Range(2, maxPages - 1).ParallelForEachAsync(async page =>
            {
                var quotePage = await _httpClient.GetPageAsync(string.Format(quoteURL, page), cancellationToken);
                quoteBag.Add(ParseQuotePage(quotePage));
                progress?.Add(1);
            }, MaxConcurrentRequests, cancellationToken);

            return(quoteBag.Where(quotes => quotes != null && quotes.Any()).SelectMany(quotes => quotes).ToList());
        }
		public CommunityMediaViewer ( List<PurposeColor.Constants.MediaDetails> mediaList )
		{
			NavigationPage.SetHasNavigationBar (this, false);
			masterLayout = new CustomLayout ();
			masterLayout.BackgroundColor = Color.Black;// Color.FromRgb(244, 244, 244);
			masterScroll = new ScrollView ();
			masterScroll.BackgroundColor = Color.Black;//Color.FromRgb(244, 244, 244);
			progressBar = DependencyService.Get<IProgressBar> ();

			mainTitleBar = new PurposeColorTitleBar (Color.FromRgb (8, 135, 224), "Purpose Color", Color.Black, "back", true);
			subTitleBar = new PurposeColorSubTitleBar (Constants.SUB_TITLE_BG_COLOR, "Gem Media Viewer", false);
			subTitleBar.BackButtonTapRecognizer.Tapped += async (object sender, EventArgs e) => {
				try {
					await Navigation.PopAsync ();
				} catch (Exception) {
				}
			};

			mainTitleBar.imageAreaTapGestureRecognizer.Tapped += (object sender, EventArgs e) => 
			{
				App.masterPage.IsPresented = !App.masterPage.IsPresented;
			};
				

			masterStack = new CustomLayout ();
			masterStack.BackgroundColor = Color.Transparent;
			masterStack.HorizontalOptions = LayoutOptions.Center;

			StackLayout bottomAndLowerControllStack = new StackLayout {
				Orientation = StackOrientation.Vertical,
				BackgroundColor = Color.Transparent,
				Spacing = 1,
				Padding = new Thickness (0, 5, 0, 5),
				WidthRequest = App.screenWidth,
			};


			ScrollView imgScrollView = new ScrollView ();
			imgScrollView.Orientation = ScrollOrientation.Horizontal;

			StackLayout horizmgConatiner = new StackLayout ();
			horizmgConatiner.Orientation = StackOrientation.Horizontal;


			CustomImageButton nextImg = new CustomImageButton ();
			nextImg.ImageName = "next.png";
			nextImg.WidthRequest = 40;
			nextImg.HeightRequest = 65;
				
			nextImg.Clicked += async (object sender, EventArgs e) => 
			{

				double curX = imgScrollView.ScrollX;
				double imgWidth = App.screenWidth * 100 / 100;

				if( Device.OS == TargetPlatform.iOS )
				{
					if( curX + imgWidth + 15 < imgScrollView.ContentSize.Width )
						await imgScrollView.ScrollToAsync( curX + imgWidth , 0, true );
				}
				else
				{
					await imgScrollView.ScrollToAsync( curX + imgWidth , 0, true );
				}
					
			};


			CustomImageButton prevImg = new CustomImageButton ();
			prevImg.ImageName = "prev.png";
			prevImg.WidthRequest = 40;
			prevImg.HeightRequest = 65;
			prevImg.Clicked += async (object sender, EventArgs e) => 
			{
				double curX = imgScrollView.ScrollX;
				double imgWidth = App.screenWidth * 90 / 100;
				if( curX > 0 )
				await imgScrollView.ScrollToAsync( curX - App.screenWidth , 0, true );
			};


			#region MEDIA LIST

			if (mediaList != null) 
			{
				foreach (var item in mediaList) 
				{
					TapGestureRecognizer videoTap = new TapGestureRecognizer ();
					videoTap.Tapped += OnActionVideoTapped;

					Image img = new Image ();
					bool isValidUrl = ( item.Url != null && !string.IsNullOrEmpty ( item.Url )) ? true : false;
					string source = (isValidUrl) ? item.Url : Device.OnPlatform ("noimage.png", "noimage.png", "//Assets//noimage.png");
					string fileExtenstion = Path.GetExtension (source);
					bool isImage = (fileExtenstion == ".png" || fileExtenstion == ".jpg" || fileExtenstion == ".jpeg") ? true : false;
					img.WidthRequest = App.screenWidth;
					img.HeightRequest = App.screenWidth;
					img.Aspect = Aspect.AspectFill;
					img.ClassId = null;
					if (item != null && item.MediaType == "mp4") 
					{
						img.ClassId = source;
						source = Constants.SERVICE_BASE_URL + item.ImageName;
					}
					else if ( item != null &&  item.MediaType == "aac")
					{
						img.ClassId = source;
						source = Device.OnPlatform ("audio.png", "audio.png", "//Assets//audio.png");
					}
					else if ( item != null &&  item.MediaType == "3gpp")
					{
						img.ClassId = source;
						source = Constants.SERVICE_BASE_URL + item.ImageName;
					}
					else if ( item != null && item.MediaType == "wav")
					{
						img.ClassId = source;
						source = Device.OnPlatform ("audio.png", "audio.png", "//Assets//audio.png");
					}
					img.Source = source;
					img.GestureRecognizers.Add (videoTap);
					var indicator = new ActivityIndicator { Color = new Color (.5), };
					indicator.SetBinding (ActivityIndicator.IsRunningProperty, "IsLoading");
					indicator.BindingContext = img;
					masterStack.AddChildToLayout (indicator, 40, 30);

					if (item != null && ( item.MediaType == "mp4" || item.MediaType == "3gpp" ) )
					{
						Grid grid = new Grid
						{
							VerticalOptions = LayoutOptions.FillAndExpand,
							HorizontalOptions = LayoutOptions.FillAndExpand,
							RowDefinitions = 
							{
								new RowDefinition { Height = new GridLength( img.WidthRequest / 3 ) },
								new RowDefinition { Height = new GridLength( img.WidthRequest / 3 ) },
								new RowDefinition { Height = new GridLength( img.WidthRequest / 3 ) },

							},
							ColumnDefinitions = 
							{
								new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },
								new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },
								new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },

							}
						};

						Image play = new Image();
						play.Source = "video_play.png";
						play.Aspect = Aspect.AspectFit;
						play.WidthRequest = 75;
						play.HeightRequest = 75;
						play.HorizontalOptions = LayoutOptions.Center;
						play.VerticalOptions = LayoutOptions.Center;
						play.ClassId =  img.ClassId;
						play.GestureRecognizers.Add(videoTap);

						grid.Children.Add( img, 0, 0 );
						Grid.SetColumnSpan(img, 3);
						Grid.SetRowSpan( img, 3 );
						grid.Children.Add(play, 1, 1);
						horizmgConatiner.Children.Add(grid);
					}
					else
					{
						horizmgConatiner.Children.Add(img);
					}
				}
				imgScrollView.Content = horizmgConatiner;
				bottomAndLowerControllStack.Children.Add (imgScrollView);

			}

			#endregion

			masterStack.AddChildToLayout (bottomAndLowerControllStack, 0, Device.OnPlatform (5, 9, 12));//12
			masterScroll.HeightRequest = App.screenHeight - 20;
			masterScroll.WidthRequest = App.screenWidth;// * 90 / 100;

			StackLayout masterStackLayout = new StackLayout ();
			masterStackLayout.HorizontalOptions = LayoutOptions.Center;
			masterStackLayout.BackgroundColor = Color.Black;
			masterStackLayout.Orientation = StackOrientation.Vertical;
			masterStackLayout.Children.Add (masterStack);
			masterScroll.Content = masterStackLayout;
			masterLayout.AddChildToLayout (mainTitleBar, 0, 0);
			masterLayout.AddChildToLayout (subTitleBar, 0, Device.OnPlatform (9, 10, 10));
			masterLayout.AddChildToLayout (masterScroll, 0, 18);
			masterLayout.AddChildToLayout (prevImg, Device.OnPlatform( -2, -2, 0 ), 50);
			masterLayout.AddChildToLayout (nextImg, 90, 50);
			Content = masterLayout;
		}
Esempio n. 28
0
        void AnalyzeAssemblies(IEnumerable <AssemblyInfo> assemblyInfos, List <string> assemblyDirectories, Action <CallInfo> onCallFound, Action <ProjectIssue> onIssueFound, Action <IProgressBar> onComplete, IProgressBar progressBar = null)
        {
            using (var assemblyResolver = new DefaultAssemblyResolver())
            {
                foreach (var path in assemblyDirectories)
                {
                    assemblyResolver.AddSearchDirectory(path);
                }

                foreach (var dir in assemblyInfos.Select(info => Path.GetDirectoryName(info.path)).Distinct())
                {
                    assemblyResolver.AddSearchDirectory(dir);
                }

                if (progressBar != null)
                {
                    progressBar.Initialize("Analyzing Scripts", "Analyzing project scripts",
                                           assemblyInfos.Count());
                }

                // Analyse all Player assemblies
                foreach (var assemblyInfo in assemblyInfos)
                {
                    Console.WriteLine("[Project Auditor] Analyzing {0}", assemblyInfo.name);
                    if (progressBar != null)
                    {
                        progressBar.AdvanceProgressBar(string.Format("Analyzing {0}", assemblyInfo.name));
                    }

                    if (!File.Exists(assemblyInfo.path))
                    {
                        Debug.LogError(assemblyInfo.path + " not found.");
                        continue;
                    }

                    AnalyzeAssembly(assemblyInfo, assemblyResolver, onCallFound, onIssueFound);
                }
            }

            if (progressBar != null)
            {
                progressBar.ClearProgressBar();
            }

            if (onComplete != null)
            {
                onComplete(progressBar);
            }
        }
		async void OnAppearing (object sender, EventArgs e)
		{
			if (!isLoadingFromDetailsPage) {
				if (progressBar == null)
					progressBar = DependencyService.Get<IProgressBar> ();

				//if (Device.OS != TargetPlatform.iOS)
					progressBar.ShowProgressbar ("Loading gems..");

				try {
					try {
						if (eventsWithImage == null) {
							eventsWithImage = await ServiceHelper.GetAllEventsWithImage ();

							if (eventsWithImage != null) {
								App.Settings.SaveEventsWithImage (eventsWithImage);
							} else {
								var success = await DisplayAlert (Constants.ALERT_TITLE, "Error in fetching gems", Constants.ALERT_OK, Constants.ALERT_RETRY);
								if (!success) {
									OnAppearing (sender, EventArgs.Empty);
									return;
								} else {
									eventsWithImage = await App.Settings.GetAllEventWithImage (); // get from local db.
									//progress.HideProgressbar ();
								}
							}
						}
					} catch (Exception ex) {
						var test = ex.Message;
					}

					listViewContainer = new StackLayout {
						Orientation = StackOrientation.Vertical,
						Padding = new Thickness (0, 0, 0, 5),
						//BackgroundColor = Color.White, //
						WidthRequest = App.screenWidth,
						Spacing = 0 // App.screenHeight * .02
					};
					masterStack.Children.Add (listViewContainer);

					StackLayout empty = new StackLayout ();
					empty.HeightRequest = Device.OnPlatform (30, 30, 50);
					empty.WidthRequest = App.screenWidth;
					empty.BackgroundColor = Color.Transparent;
					masterStack.Children.Add (empty);

					masterScroll.Content = masterStack;

					masterLayout.AddChildToLayout (masterScroll, 0, Device.OnPlatform (17, 18, 18));

					Content = masterLayout;

					// call - ShowEmotionsTapGesture_Tapped //
					progressBar.HideProgressbar ();
					ShowEmotionsTapGesture_Tapped (emotionsButtion, null);	
				} catch (Exception ex) {
					var test = ex.Message;
					progressBar.HideProgressbar ();
				}
				//progressBar.HideProgressbar ();
			} else {
				// if gem deleted.. chk selectd gem... try to remov frm stack
				if (App.GemDeleted) {

					//remov frm stack
					try {
						var deletedGem = listViewContainer.Children.First(c => c.ClassId == selectedGem);
						if (deletedGem != null) {
							listViewContainer.Children.Remove (deletedGem);
						}
					} catch (Exception ex) {
						var test = ex.Message;
					}
				}
			}
		}
Esempio n. 30
0
        public void Audit(Action <ProjectIssue> onIssueFound, Action onComplete, IProgressBar progressBar = null)
        {
            if (m_Config.AnalyzeInBackground && m_AssemblyAnalysisThread != null)
            {
                m_AssemblyAnalysisThread.Join();
            }

            var compilationHelper = new AssemblyCompilationHelper();
            var callCrawler       = new CallCrawler();

            Profiler.BeginSample("ScriptAuditor.Audit.Compilation");
            var assemblyInfos = compilationHelper.Compile(progressBar);

            Profiler.EndSample();

            var issues                = new List <ProjectIssue>();
            var localAssemblyInfos    = assemblyInfos.Where(info => !info.readOnly).ToArray();
            var readOnlyAssemblyInfos = assemblyInfos.Where(info => info.readOnly).ToArray();

            var assemblyDirectories = new List <string>();

            assemblyDirectories.AddRange(AssemblyHelper.GetPrecompiledAssemblyDirectories());
            assemblyDirectories.AddRange(AssemblyHelper.GetPrecompiledEngineAssemblyDirectories());

            var onCallFound = new Action <CallInfo>(pair =>
            {
                callCrawler.Add(pair);
            });

            var onCompleteInternal = new Action <IProgressBar>(bar =>
            {
                compilationHelper.Dispose();
                callCrawler.BuildCallHierarchies(issues, bar);
                onComplete();
            });

            var onIssueFoundInternal = new Action <ProjectIssue>(issue =>
            {
                issues.Add(issue);
                onIssueFound(issue);
            });

            Profiler.BeginSample("ScriptAuditor.Audit.Analysis");

            // first phase: analyze assemblies generated from editable scripts
            AnalyzeAssemblies(localAssemblyInfos, assemblyDirectories, onCallFound, onIssueFoundInternal, null, progressBar);

            var enableBackgroundAnalysis = m_Config.AnalyzeInBackground;

#if !UNITY_2019_3_OR_NEWER
            enableBackgroundAnalysis = false;
#endif
            // second phase: analyze all remaining assemblies, in a separate thread if enableBackgroundAnalysis is enabled
            if (enableBackgroundAnalysis)
            {
                m_AssemblyAnalysisThread = new Thread(() =>
                                                      AnalyzeAssemblies(readOnlyAssemblyInfos, assemblyDirectories, onCallFound, onIssueFound, onCompleteInternal));
                m_AssemblyAnalysisThread.Name     = "Assembly Analysis";
                m_AssemblyAnalysisThread.Priority = ThreadPriority.BelowNormal;
                m_AssemblyAnalysisThread.Start();
            }
            else
            {
                Profiler.BeginSample("ScriptAuditor.Audit.AnalysisReadOnly");
                AnalyzeAssemblies(readOnlyAssemblyInfos, assemblyDirectories, onCallFound, onIssueFoundInternal, onCompleteInternal, progressBar);
                Profiler.EndSample();
            }
            Profiler.EndSample();
        }
Esempio n. 31
0
 public void TestInit() {
     _progressBar = new ProgressBar();
 }
Esempio n. 32
0
        public async Task <Response> GenerateNewFormatData(
            BookInfo curBook,
            Settings settings,
            ISecondarySource dataSource,
            AuthorProfileGenerator.Response authorProfile,
            Func <string, string, string> asinPrompt,
            IMetadata metadata,
            IProgressBar progress,
            CancellationToken cancellationToken = default)
        {
            // Generate old stuff first, ignore response since curBook and custAlsoBought are shared
            // todo make them not shared
            var oldResponse = await GenerateOld(curBook, settings, progress, cancellationToken);

            if (oldResponse == null)
            {
                return(null);
            }

            try
            {
                await dataSource.GetExtrasAsync(curBook, progress, cancellationToken);

                progress?.Set(0);
                _logger.Log("Checking if this book is part of a series…");
                curBook.Series = await dataSource.GetSeriesInfoAsync(curBook.DataUrl, cancellationToken);

                if (curBook.Series == null || curBook.Series.Total == 0)
                {
                    _logger.Log("The book was not found to be part of a series.");
                }
                else if (curBook.Series.Next == null && curBook.Series.Position != curBook.Series.Total.ToString())// && !curBook.Series.Position?.Contains(".") == true)
                {
                    _logger.Log("An error occurred finding the next book in series. The book may not be part of a series, or it is the latest release.");
                }
                else
                {
                    await ExpandSeriesMetadata(authorProfile, curBook.Series, settings, asinPrompt, cancellationToken);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("(404)"))
                {
                    _logger.Log("An error occurred finding next book in series: Goodreads URL not found.\r\n" +
                                "If reading from a file, you can switch the source to Goodreads to specify a URL, then switch back to File.");
                }
                else
                {
                    _logger.Log($"An error occurred finding next book in series: {ex.Message}\r\n{ex.StackTrace}");
                }
                throw;
            }

            // TODO: Refactor next/previous series stuff
            if (curBook.Series?.Next == null)
            {
                try
                {
                    var seriesResult = await _roentgenClient.DownloadNextInSeriesAsync(curBook.Asin, cancellationToken);

                    switch (seriesResult?.Error?.ErrorCode)
                    {
                    case "ERR004":
                        _logger.Log("According to Amazon, this book is not part of a series.");
                        break;

                    case "ERR000":
                        curBook.Series ??= new SeriesInfo();
                        curBook.Series.Next =
                            new BookInfo(seriesResult.NextBook.Title.TitleName,
                                         Functions.FixAuthor(seriesResult.NextBook.Authors.FirstOrDefault()?.AuthorName),
                                         seriesResult.NextBook.Asin);
                        var response = await _amazonInfoParser.GetAndParseAmazonDocument(curBook.Series.Next.AmazonUrl, cancellationToken);

                        response.ApplyToBookInfo(curBook.Series.Next);
                        break;
                    }
                }
                catch
                {
                    // Ignore
                }
            }

            if (curBook.Series != null)
            {
                _logger.Log($"Series URL: {curBook.Series.Url}");
                if (!string.IsNullOrEmpty(curBook.Series.Name))
                {
                    _logger.Log((int)Convert.ToDouble(curBook.Series.Position) == curBook.Series.Total
                        ? $"This is the latest book in the {curBook.Series.Name} series."
                        : $"This is book {curBook.Series.Position} of {curBook.Series.Total} in the {curBook.Series.Name} series.");
                }
                if (curBook.Series.Previous != null)
                {
                    _logger.Log($"Preceded by: {curBook.Series.Previous.Title}");
                }
                if (curBook.Series.Next != null)
                {
                    _logger.Log($"Followed by: {curBook.Series.Next.Title}");
                }
            }

            // If the page count isn't known, attempt to locate or estimate it (if the setting is enabled)
            if (curBook.PageCount == 0)
            {
                try
                {
                    if (!await dataSource.GetPageCountAsync(curBook, cancellationToken))
                    {
                        var metadataCount = metadata.GetPageCount();
                        if (metadataCount.HasValue)
                        {
                            curBook.PageCount = metadataCount.Value;
                        }
                        else if (settings.EstimatePageCount)
                        {
                            _logger.Log($"No page count found on {dataSource.Name} or in metadata. An estimation will be made, if possible.");
                            curBook.PageCount = _pageCountService.EstimatePageCount(metadata);
                        }
                        else
                        {
                            _logger.Log($"No page count found on {dataSource.Name} or in metadata");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Log($"An error occurred while searching for or estimating the page count: {ex.Message}\r\n{ex.StackTrace}");
                    throw;
                }
            }

            if (curBook.PageCount != 0)
            {
                var readingTime = _readingTimeService.GetReadingTime(curBook.PageCount);
                curBook.ReadingHours   = readingTime.Hours;
                curBook.ReadingMinutes = readingTime.Minutes;
                var readingTimeFromPageCount = _readingTimeService.GetFormattedReadingTime(curBook.PageCount);
                if (readingTimeFromPageCount != null)
                {
                    _logger.Log(readingTimeFromPageCount);
                }
            }

            return(new Response
            {
                Book = curBook,
                CustomerAlsoBought = oldResponse.CustomerAlsoBought
            });
        }
Esempio n. 33
0
        public static void Obfuscate(PerformContext performContext, DbAppContext dbContext, string sourceLocation, string destinationLocation, string systemId)
        {
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, "Obfuscate_" + OldTableProgress, BcBidImport.SigId, NewTable);

            if (startPoint == BcBidImport.SigId)    // this means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Obfuscating " + XmlFileName + " is complete from the former process ***");
                return;
            }
            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                // create Processer progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer ser          = new XmlSerializer(typeof(Project[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, sourceLocation, rootAttr);
                Project[]     legacyItems  = (Project[])ser.Deserialize(memoryStream);

                performContext.WriteLine("Obfuscating Project data");
                progress.SetValue(0);

                List <ImportMapRecord> importMapRecords = new List <ImportMapRecord>();

                foreach (Project item in legacyItems.WithProgress(progress))
                {
                    item.Created_By = systemId;

                    Random random        = new Random();
                    string newProjectNum = random.Next(10000).ToString();

                    ImportMapRecord importMapRecordOrganization = new ImportMapRecord
                    {
                        TableName     = NewTable,
                        MappedColumn  = "Project_Num",
                        OriginalValue = item.Project_Num,
                        NewValue      = newProjectNum
                    };

                    importMapRecords.Add(importMapRecordOrganization);

                    item.Project_Num = newProjectNum;
                    item.Job_Desc1   = ImportUtility.ScrambleString(item.Job_Desc1);
                    item.Job_Desc2   = ImportUtility.ScrambleString(item.Job_Desc2);
                }

                performContext.WriteLine("Writing " + XmlFileName + " to " + destinationLocation);

                // write out the array.
                FileStream fs = ImportUtility.GetObfuscationDestination(XmlFileName, destinationLocation);
                ser.Serialize(fs, legacyItems);
                fs.Close();

                // write out the spreadsheet of import records.
                ImportUtility.WriteImportRecordsToExcel(destinationLocation, importMapRecords, OldTable);
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Generate the necessities for the old format
        /// TODO Remove anything that gets generated for the new version
        /// </summary>
        public async Task <Response> GenerateOld(BookInfo curBook, Settings settings, IProgressBar progress = null, CancellationToken cancellationToken = default)
        {
            _logger.Log($"Attempting to find book on Amazon.{settings.AmazonTld}…");
            //Generate Book search URL from book's ASIN
            var ebookLocation = $@"https://www.amazon.{settings.AmazonTld}/dp/{curBook.Asin}";

            HtmlDocument bookHtmlDoc;

            try
            {
                bookHtmlDoc = await _httpClient.GetPageAsync(ebookLocation, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.Log($"An error occurred while downloading book's Amazon page: {ex.Message}\r\nYour ASIN may not be correct.");
                return(null);
            }
            _logger.Log("Book found on Amazon!");

            try
            {
                var response = _amazonInfoParser.ParseAmazonDocument(bookHtmlDoc);
                response.ApplyToBookInfo(curBook);
            }
            catch (Exception ex)
            {
                _logger.Log($"An error occurred parsing Amazon info: {ex.Message}");
                return(null);
            }

            string ReadDesc(string file)
            {
                try
                {
                    var fileText = Functions.ReadFromFile(file);

                    if (string.IsNullOrEmpty(fileText))
                    {
                        _logger.Log($"Found description file, but it is empty!\r\n{file}");
                    }
                    if (!string.Equals(curBook.Description, fileText))
                    {
                        _logger.Log($"Using biography from {file}.");
                    }

                    return(fileText);
                }
                catch (Exception ex)
                {
                    _logger.Log($"An error occurred while opening {file}\r\n{ex.Message}\r\n{ex.StackTrace}");
                }

                return(null);
            }

            var descFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory ?? Environment.CurrentDirectory, "ext", $"{curBook.Asin}.desc");

            if (settings.EditDescription)
            {
                if (!File.Exists(descFile) || new FileInfo(descFile).Length == 0)
#if NETFRAMEWORK
                { File.WriteAllText(descFile, curBook.Description); }
#else
                { await File.WriteAllTextAsync(descFile, curBook.Description, cancellationToken); }
#endif
                _logger.Log("Displaying book description for editing...");
                Functions.RunNotepad(descFile);
                curBook.Description = ReadDesc(descFile);
            }

            try
            {
                var listSelectors = new[]
                {
                    "//ol[@class='a-carousel' and @role='list']/li[@class='a-carousel-card']",
                    "//ol[@class='a-carousel' and @role='list']/li[@class='a-carousel-card a-float-left']",
                    "//ol[@class='a-carousel' and @role='list']/li[@class='a-carousel-card aok-float-left']",
                    "//*[contains(@id, 'desktop-dp-sims_purchase-similarities-esp')]/li",
                    "//*[contains(@id, 'dp-sims_OnlineDpSimsPurchaseStrategy-sims')]/li",
                    "//*[@id='desktop-dp-sims_purchase-similarities-sims-feature']/li",
                    "//*[@id='desktop-dp-sims_vtp-60-sims-feature']/li",
                    "//div[@id='desktop-dp-sims_session-similarities-brand-protection-sims-feature']/li",
                    "//div[@id='desktop-dp-sims_session-similarities-sims-feature']/li",
                    "//*[@id='view_to_purchase-sims-feature']/li"
                };

                var relatedBooks = listSelectors.SelectMany(selector =>
                {
                    var listNodes = bookHtmlDoc.DocumentNode.SelectNodes(selector);
                    return(listNodes != null
                            ? ParseBookList(listNodes)
                            : Enumerable.Empty <BookInfo>());
                }).Where(list => list != null)
                                   .Distinct()
                                   .Where(book => !book.Title.ToLower().Contains(curBook.Title.ToLower()) && book.Asin != curBook.Asin && !_invalidBookTitleRegex.IsMatch(curBook.Title))
                                   .ToArray();

                if (settings.UseNewVersion && relatedBooks.Any())
                {
                    _logger.Log($"Gathering metadata for {relatedBooks.Length} related book(s)…");
                    progress?.Set(0, relatedBooks.Length);
                    await foreach (var _ in _amazonClient.EnhanceBookInfos(relatedBooks, cancellationToken))
                    {
                        progress?.Add(1);
                    }
                }

                return(new Response
                {
                    Book = curBook,
                    CustomerAlsoBought = relatedBooks
                });
            }
            catch (Exception ex)
            {
                _logger.Log($"An error occurred parsing the book's amazon page: {ex.Message}{ex.StackTrace}");
                return(null);
            }
        }
Esempio n. 35
0
 public Parser(GlobalConfiguration config, IProgressBar progress)
     : base(config, progress)
 {
 }
        /// <summary>
        /// Caller needs to dispose image.
        /// </summary>
        private Image <Rgb24> DownloadImage(int zoomLevel, ZoomModifier zoomModifier, IProgressBar parentProgressBar = null)
        {
            if (!ZoomModifiers.Contains(zoomModifier))
            {
                throw new ArgumentOutOfRangeException(nameof(zoomModifier));
            }

            if (zoomLevel + zoomModifier.Level > ZoomLevels)
            {
                throw new ArgumentOutOfRangeException(nameof(zoomLevel));
            }

            var totalSize = TileCount(zoomLevel, zoomModifier) * zoomModifier.TileSize;

            return(LeafletjsDownloader.Download(UrlGen(zoomLevel, zoomModifier), zoomModifier.TileSize, totalSize, parentProgressBar));
        }
Esempio n. 37
0
        /// <summary>
        /// Runs all available auditors (code, project settings) and generate a report of all found issues.
        /// </summary>
        /// <param name="onIssueFound"> Action called whenever a new issue is found </param>
        /// <param name="onUpdate"> Action called whenever an internal auditor completes </param>
        /// <param name="progressBar"> Progress bar, if applicable </param>
        public void Audit(Action <ProjectIssue> onIssueFound, Action <bool> onUpdate, IProgressBar progressBar = null)
        {
            var stopwatch = Stopwatch.StartNew();

            var numAuditors = m_Auditors.Count;

            foreach (var auditor in m_Auditors)
            {
                var startTime = stopwatch.ElapsedMilliseconds;
                auditor.Audit(onIssueFound, () =>
                {
                    if (config.LogTimingsInfo)
                    {
                        Debug.Log(auditor.GetType().Name + " took: " + (stopwatch.ElapsedMilliseconds - startTime) / 1000.0f + " seconds.");
                    }

                    onUpdate(false);

                    numAuditors--;

                    // check if all auditors completed
                    if (numAuditors == 0)
                    {
                        stopwatch.Stop();
                        if (config.LogTimingsInfo)
                        {
                            Debug.Log("Project Auditor took: " + stopwatch.ElapsedMilliseconds / 1000.0f + " seconds.");
                        }

                        onUpdate(true);
                    }
                }, progressBar);
            }

            Debug.Log("Project Auditor time to interactive: " + stopwatch.ElapsedMilliseconds / 1000.0f + " seconds.");
        }
        /// <summary>
        /// Caller needs to dispose image.
        /// </summary>
        public Image <Rgb24> DownloadImage(int?zoomLevel = null, ZoomModifier zoomModifier = null, IProgressBar parentProgressBar = null)
        {
            var modifier = zoomModifier ?? ZoomModifiers.Last();

            if (zoomLevel < 0 || zoomLevel > MaxZoomLevels - modifier.Level)
            {
                throw new ArgumentOutOfRangeException(nameof(zoomLevel));
            }

            return(DownloadImage(zoomLevel ?? MaxZoomLevels - modifier.Level, modifier, parentProgressBar));
        }
Esempio n. 39
0
        //override public object TokenEOL => TokenId._EOL_;
        //override public object TokenComment => TokenId._COMMENT_;

        public ScaleScanner(IProgressBar progressbar = null) : base(progressbar)
        {
            BuildRegex();
        }
Esempio n. 40
0
 public void Audit(Action <ProjectIssue> onIssueFound, Action onComplete, IProgressBar progressBar = null)
 {
     AnalyzeResources(onIssueFound);
     onComplete();
 }
Esempio n. 41
0
 public ScaleScanner(StreamReader input, IProgressBar progressbar) : base(input, progressbar)
 {
     BuildRegex();
 }
Esempio n. 42
0
 public Task GetExtrasAsync(BookInfo curBook, IProgressBar progress = null, CancellationToken cancellationToken = default)
 {
     throw new NotSupportedException();
 }
Esempio n. 43
0
        /// <summary>
        /// Runs all available auditors (code, project settings) and generate a report of all found issues.
        /// </summary>
        /// <param name="onIssueFound"> Action called whenever a new issue is found </param>
        /// <param name="onUpdate"> Action called whenever an internal auditor completes </param>
        /// <param name="progressBar"> Progress bar, if applicable </param>
        public void Audit(Action <ProjectIssue> onIssueFound, Action <bool> onUpdate, IProgressBar progressBar = null)
        {
            var numAuditors = m_Auditors.Count;

            if (numAuditors == 0)
            {
                // early out if, for any reason, there are no registered Auditors
                onUpdate(true);
                return;
            }

            var stopwatch = Stopwatch.StartNew();

            foreach (var auditor in m_Auditors)
            {
                var startTime = stopwatch.ElapsedMilliseconds;
                auditor.Audit(onIssueFound, () =>
                {
                    if (m_Config.LogTimingsInfo)
                    {
                        Debug.Log(auditor.GetType().Name + " took: " + (stopwatch.ElapsedMilliseconds - startTime) / 1000.0f + " seconds.");
                    }

                    var finished = --numAuditors == 0;
                    if (finished)
                    {
                        stopwatch.Stop();
                        if (m_Config.LogTimingsInfo)
                        {
                            Debug.Log("Project Auditor took: " + stopwatch.ElapsedMilliseconds / 1000.0f + " seconds.");
                        }
                    }

                    onUpdate(finished);
                }, progressBar);
            }

            if (m_Config.LogTimingsInfo)
            {
                Debug.Log("Project Auditor time to interactive: " + stopwatch.ElapsedMilliseconds / 1000.0f + " seconds.");
            }
        }
Esempio n. 44
0
        public async Task <IEnumerable <Term> > GetTermsAsync(string dataUrl, string asin, string tld, bool includeTopics, IProgressBar progress, CancellationToken cancellationToken = default)
        {
            try
            {
                var terms = await _roentgenClient.DownloadTermsAsync(asin, tld, cancellationToken);

                if (terms == null)
                {
                    _logger.Log("No terms were available for this book :(");
                    return(Enumerable.Empty <Term>());
                }

                terms = terms.Where(term => term.Type == "character" || includeTopics).ToArray();
                _logger.Log($"Successfully downloaded {terms.Length} terms from Roentgen!");
                return(terms);
            }
            catch (Exception e)
            {
                _logger.Log($"Failed to download terms: {e.Message}");
                return(Enumerable.Empty <Term>());
            }
        }
Esempio n. 45
0
        /// <summary>
        /// Import Rotaion List
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="fileLocation"></param>
        /// <param name="systemId"></param>
        public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId)
        {
            // check the start point. If startPoint == sigId then it is already completed
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BCBidImport.SigId);

            if (startPoint == BCBidImport.SigId)    // this means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***");
                return;
            }

            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                //Create Processer progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer ser          = new XmlSerializer(typeof(Block[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                Block[]       legacyItems  = (Block[])ser.Deserialize(memoryStream);

                int ii = startPoint;

                // skip the portion already processed
                if (startPoint > 0)
                {
                    legacyItems = legacyItems.Skip(ii).ToArray();
                }

                foreach (Block item in legacyItems.WithProgress(progress))
                {
                    int areaId          = item.Area_Id ?? 0;
                    int equipmentTypeId = item.Equip_Type_Id ?? 0;
                    int blockNum        = Convert.ToInt32(float.Parse(item.Block_Num ?? "0.0"));

                    // this is for conversion record hope this is unique
                    string oldUniqueId = ((areaId * 10000 + equipmentTypeId) * 100 + blockNum).ToString();

                    // see if we have this one already
                    ImportMap importMap = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == OldTable && x.OldKey == oldUniqueId);

                    // new entry
                    if (importMap == null)
                    {
                        if (areaId > 0)
                        {
                            LocalAreaRotationList instance = null;
                            CopyToInstance(dbContext, item, ref instance, systemId);
                            ImportUtility.AddImportMap(dbContext, OldTable, oldUniqueId, NewTable, instance.Id);
                        }
                    }
                    else // update
                    {
                        LocalAreaRotationList instance = dbContext.LocalAreaRotationLists.FirstOrDefault(x => x.Id == importMap.NewKey);

                        // record was deleted
                        if (instance == null)
                        {
                            CopyToInstance(dbContext, item, ref instance, systemId);

                            // update the import map
                            importMap.NewKey = instance.Id;
                            dbContext.ImportMaps.Update(importMap);
                        }
                        else // ordinary update
                        {
                            CopyToInstance(dbContext, item, ref instance, systemId);

                            // touch the import map
                            importMap.LastUpdateTimestamp = DateTime.UtcNow;
                            dbContext.ImportMaps.Update(importMap);
                        }
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    if (++ii % 500 == 0)
                    {
                        try
                        {
                            ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, ii.ToString(), BCBidImport.SigId);
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                try
                {
                    performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                    ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BCBidImport.SigId.ToString(), BCBidImport.SigId);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    performContext.WriteLine("Error saving data " + e.Message);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
            }
        }
Esempio n. 46
0
 public Task <IEnumerable <NotableClip> > GetNotableClipsAsync(string url, HtmlDocument srcDoc = null, IProgressBar progress = null, CancellationToken cancellationToken = default)
 {
     throw new NotSupportedException();
 }
		public void Dispose ()
		{
			masterScroll = null;
			Content = null;
			masterLayout = null;
			progressBar = null;
			masterStack = null;
			this.Content = null;
			GC.Collect ();
		}
Esempio n. 48
0
 public Progress(IProgressBar progress)
 {
     _progress = progress;
 }
Esempio n. 49
0
 public ProgressBar(Generator generator)
     : base(generator, typeof(IProgressBar), true)
 {
     inner = (IProgressBar)Handler;
 }
Esempio n. 50
0
            public Descriptor(ResourceDownloader parent, Downloader downloader, IProgressBar progress)
            {
                this.progress = progress;
                this.downloader = downloader;
                this.parent = parent;

                downloader.Completed += new EventHandler(Completed);
                downloader.DownloadFailed += new ErrorEventHandler(DownloadFailed);
                downloader.DownloadProgressChanged += new EventHandler(DownloadProgressChanged);
            }
		async void ShowEmotionsTapGesture_Tapped (object sender, EventArgs e)
		{
			try {
				if (App.isEmotionsListing) {
					return;
				}

				if(progressBar == null)
				{
					progressBar = DependencyService.Get<IProgressBar>();
				}
				// display the emotions list and change color of Goals selection uttion
				//progressBar.ShowProgressbar ("Loading gems.. 3");

				bool isSuccess = await AddEventsToView (0);
				if (isSuccess) 
				{
					masterScroll.ScrollToAsync(0,0, true);
					App.isEmotionsListing = true;
					#region MyRegionButton color
					Color eBtnClr = emotionsButtion.BackgroundColor;
					emotionsButtion.BackgroundColor = goalsButton.BackgroundColor;
					goalsButton.BackgroundColor = eBtnClr;
					Color ETxtClr = emotionLabel.TextColor;
					emotionLabel.TextColor = goalsAndDreamsLabel.TextColor;
					goalsAndDreamsLabel.TextColor = ETxtClr;

					#endregion
				}
				progressBar.HideProgressbar();
			} catch (Exception ) {
				
			}
			//progressBar.HideProgressbar ();
		}
		public void Dispose()
		{
			masterLayout = null;
			progressBar = null;
			mainTitleBar = null;
			masterScroll = null;
			masterStack = null;
			eventsWithImage = null;
			actionsWithImage = null;
			emotionsButtion = null;
			goalsButton = null;
			goalsAndDreamsLabel = null;
			emotionLabel = null;
			emotionListingBtnTapgesture = null;
			goalsListingBtnTapgesture = null;
			listViewContainer = null;


			//GC.SuppressFinalize(this);
		}
		public GemsMainPage()
		{

			NavigationPage.SetHasNavigationBar(this, false);
			masterLayout = new CustomLayout();
			masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
			progressBar = DependencyService.Get<IProgressBar>();
			progressBar.ShowProgressbar ("Loading gems..");
			App.isEmotionsListing = false;
			isLoadingFromDetailsPage = false;

			this.Appearing += OnAppearing;
			this.Disappearing += GemsMainPage_Disappearing;
			mainTitleBar = new GemsPageTitleBar(Color.FromRgb(8, 135, 224), "Goal Enabling Materials", Color.White, "", true);
			mainTitleBar.imageAreaTapGestureRecognizer.Tapped += OnImageAreaTapGestureRecognizerTapped;
			masterScroll = new ScrollView();
			masterScroll.WidthRequest = App.screenWidth;
			masterScroll.HeightRequest = App.screenHeight * 85 / 100;
			masterScroll.BackgroundColor = Color.White;
			masterScroll.Scrolled += OnScroll;
			masterScroll.IsClippedToBounds = true;

			masterStack = new StackLayout();
			masterStack.Orientation = StackOrientation.Vertical;
			masterStack.BackgroundColor = Color.White;

			emotionLabel = new Label {
				Text = "EMOTIONS  ", 
				FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
				FontSize = Device.OnPlatform (14, 18, 14),
				HorizontalOptions = LayoutOptions.End,
				VerticalOptions = LayoutOptions.Center,
				TextColor = Color.White,
				WidthRequest = App.screenWidth * .5,
				XAlign = TextAlignment.Center
			};

			emotionsButtion = new StackLayout{
				Children = {
					emotionLabel
				},
				BackgroundColor = Color.FromRgb(8, 159, 245),
				Orientation = StackOrientation.Horizontal,
				WidthRequest = App.screenWidth * .5
				///HorizontalOptions = LayoutOptions.Center
			};

			emotionListingBtnTapgesture = new TapGestureRecognizer ();
			emotionListingBtnTapgesture.Tapped += ShowEmotionsTapGesture_Tapped;
			emotionsButtion.GestureRecognizers.Add (emotionListingBtnTapgesture);

			goalsAndDreamsLabel = new Label {
				Text = "GOALS & DREAMS", 
				FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
				FontSize = Device.OnPlatform (14, 18, 14),
				HorizontalOptions = LayoutOptions.End,
				VerticalOptions = LayoutOptions.Center,
				TextColor = Color.Gray,
				XAlign = TextAlignment.Center
			};

			goalsButton = new StackLayout{
				Children = {
					goalsAndDreamsLabel
				},
				BackgroundColor = Constants.INPUT_GRAY_LINE_COLOR,
				Orientation = StackOrientation.Horizontal,
				WidthRequest = App.screenWidth * .5,
				HorizontalOptions = LayoutOptions.Center,
				Padding = new Thickness(Device.OnPlatform(20,15,20),0,0,0)
			};
			goalsListingBtnTapgesture = new TapGestureRecognizer ();
			goalsListingBtnTapgesture.Tapped += GoalsListingBtnTapgesture_Tapped;
			goalsButton.GestureRecognizers.Add (goalsListingBtnTapgesture);

			masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
			masterLayout.AddChildToLayout(new StackLayout{HeightRequest =  App.screenHeight * 0.08, Orientation = StackOrientation.Horizontal, Spacing = 0, Children = {emotionsButtion, goalsButton}}, 0,Device.OnPlatform(9,10,10));

			progressBar.HideProgressbar ();
		}
Esempio n. 54
0
		protected ProgressBar (Generator generator, Type type, bool initialize = true)
			: base (generator, type, initialize)
		{
			handler = (IProgressBar)Handler;
		}
		async void OnScroll(object sender, ScrolledEventArgs e)
		{
			try {
				if(progressBar == null)
				{
					progressBar = DependencyService.Get<IProgressBar>();
				}
				if (masterScroll.Height+ masterScroll.ScrollY > (masterStack.Height - masterStack.Y-20)) {//Device.OnPlatform (512, 550, 0)
					masterScroll.Scrolled -= OnScroll;
					if (!displayedLastGem) {
						//progressBar.ShowProgressbar ("loading gems..");
						await LoadMoreGemsClicked ();
						//progressBar.HideProgressbar ();
					} else {
						progressBar.ShowToast ("Reached end of the list..");
					}
					await Task.Delay (TimeSpan.FromSeconds (2));
					masterScroll.Scrolled += OnScroll;
				} else if (masterScroll.ScrollY < Device.OnPlatform (-15, 10, 0)) {
					masterScroll.Scrolled -= OnScroll;
					if (!reachedFront) {
						//progressBar.ShowProgressbar ("Lading gems..");
						await LoadPreviousGems ();
						//progressBar.HideProgressbar ();
					} else {
						progressBar.ShowToast ("Reached starting of the list..");
					}
					await Task.Delay (TimeSpan.FromSeconds (2));
					masterScroll.Scrolled += OnScroll;
				}
			} catch (Exception ex) {
				progressBar.HideProgressbar ();                                                                         
			}
		}
Esempio n. 56
0
 public Database( IProgressBar progressBar )
 {
     this._progressBar = progressBar;
     this.IterationsToRun = 1;
 }
        public Dictionary<string, protInfo> GetProfile(profileNode node,string listFile)
        {
            profileNode n=GetNode(node.internalName);
           
            if (n != null)
            {
                Type t = Type.GetType(internalList[n]);
                InternalProfileBase c = Activator.CreateInstance(t) as InternalProfileBase;
                progressInfo = c;
                Dictionary<string, protInfo> res = c.GetProfile(node, listFile, null);
                progressInfo = null;
                progress++;

                return res;
            }
            return null;
        }
Esempio n. 58
0
 public ShowEnvironment(IOctopusHelper octopusHelper, ILanguageProvider languageProvider, IProgressBar progressBar, IConfiguration configuration) : base(octopusHelper, languageProvider)
 {
     this.progressBar   = progressBar;
     this.configuration = configuration;
 }
        public IEnumerable <AssemblyInfo> Compile(IProgressBar progressBar = null)
        {
#if UNITY_2018_1_OR_NEWER
            var assemblies = CompilationPipeline.GetAssemblies(AssembliesType.Player);
#else
            var assemblies = CompilationPipeline.GetAssemblies();
#endif

#if UNITY_2018_2_OR_NEWER
            if (progressBar != null)
            {
                var numAssemblies = assemblies.Length;
                progressBar.Initialize("Assembly Compilation", "Compiling project scripts",
                                       numAssemblies);
                m_OnAssemblyCompilationStarted = (s) =>
                {
                    progressBar.AdvanceProgressBar(Path.GetFileName(s));
                };
                CompilationPipeline.assemblyCompilationStarted += m_OnAssemblyCompilationStarted;
            }
            CompilationPipeline.assemblyCompilationFinished += OnAssemblyCompilationFinished;

            m_OutputFolder = FileUtil.GetUniqueTempPathInProject();

            var input = new ScriptCompilationSettings
            {
                target = EditorUserBuildSettings.activeBuildTarget,
                group  = EditorUserBuildSettings.selectedBuildTargetGroup
            };

            var compilationResult = PlayerBuildInterface.CompilePlayerScripts(input, m_OutputFolder);

            if (progressBar != null)
            {
                progressBar.ClearProgressBar();
            }

            if (!m_Success)
            {
                Dispose();
                throw new AssemblyCompilationException();
            }

            var compiledAssemblyPaths = compilationResult.assemblies.Select(assembly => Path.Combine(m_OutputFolder, assembly));
#else
            // fallback to CompilationPipeline assemblies
            var compiledAssemblyPaths = CompilationPipeline.GetAssemblies()
                                        .Where(a => a.flags != AssemblyFlags.EditorAssembly).Select(assembly => assembly.outputPath);
#endif

            var assemblyInfos = new List <AssemblyInfo>();
            foreach (var compiledAssemblyPath in compiledAssemblyPaths)
            {
                var assemblyInfo = AssemblyHelper.GetAssemblyInfoFromAssemblyPath(compiledAssemblyPath);
                var assembly     = assemblies.First(a => a.name.Equals(assemblyInfo.name));
                var sourcePaths  = assembly.sourceFiles.Select(file => file.Remove(0, assemblyInfo.relativePath.Length + 1));

                assemblyInfo.sourcePaths = sourcePaths.ToArray();
                assemblyInfos.Add(assemblyInfo);
            }

            return(assemblyInfos);
        }
        public void RunProfile(string name,string listFile)
        {
            profileNode node=GetNode(name);

            if (node != null)
            {
                Type t = Type.GetType(internalList[node]);
                InternalProfileBase c = Activator.CreateInstance(t) as InternalProfileBase;
                c.CheckIfAvailable();
                progressInfo = c;
                c.RunThreads(listFile);
                progressInfo = null;
                progress ++;
            }

        }