protected async override void OnAppearing() { if (IsBusy) { return; } IsBusy = true; ViewModel.ErrorMessage = ""; base.OnAppearing(); IProgressDialog progress = null; try { progress = UserDialogs.Instance.Loading(TranslateServices.GetResourceString(CommonConstants.DialogLoading), maskType: MaskType.Clear); progress.Show(); InitContributionType(); await BindContributionAreas(); BindingSelectors(); } catch (Exception ex) { await UserDialogs.Instance.AlertAsync(string.Format(CommonConstants.DialogDescriptionForCheckNetworkFormat, ex.Message), TranslateServices.GetResourceString(CommonConstants.DialogOK)); } finally { progress?.Hide(); IsBusy = false; } }
protected async override void OnAppearing() { if (IsBusy) { return; } IsBusy = true; ViewModel.ErrorMessage = ""; base.OnAppearing(); IProgressDialog progress = null; try { progress = UserDialogs.Instance.Loading("Loading...", maskType: MaskType.Clear); progress.Show(); InitContributionType(); await BindContributionAreas(); BindingSelectors(); } catch { } finally { progress?.Hide(); IsBusy = false; } }
/// <summary> /// Shows the progress. /// </summary> /// <param name="visible">If set to <c>true</c> visible.</param> /// <param name="title">Title.</param> /// <param name="subtitle">Subtitle.</param> public void UpdateProgress(bool visible, string title = "", string subtitle = "") { if (_progressDialog == null && visible == false) { return; } if (_progressDialog == null) { _progressDialog = UserDialogs.Instance.Progress(); _progressDialog.IsDeterministic = false; } _progressDialog.Title = title ?? string.Empty; if (visible) { if (!_progressDialog.IsShowing) { _progressDialog.Show(); } } else { if (_progressDialog.IsShowing) { _progressDialog.Hide(); } _progressDialog = null; } }
async Task ExecuteTapQueueMessageCommandAsync(CloudQueueMessage queueMessage) { if (queueMessage == null) { return; } MessagingService.Current.Subscribe <MessageArgsDeleteQueueMessage>(MessageKeys.DeleteQueueMessage, async(m, argsDeleteQueueMessage) => { Navigation.PopAsync(); IProgressDialog deletingDialog = UserDialogs.Loading("Deleting Queue Message"); deletingDialog.Show(); try { var message = QueueMessages.Where(qm => qm.Id == argsDeleteQueueMessage.QueueId).FirstOrDefault(); if (message == null) { return; } await Queue.BaseQueue.DeleteMessageAsync(message); App.Logger.Track(AppEvent.DeleteQueueMessage.ToString()); QueueMessages.Remove(message); QueueMessageCount--; SortQueueMessages(); } catch (Exception ex) { Logger.Report(ex, "Method", "HandleMessageArgsDeleteQueueMessage"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { if (deletingDialog != null) { if (deletingDialog.IsShowing) { deletingDialog.Hide(); } deletingDialog.Dispose(); } } }); try { var queueMessageDetailsPage = new QueueMessageDetailsPage(queueMessage, queue); App.Logger.TrackPage(AppPage.QueueMessageDetails.ToString()); await NavigationService.PushAsync(Navigation, queueMessageDetailsPage); } catch (Exception ex) { Console.WriteLine("Ex: " + ex.Message); } }
async Task ExecuteTapFileShareCommandAsync(ASECloudFileShare fileShare) { if (fileShare == null) { return; } MessagingService.Current.Subscribe <MessageArgsDeleteFileShare>(MessageKeys.DeleteFileShare, async(m, argsDeleteFileShare) => { Navigation.PopAsync(); IProgressDialog deletingDialog = UserDialogs.Loading("Deleting FileShare"); deletingDialog.Show(); try { var aseFileShare = FileShares.Where(fs => fs.FileShareName == argsDeleteFileShare.FileShareName && fs.StorageAccountName == argsDeleteFileShare.StorageAccountName).FirstOrDefault(); if (aseFileShare == null) { return; } await aseFileShare.BaseFileShare.DeleteAsync(); App.Logger.Track(AppEvent.DeleteFileShare.ToString()); FileShares.Remove(aseFileShare); SortFileShares(); var realm = App.GetRealm(); await realm.WriteAsync(temprealm => { temprealm.Remove(temprealm.All <RealmCloudFileShare>() .Where(fs => fs.FileShareName == argsDeleteFileShare.FileShareName && fs.StorageAccountName == argsDeleteFileShare.StorageAccountName).First()); }); } catch (Exception ex) { Logger.Report(ex, "Method", "HandleMessageArgsDeleteFileShare"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { if (deletingDialog != null) { if (deletingDialog.IsShowing) { deletingDialog.Hide(); } deletingDialog.Dispose(); } } }); var filesPage = new FilesPage(fileShare); App.Logger.TrackPage(AppPage.Files.ToString()); await NavigationService.PushAsync(Navigation, filesPage); }
async Task ExecuteTapContainerCommandAsync(ASECloudBlobContainer container) { if (container == null) { return; } MessagingService.Current.Subscribe <MessageArgsDeleteContainer>(MessageKeys.DeleteContainer, async(m, argsDeleteContainer) => { Console.WriteLine("Delete containerX: " + argsDeleteContainer.ContainerName); Navigation.PopAsync(); IProgressDialog deletingDialog = UserDialogs.Loading("Deleting Container"); deletingDialog.Show(); try { var aseContainer = Containers.Where(c => c.ContainerName == argsDeleteContainer.ContainerName && c.StorageAccountName == argsDeleteContainer.StorageAccountName).FirstOrDefault(); if (aseContainer == null) { return; } await aseContainer.BaseContainer.DeleteAsync(); App.Logger.Track(AppEvent.DeleteContainer.ToString()); Containers.Remove(aseContainer); SortContainers(); var realm = App.GetRealm(); await realm.WriteAsync(temprealm => { temprealm.Remove(temprealm.All <RealmCloudBlobContainer>() .Where(c => c.ContainerName == argsDeleteContainer.ContainerName && c.StorageAccountName == argsDeleteContainer.StorageAccountName).First()); }); } catch (Exception ex) { Logger.Report(ex, "Method", "HandleMessageArgsDeleteContainer"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { if (deletingDialog != null) { if (deletingDialog.IsShowing) { deletingDialog.Hide(); } deletingDialog.Dispose(); } } }); var blobsPage = new BlobsPage(container); App.Logger.TrackPage(AppPage.Blobs.ToString()); await NavigationService.PushAsync(Navigation, blobsPage); }
async Task ExecuteTapContainerCommandAsync(ASECloudTable table) { if (table == null) { return; } MessagingService.Current.Subscribe <MessageArgsDeleteTable>(MessageKeys.DeleteTable, async(m, argsDeleteTable) => { Navigation.PopAsync(); IProgressDialog deletingDialog = UserDialogs.Loading("Deleting Table"); deletingDialog.Show(); try { var aseTable = Tables.Where(t => t.TableName == argsDeleteTable.TableName && t.StorageAccountName == argsDeleteTable.StorageAccountName).FirstOrDefault(); if (aseTable == null) { return; } await aseTable.BaseTable.DeleteIfExistsAsync(); App.Logger.Track(AppEvent.DeleteTable.ToString()); Tables.Remove(aseTable); SortTables(); var realm = App.GetRealm(); await realm.WriteAsync(temprealm => { temprealm.Remove(temprealm.All <RealmCloudTable>() .Where(t => t.TableName == argsDeleteTable.TableName && t.StorageAccountName == argsDeleteTable.StorageAccountName).First()); }); } catch (Exception ex) { Logger.Report(ex, "Method", "HandleMessageArgsDeleteTable"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { if (deletingDialog != null) { if (deletingDialog.IsShowing) { deletingDialog.Hide(); } deletingDialog.Dispose(); } } }); var tableRowsPage = new TableRowsPage(table); App.Logger.TrackPage(AppPage.TableRows.ToString()); await testPage.Navigation.PushAsync(tableRowsPage); }
protected void ShowBusy(string message) { if (_busy == null) { _busy = UserDialogs.Instance.Loading(message); } else if (!_busy.IsShowing) { _busy.Show(); } }
private void wb_Navigating(object sender, WebNavigatingEventArgs e) { if (_pd == null) { _pd = UserDialogs.Instance.Loading("Please wait", null, null, true, MaskType.Clear); } else { _pd.Show(); } }
public static bool TryConnectStart(int id_attempt) { var config = new ProgressDialogConfig() .SetTitle("Trying connect to internet...\n" + "Attempt: " + id_attempt) .SetIsDeterministic(false) .SetMaskType(MaskType.Clear); progress = UserDialogs.Instance.Progress(config); progress.Show(); return(true); }
public void Show(string message) { try { progress = DependencyService.Get <IProgressDialog>(); progress.Show(message); } catch (Exception ex) { throw ex; } }
/// <summary> /// Show a loading screen /// </summary> public static void ShowLoading(string text = null) { if (string.IsNullOrEmpty(text)) { text = AppResources.text_loading; } try { _loadingDialog = UserDialogs.Instance.Loading(text, maskType: MaskType.Gradient); _loadingDialog.Show(); } catch (Exception ex) { AddLog(ex.Message); } }
async void OnLogin_Clicked(object sender, EventArgs args) { loadingDialog = UserDialogs.Instance.Loading("Connecting...",null,null,false,MaskType.Gradient); if (String.IsNullOrEmpty(webSocketUrl.Text)) { await DisplayAlert("Validation Error", "Server URL is required", "Re-try"); } else { //if(false){ if (String.IsNullOrEmpty (username.Text) || String.IsNullOrEmpty (password.Text)) { await DisplayAlert ("Validation Error", "Username and Password are required", "Re-try"); } else { await App.Database.Delete_RemoteData_Item (); await App.Database.Delete_All_Login_Username_Show_For_Del (); loadingDialog.Show (); //System.Threading.Tasks.Task.Run (() => //{ ws_client = new WebSocketClient (); ws_client.Opened += websocket_Opened; ws_client.Closed += websocket_Closed; ws_client.MessageReceived += websocket_MessageReceived; //ws_client.AutoSendPongResponse = true; //}); try { Debug.WriteLine ("Websocket Opening....."); await ws_client.OpenAsync(webSocketUrl.Text); } catch (Exception ex) { Debug.WriteLine (ex.ToString()); Debug.WriteLine ("OpenAsync Exception"); UserDialogs.Instance.ShowError ("Can not Connect to Websocket Server"); } } } }
public void Sort(IProgressDialog progressDialog) { var backgroundWorker = new WriteSortToDiskBackgroundWorker(); var args = new WriteSortToDiskBackgroundWorker.Arguments( OutputDirectory, Form.MoveOrCopy, GroupList ); progressDialog.SubscribeToBackgroundWorker(backgroundWorker); backgroundWorker.RunWorkerCompleted += delegate { Form.OnProgressCompleted(); }; backgroundWorker.RunWorkerAsync(args); progressDialog.Show(); }
public void SortPreview(bool inDebugMode, IProgressDialog progressDialog) { var groupFormats = Form.SelectedGroupFormats; List <string> sourceDirectories = Form.SourceDirectories; string outputDirectory = Form.OutputDirectory; if (inDebugMode) { groupFormats = new List <string>() { GroupName.YEAR_FORMAT, GroupName.MONTH_FORMAT, GroupName.DAY_FORMAT, GroupName.HOUR_FORMAT }; sourceDirectories = new List <string>() { DEBUG_SOURCE }; outputDirectory = DEBUG_OUTPUT; } else if (!AreOptionsValid()) { return; } var backgroundWorker = new SortPreviewBackgroundWorker(); var args = new SortPreviewBackgroundWorker.Arguments( sourceDirectories, outputDirectory, Form.IncludeSubDirectories, groupFormats ); progressDialog.SubscribeToBackgroundWorker(backgroundWorker); backgroundWorker.RunWorkerCompleted += Form.OnSortPreviewComplete; backgroundWorker.RunWorkerAsync(args); progressDialog.Show(); }
async Task ExecuteTapFileCommandAsync(IListFileItem fileItem) { if (fileItem == null) { return; } MessagingService.Current.Subscribe <MessageArgsDeleteFile>(MessageKeys.DeleteFile, async(m, argsDeleteFile) => { Navigation.PopAsync(); IProgressDialog deletingDialog = UserDialogs.Loading("Deleting File"); deletingDialog.Show(); try { var file = Files.Where(f => f.Share.Name == argsDeleteFile.FileName).FirstOrDefault(); if (file == null) { return; } await FileShare.BaseFileShare.GetRootDirectoryReference().GetFileReference(file.Share.Name).DeleteAsync(); App.Logger.Track(AppEvent.DeleteFile.ToString()); Files.Remove(file); FileAndDirectoryCount--; SortFiles(); } catch (Exception ex) { Logger.Report(ex, "Method", "HandleMessageArgsDeleteFile"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { if (deletingDialog != null) { if (deletingDialog.IsShowing) { deletingDialog.Hide(); } deletingDialog.Dispose(); } } }); }
private async Task SetLocation(Location location, bool isPreparing = false) { try { if (!isPreparing) { _progressDialogs.Show(); } Location = location; NearbyMarker = await _locationsRepository.GetNearbyEntries(location, _appSettings.NearbyMarkerCount, false); } finally { if (!isPreparing && _progressDialogs.IsShowing) { _progressDialogs.Hide(); } } }
private async void Send(object sender, EventArgs e) { IProgressDialog waiter = null; try { UserModel[] additionalVolunteers = viewModel.AdditionalVolunteers.Select(m => m.Model).ToArray(); double hours = viewModel.Hours; DateTime now = DateTime.UtcNow; UserModel user = UserModel.CurrentUser; IDataStore <Event> dataStore = DependencyService.Get <IDataStore <Event> >() ?? new MockDataStore(); EventCheckInModel checkIn = new EventCheckInModel(); checkIn.EventId = program.Id; checkIn.CheckinDate = now; checkIn.HourCount = hours; checkIn.ParentUserEmail = null; checkIn.UserEmail = user.Email; waiter = UserDialogs.Instance.Loading("Sending...", maskType: MaskType.Clear); waiter.Show(); bool result = await dataStore.CheckInUserOnEventAsync(checkIn); if (!result) { throw new Exception(); } waiter?.Hide(); await Navigation.PopAsync(); } catch { waiter?.Hide(); await DisplayAlert("Error", "Cannot save hours", "OK"); } }
protected async override void OnAppearing() { base.OnAppearing(); this.viewModel = this.BindingContext as PetServicesViewModel; IProgressDialog l = App.GetLoadingDialog(AppSettings.Constants.LoaderText); l.Show(); try { await viewModel.LoadContents(); l.Hide(); } catch (Exception) { l.Hide(); await DisplayAlert(AppSettings.Constants.DisplayGeneralErrorDlgTitle, AppSettings.Constants.DisplayGeneralErrorDlgMessage, "OK"); } company = CompanyInformation.GetDefault(); this.PetServicesList.ItemsSource = viewModel.PetServices; }
/// <summary> /// Called when starting the app (and loading this page) or when returning to this page from another page /// </summary> protected override void OnAppearing() { // Just returned from bluetooth device page that is no longer visible if (bluetoothDevicePage != null) { bluetoothDevicePage = null; bluetooth.endEnumeration(); if (deviceToConnectTo > -1) { if (deviceToConnectTo >= discoveredDevices.Count) { Debug.WriteLine("An invalid device was selected. Index was " + deviceToConnectTo + " but there were only " + discoveredDevices.Count + " devices."); return; } bluetooth.connect(discoveredDevices[deviceToConnectTo]); connectProgressDialog = UserDialogs.Instance.Progress( new ProgressDialogConfig() { Title = AppResources.Connecting + deviceNames[deviceToConnectTo], IsDeterministic = false, OnCancel = () => { bluetooth.cancelConnect(); bluetooth.disconnect(); }, CancelText = AppResources.Cancel } ); connectProgressDialog.Show(); connectedDeviceName = deviceNames[deviceToConnectTo]; deviceToConnectTo = -1; } else { Debug.WriteLine("Was told to connect to -1"); } } }
/// <summary> /// Show a loading screen with cancel button /// </summary> public static void ShowLoading(string text, string cancelText, CancellationTokenSource cts) { if (string.IsNullOrEmpty(text)) { text = AppResources.text_loading; } Action ca = null; if (cts != null) { ca = () => cts.Cancel(); } try { _loadingDialog = UserDialogs.Instance.Loading(text, ca, cancelText, maskType: MaskType.Gradient); _loadingDialog.Show(); } catch (Exception) { // ignored } }
private async void GetProfile() { IProgressDialog progress = null; if (string.IsNullOrEmpty(MyProfileViewModel.Instance.FirstAwardValue)) { try { progress = UserDialogs.Instance.Loading("Loading...", maskType: MaskType.Clear); progress.Show(); ProfileModel profile = null; CheckCache(); CheckCacheItem(); if (cacheItem.ContainsKey(CommonConstants.ProfileCacheKey)) { DateTime cachedDate = DateTime.Parse(cacheItem[CommonConstants.ProfileCacheDateKey].ToString()); DateTime ExpiredDate = cachedDate.AddHours(24); if (DateTime.Compare(ExpiredDate, DateTime.Now) > 0) //Valid data. { string profileString = cacheItem[CommonConstants.ProfileCacheKey].ToString(); profile = Newtonsoft.Json.JsonConvert.DeserializeObject <ProfileModel>(profileString); } else { profile = await MvpHelper.MvpService.GetProfile(LogOnViewModel.StoredToken); cacheItem[CommonConstants.ProfileCacheKey] = Newtonsoft.Json.JsonConvert.SerializeObject(profile); cacheItem[CommonConstants.ProfileCacheDateKey] = DateTime.Now; cache[currentUserIdKey] = cacheItem; } } else { profile = await MvpHelper.MvpService.GetProfile(LogOnViewModel.StoredToken); cacheItem.Add(CommonConstants.ProfileCacheKey, Newtonsoft.Json.JsonConvert.SerializeObject(profile)); cacheItem.Add(CommonConstants.ProfileCacheDateKey, DateTime.Now); cache[currentUserIdKey] = cacheItem; } Application.Current.Properties[CommonConstants.ProfileCacheListKey] = cache; if (profile != null) { MyProfileViewModel.Instance.FirstAwardValue = profile.FirstAwardYear.ToString(System.Globalization.CultureInfo.CurrentCulture); MyProfileViewModel.Instance.PersonName = profile.DisplayName; MyProfileViewModel.Instance.MvpNumber = $"MVP {profile.MvpId}"; MyProfileViewModel.Instance.AwardCategoriesValue = profile.AwardCategoryDisplay.Replace(",", Environment.NewLine); MyProfileViewModel.Instance.Description = profile.Biography; MyProfileViewModel.Instance.AwardsCountValue = profile.YearsAsMVP.ToString(System.Globalization.CultureInfo.CurrentCulture); } } catch (Exception ex) { progress?.Hide(); await UserDialogs.Instance.AlertAsync("Looks like something went wrong. Please check your connection.. Error: " + ex.Message, "Unable to load", "OK"); } finally { progress?.Hide(); } } }
public async void ButtonSaveClicked(object sender, EventArgs e) { IProgressDialog progress = null; try { bool isValid = CheckData(); if (!isValid) { return; } if (!CrossConnectivity.Current.IsConnected) { await UserDialogs.Instance.AlertAsync("Please check connectivity to submit activity.", "Check Connectivity", "OK"); return; } IsBusy = true; progress = UserDialogs.Instance.Loading("Saving...", maskType: MaskType.Clear); progress.Show(); if (ViewModel.MyContribution == null) { var model = new ContributionModel() { ContributionId = "0", ContributionType = ViewModel.ContributionTypeNames[contributionTypeSelector.SelectedIndex], ContributionTechnology = ViewModel.ContributionAreas[ContributionAreaSelector.SelectedIndex], Visibility = ViewModel.PersonGroups[PersonGroupSelector.SelectedIndex], StartDate = ContributionDateSelector.Date.ToUniversalTime(), Title = entryTitle.Text, ReferenceUrl = entryURL.Text, Description = entryDescription.Text, AnnualQuantity = Convert.ToInt32(entryAnnualQuantity.Text, System.Globalization.CultureInfo.InvariantCulture), AnnualReach = Convert.ToInt32(entryAnnualReach.Text, System.Globalization.CultureInfo.InvariantCulture), SecondAnnualQuantity = Convert.ToInt32(entrySecondAnnualQuantity.Text, System.Globalization.CultureInfo.InvariantCulture) }; var result = await MvpHelper.MvpService.AddContributionModel(model, LogOnViewModel.StoredToken); if (result != null && result.ContributionId != "0") { Logger.Log("Activity-Added"); MvpHelper.SetLabelTextOfContribution(result); MyProfileViewModel.Instance.List.Insert(0, result); MyProfileViewModel.Instance.TotalOfData += 1; } else { return; } } else { ViewModel.MyContribution.ContributionType = ViewModel.ContributionTypeNames[contributionTypeSelector.SelectedIndex]; ViewModel.MyContribution.ContributionTechnology = ViewModel.ContributionAreas[ContributionAreaSelector.SelectedIndex]; ViewModel.MyContribution.Visibility = ViewModel.PersonGroups[PersonGroupSelector.SelectedIndex]; ViewModel.MyContribution.StartDate = ContributionDateSelector.Date.ToUniversalTime(); ViewModel.MyContribution.AnnualQuantity = Convert.ToInt32(entryAnnualQuantity.Text, System.Globalization.CultureInfo.InvariantCulture); ViewModel.MyContribution.AnnualReach = Convert.ToInt32(entryAnnualReach.Text, System.Globalization.CultureInfo.InvariantCulture); ViewModel.MyContribution.SecondAnnualQuantity = Convert.ToInt32(entrySecondAnnualQuantity.Text, System.Globalization.CultureInfo.InvariantCulture); string result = await MvpHelper.MvpService.EditContributionModel(ViewModel.MyContribution, LogOnViewModel.StoredToken); if (result == CommonConstants.OkResult) { Logger.Log("Activity-Edit"); MyProfileViewModel.Instance.List = new ObservableRangeCollection <ContributionModel>(MyProfileViewModel.Instance.List); } else { var currentContribution = MyProfileViewModel.Instance.List.Where(item => item.ContributionId == ViewModel.MyContribution.ContributionId).FirstOrDefault(); int index = MyProfileViewModel.Instance.List.IndexOf(currentContribution); MyProfileViewModel.Instance.List.Remove(currentContribution); MyProfileViewModel.Instance.List.Insert(index, ViewModel.MyContributionBackup); return; } } ViewModel.MyContribution = null; #if DEBUG await Task.Delay(3000); #endif progress?.Hide(); await UserDialogs.Instance.AlertAsync("MVP activity has been saved successfully. Thank you for your contribution.", "Saved!", "OK"); await Navigation.PopModalAsync(); } catch (Exception ex) { progress?.Hide(); ViewModel.ErrorMessage = ex.Message; await UserDialogs.Instance.AlertAsync("Looks like something went wrong. Please check your connection and submit again. Error: " + ex.Message, "Unable to save", "OK"); } finally { if (progress?.IsShowing ?? false) { progress?.Hide(); } IsBusy = false; } }
async Task ExecuteCreateContainerAsync() { if (IsBusy) { return; } if (!ReadyToSave) { //This should never happen as the save button should be disabled Logger.Report(new Exception("Create container called when ReadyToSave was false"), "Method", "ExecuteCreateContainerAsync"); return; } if (containerName.Length < 3 || containerName.Length > 63 || !Regex.IsMatch(containerName, @"^[a-z0-9]+(-[a-z0-9]+)*$")) { MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Container name is invalid", Message = "Container names must be between 3 and 63 chars, only contain lowercase letters, numbers, and hyphens, must begin with a number or letter, must not contain consecutive hyphens, or end with a hyphen.", Cancel = "OK" }); return; } IProgressDialog savingDialog = UserDialogs.Loading("Saving Container"); savingDialog.Show(); try { IsBusy = true; string connectionString = Constants.StorageConnectionString; connectionString = connectionString.Replace("<ACCOUNTNAME>", SelectedStorageAccount.Name); connectionString = connectionString.Replace("<ACCOUNTKEY>", SelectedStorageAccount.PrimaryKey); CloudStorageAccount sa = CloudStorageAccount.Parse(connectionString); var blobClient = sa.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(ContainerName); if (container == null) { Console.WriteLine("Container is null"); } if (await container.ExistsAsync()) { MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Container Exists", Message = "A container with the name \"" + ContainerName + "\" already exists in this storage account.", Cancel = "OK" }); return; } else { await container.CreateAsync(); if (SelectedAccessType != "Private") { if (SelectedAccessType == "Container") { await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container }); } else if (SelectedAccessType == "Blob") { await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); } } var realm = App.GetRealm(); var storageAccountName = selectedStorageAccount.Name; realm.Write(() => { realm.Add(new RealmCloudBlobContainer(container.Name, selectedStorageAccount.Name, container.Uri.ToString())); }); if (containersVM != null) { containersVM.AddContainer(new ASECloudBlobContainer(container, selectedStorageAccount.Name)); App.Logger.Track(AppEvent.CreatedContainer.ToString()); } //This is here and in finally so we'll dismiss this before popping the page so the //Loader doesn't stay longer than the popup if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } await PopupNavigation.PopAsync(); } } catch (Exception ex) { Logger.Report(ex, "Method", "ExecuteCreateContainerAsync"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { IsBusy = false; if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } } return; }
async Task ExecuteCreateTableAsync() { if (IsBusy) { return; } if (!ReadyToSave) { Logger.Report(new Exception("Create table called when ReadyToSave was false"), "Method", "ExecuteCreateTableAsync"); return; } if (tableName.Length < 3 || tableName.Length > 63 || !Regex.IsMatch(tableName, @"^[A-Za-z][A-Za-z0-9]*$")) { MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Table name is invalid", Message = "Table names must be between 3 and 63 chars, only contain letters and numbers, and start with a letter.", Cancel = "OK" }); return; } IProgressDialog savingDialog = UserDialogs.Loading("Saving Table"); savingDialog.Show(); try { IsBusy = true; string connectionString = Constants.StorageConnectionString; connectionString = connectionString.Replace("<ACCOUNTNAME>", SelectedStorageAccount.Name); connectionString = connectionString.Replace("<ACCOUNTKEY>", SelectedStorageAccount.PrimaryKey); CloudStorageAccount sa = CloudStorageAccount.Parse(connectionString); var tableClient = sa.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference(tableName); if (table == null) { Console.WriteLine("Table is null"); } if (await table.ExistsAsync()) { MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Table Exists", Message = "A table with the name \"" + TableName + "\" already exists in this storage account.", Cancel = "OK" }); return; } else { await table.CreateAsync(); var realm = App.GetRealm(); var storageAccountName = selectedStorageAccount.Name; realm.Write(() => { realm.Add(new RealmCloudTable(table.Name, selectedStorageAccount.Name, table.Uri.ToString())); }); if (tablesVM != null) { tablesVM.AddTable(new ASECloudTable(table, selectedStorageAccount.Name)); App.Logger.Track(AppEvent.CreatedTable.ToString()); } //This is here and in finally so we'll dismiss this before popping the page so the //Loader doesn't stay longer than the popup if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } await PopupNavigation.PopAsync(); } } catch (Exception ex) { Logger.Report(ex, "Method", "ExecuteCreateTableAsync"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { IsBusy = false; if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } } return; }
async Task ExecuteCreateQueueMessageAsync() { if (IsBusy) { return; } if (!ReadyToSave) { //This should never happen as the save button should be disabled Logger.Report(new Exception("Create Queue Message called when ReadyToSave was false"), "Method", "ExecuteCreateQueueMessageAsync"); return; } //Messages must expire in 1 second to 7 days //Calculate time to live TimeSpan?messageTTL = null; switch (SelectedExpirationTimePeriod) { case "Days": messageTTL = new TimeSpan(ExpiresInTime, 0, 0, 0); break; case "Hours": messageTTL = new TimeSpan(0, ExpiresInTime, 0, 0); break; case "Minutes": messageTTL = new TimeSpan(0, 0, ExpiresInTime, 0); break; case "Seconds": messageTTL = new TimeSpan(0, 0, 0, ExpiresInTime); break; } if (messageTTL < MinimumExpirationtime || messageTTL > MaximumExpirationtime) { MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Expiration time is invalid", Message = "Messages must expire in no less than 1 second and no more than 7 days.", Cancel = "OK" }); return; } IProgressDialog savingDialog = UserDialogs.Loading("Saving Queue Message"); savingDialog.Show(); try { IsBusy = true; var newMessage = new CloudQueueMessage(MessageText); await queueMessagesViewModel.Queue.BaseQueue.AddMessageAsync(newMessage, messageTTL, null, null, null); if (queueMessagesViewModel != null) { queueMessagesViewModel.AddQueueMessage(newMessage); App.Logger.Track(AppEvent.CreatedQueueMessage.ToString()); } //This is here and in finally so we'll dismiss this before popping the page so the //Loader doesn't stay longer than the popup if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } await PopupNavigation.PopAsync(); } catch (Exception ex) { Logger.Report(ex, "Method", "ExecuteCreateQueueMessageAsync"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { IsBusy = false; if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } } return; }
async void OnDelete(object sender, EventArgs e) { var mi = ((MenuItem)sender); var remoteData = (RemoteData)mi.BindingContext; var answer = await DisplayAlert ("Confirm?", "Would you like to delete " + remoteData.remote_button_name, "Yes", "No"); if (answer.Equals (true)) { waitRemoteDialog = UserDialogs.Instance.Loading("Deleteting...",null,null,false,MaskType.Gradient); waitRemoteDialog.Show (); remoteData.remote_button_name = remoteData.remote_button_name; remoteData.node_command = "delete_button_remote"; string jsonCommandaddRemoteButton = JsonConvert.SerializeObject(remoteData, Formatting.Indented); System.Diagnostics.Debug.WriteLine ("{0}",jsonCommandaddRemoteButton); await LoginPage.ws_client.SendAsync (jsonCommandaddRemoteButton); } else { } }
async Task ExecuteTapBlobCommandAsync(CloudBlob blob) { if (blob == null) { return; } MessagingService.Current.Subscribe <MessageArgsDeleteBlob>(MessageKeys.DeleteBlob, async(m, argsDeleteBlob) => { Navigation.PopAsync(); IProgressDialog deletingDialog = UserDialogs.Loading("Deleting Blob"); deletingDialog.Show(); try { var aseBlob = Blobs.Where(b => b.Name == argsDeleteBlob.BlobName && b.Container.Name == argsDeleteBlob.ContainerName).FirstOrDefault(); if (aseBlob == null) { return; } await aseBlob.DeleteAsync(); App.Logger.Track(AppEvent.DeleteBlob.ToString()); Blobs.Remove(aseBlob); byteCount -= aseBlob.Properties.Length; BlobCount = Blobs.Count.ToString(); TotalBlobSize = FileSizeHelper.GetHumanizedSizeFromBytes(byteCount); SortBlobs(); } catch (Exception ex) { Logger.Report(ex, "Method", "HandleMessageArgsDeleteBlob"); MessagingService.Current.SendMessage(MessageKeys.Error, ex); } finally { if (deletingDialog != null) { if (deletingDialog.IsShowing) { deletingDialog.Hide(); } deletingDialog.Dispose(); } } }); try { var blobDetailsPage = new BlobDetailsPage(blob); App.Logger.TrackPage(AppPage.BlobDetails.ToString()); await NavigationService.PushAsync(Navigation, blobDetailsPage); } catch (Exception ex) { Console.WriteLine("Ex: " + ex.Message); } }
async Task ExecuteAddBlobCommandAsync() { if (IsBusy) { return; } IProgressDialog savingDialog = null; try { //Check for Storage Permissions var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location)) { MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Need storage access", Message = "In order to upload new blobs, we need access to your phone's storage.", Cancel = "OK" }); } var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Storage }); status = results[Permission.Storage]; } if (status == PermissionStatus.Granted) { var result = await DependencyService.Get <IFilePicker>().PickFile(); if (result != null) { savingDialog = UserDialogs.Loading("Saving Blob"); savingDialog.Show(); var blob = Container.BaseContainer.GetBlockBlobReference(result.FileName); if (await blob.ExistsAsync()) { savingDialog.Hide(); MessagingService.Current.SendMessage <MessagingServiceQuestion>(MessageKeys.Question, new MessagingServiceQuestion { Negative = "No", Positive = "Yes", Question = "A blob with the same name already exists in this Container, would you like to overwrite?", Title = "Overwrite blob?", OnCompleted = (async(questionResult) => { if (questionResult) { try { savingDialog.Show(); await blob.FetchAttributesAsync(); byteCount -= blob.Properties.Length; await blob.UploadFromByteArrayAsync(result.DataArray, 0, result.DataArray.Length); byteCount += blob.Properties.Length; TotalBlobSize = FileSizeHelper.GetHumanizedSizeFromBytes(byteCount); App.Logger.Track(AppEvent.OverwriteBlob.ToString()); } catch (Exception ex) { Logger.Report(ex); MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Unable to Overwrite Blob", Message = "There was an issue trying to overwrite blob in storage. Please try again.", Cancel = "OK" }); } finally { if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } } } } ) }); } else { await blob.UploadFromByteArrayAsync(result.DataArray, 0, result.DataArray.Length); App.Logger.Track(AppEvent.CreatedBlob.ToString()); Blobs.Add((CloudBlob)blob); byteCount += blob.Properties.Length; BlobCount = Blobs.Count.ToString(); TotalBlobSize = FileSizeHelper.GetHumanizedSizeFromBytes(byteCount); SortBlobs(); } } } } catch (Exception ex) { Logger.Report(ex); MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Unable to Save Blob", Message = "There was an issue trying to save to blob storage. Please try again.", Cancel = "OK" }); } finally { if (savingDialog != null) { if (savingDialog.IsShowing) { savingDialog.Hide(); } savingDialog.Dispose(); } } }
async void OnRename(object sender, EventArgs e) { var mi = ((MenuItem)sender); var remote = (RemoteData)mi.BindingContext; var result = await UserDialogs.Instance.PromptAsync(new PromptConfig { Title = "Rename", Text = remote.remote_button_name, IsCancellable = true, Placeholder = "Type new name" }); if(!result.Text.Equals(remote.new_button_name)){ waitRemoteDialog = UserDialogs.Instance.Loading("Renaming...",null,null,false,MaskType.Gradient); waitRemoteDialog.Show (); var newName = result.Text; RemoteData itemRemote = new RemoteData(); itemRemote.remote_button_name = remote.remote_button_name; itemRemote.node_command = "ir_remote_rename"; itemRemote.new_button_name = newName; itemRemote.node_addr = remote.node_addr; itemRemote.remote_username = remote.remote_username; string jsonCommandaddRemoteButton = JsonConvert.SerializeObject(itemRemote, Formatting.Indented); System.Diagnostics.Debug.WriteLine ("{0}",jsonCommandaddRemoteButton); await LoginPage.ws_client.SendAsync (jsonCommandaddRemoteButton); } System.Diagnostics.Debug.WriteLine("RenameRemote_Clicked"); }