/// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param> /// <param name="value">The System.Object to convert.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { Type type = ((EntityValueConverterContext)context).Property.Property.PropertyType; if (value is int) return Enum.ToObject(type, (int)value); return Enum.Parse(type, (string)value); }
public object Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { if (value is int) return new Thickness { Left = (int) value }; if (value is double) return new Thickness { Left = (double) value }; return new Thickness(); }
public override object ConvertFrom(ComponentModel.ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { if(value is string) { return DataUri.Parse((string)value); } return base.ConvertFrom(context, culture, value); }
object IValueConverter.Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { if (ReferenceEquals(value, null)) return Visibility.Collapsed; var str = parameter as string; return str == "IsNullOrWhiteSpace" ? ((value as string).IsNullOrWhiteSpace() ? Visibility.Collapsed : Visibility.Visible) : ((value as string).IsNullOrEmpty() ? Visibility.Collapsed : Visibility.Visible); }
/// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param> /// <param name="value">The System.Object to convert.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { if (context == null) throw new ArgumentNullException("context"); Guid id; if (!Guid.TryParse((string)value, out id)) return null; dynamic queryable = context.GetService(((EntityValueConverterContext)context).Property.Property.PropertyType); return queryable.GetEntity(id); }
/// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A System.Globalization.CultureInfo. If null is passed, the current culture is assumed.</param> /// <param name="value">The System.Object to convert.</param> /// <param name="destinationType">The System.Type to convert the value parameter to.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value, Type destinationType) { Type type = value.GetType(); string name = Enum.GetName(type, value); FieldInfo field = type.GetField(name, Reflection.BindingFlags.Public | Reflection.BindingFlags.Static); DescriptionAttribute description = field.GetCustomAttribute<DescriptionAttribute>(); if (description != null) return description.Description; DisplayAttribute display = field.GetCustomAttribute<DisplayAttribute>(); if (display != null) return display.Name; return name; }
public object Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { ModelItem modelItem = value as ModelItem; if (modelItem != null) { EditingContext editingContext = modelItem.GetEditingContext(); if (editingContext != null) { return editingContext.Services.GetService<DesignerConfigurationService>().AnnotationEnabled; } } return false; }
public object Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { // I do use reflection for this. Another way would be to force the viewModel to implement sth like // IDragSource and IDropTarget. Then I could cast and return the method. Would probably be more // performant, but we force the viewmodel to reference an controls assembly. Lets try this code // until someone dont likes it. ;o) var mi = value.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance); if (mi == null) { throw new InvalidOperationException("Could not find method with name '" + methodName + "' on type '" + value.GetType() + "'."); } if (targetType == typeof(Func<object, bool>)) { return new Func<object, bool>(x => (bool)mi.Invoke(value, new object[] { x })); } else if (targetType == typeof(Func<int, object, bool>)) { return new Func<int, object, bool>((i, x) => (bool)mi.Invoke(value, new object[] { i, x })); } else if (targetType == typeof(Func<string, bool>)) { return new Func<string, bool>(s => (bool)mi.Invoke(value, new object[] { s })); } else if (targetType == typeof(Func<int, string, bool>)) { return new Func<int, string, bool>((i, s) => (bool)mi.Invoke(value, new object[] { i, s })); } else if (targetType == typeof(Action<object>)) { return new Action<object>(x => mi.Invoke(value, new object[] { x })); } else if (targetType == typeof(Action<int, object>)) { return new Action<int, object>((i, x) => mi.Invoke(value, new object[] { i, x })); } else if (targetType == typeof(Func<bool>)) { return new Func<bool>(() => (bool)mi.Invoke(value, new object[] { })); } else if (targetType == typeof(Func<object>)) { return new Func<object>(() => mi.Invoke(value, null)); } return null; }
/// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param> /// <param name="value">The System.Object to convert.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { if (context == null) throw new ArgumentNullException("context"); string[] ids = ((string)value).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List<object> items = new List<object>(); dynamic queryable = context.GetService(typeof(IEntityContext<>).MakeGenericType(((EntityValueConverterContext)context).Property.ClrType.GetGenericArguments()[0])); for (int i = 0; i < ids.Length; i++) { Guid id; if (!Guid.TryParse(ids[i], out id)) continue; object item = queryable.GetEntity(id); if (item != null) items.Add(item); } return items.ToArray(); }
/// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A System.Globalization.CultureInfo. If null is passed, the current culture is assumed.</param> /// <param name="value">The System.Object to convert.</param> /// <param name="destinationType">The System.Type to convert the value parameter to.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value, Type destinationType) { Type type = value.GetType(); if (type.GetCustomAttribute<FlagsAttribute>() != null) { Enum v = (Enum)value; Array values = Enum.GetValues(type); List<string> target = new List<string>(); foreach (Enum item in values) { if (!v.HasFlag(item)) continue; string name = Enum.GetName(type, item); FieldInfo field = type.GetField(name, Reflection.BindingFlags.Public | Reflection.BindingFlags.Static); DescriptionAttribute description = field.GetCustomAttribute<DescriptionAttribute>(); if (description != null) { target.Add(description.Description); continue; } DisplayAttribute display = field.GetCustomAttribute<DisplayAttribute>(); if (display != null) target.Add(display.Name); else target.Add(name); } return string.Join(", ", target); } else { string name = Enum.GetName(type, value); FieldInfo field = type.GetField(name, Reflection.BindingFlags.Public | Reflection.BindingFlags.Static); DescriptionAttribute description = field.GetCustomAttribute<DescriptionAttribute>(); if (description != null) return description.Description; DisplayAttribute display = field.GetCustomAttribute<DisplayAttribute>(); if (display != null) return display.Name; return name; } }
private void AddLanguageLink(string culture, Node node, HtmlGenericControl listControl, string languageAsText, bool showImage) { if (node.Culture != base.PageEngine.RootNode.Culture) { HtmlGenericControl listItem = new HtmlGenericControl("li"); HyperLink hpl = new HyperLink(); hpl.NavigateUrl = UrlUtil.GetUrlFromNode(node); hpl.Text = languageAsText; if (showImage) { string countryCode = Globalization.GetCountryFromCulture(culture).ToLower(); string imageUrl = this.TemplateSourceDirectory + String.Format("/Images/flags/{0}.png", countryCode); Image image = new Image(); image.ImageUrl = imageUrl; image.AlternateText = languageAsText; hpl.ToolTip = languageAsText; hpl.Controls.Add(image); } listItem.Controls.Add(hpl); listControl.Controls.Add(listItem); } }
public async void ShouldReturnDebugCollectionInformation(string yamlFile) { // IMPORTANT please the nl-NL language at the end of the collection, as other // tests are primarily tested under nl-NL yaml test files. foreach (var language in new[] { "en-US", "nl-NL" }) { Globalization.SetKeywordResourceCulture(new System.Globalization.CultureInfo(language)); Globalization.SetFormattingExceptionResourceCulture(new System.Globalization.CultureInfo(language)); var controller = new YamlScriptController(); var result = controller.Parse(YamlTestFileLoader.Load($"Malformed/{language}/{yamlFile}.yaml")); Assert.True(result.IsError); Assert.NotNull(result.Exceptions); Assert.NotNull(result.Message); Output.WriteLine(result.Message); foreach (var exception in result.Exceptions.Exceptions) { Assert.NotNull(exception.Message); Assert.NotNull(exception.DebugInfo); Output.WriteLine($"{language}: {exception.Message} {exception.DebugInfo}"); } } }
private async void EjectButton_Click(object sender, RoutedEventArgs e) { if (DeviceGrid.SelectedItem is HardDeviceInfo Item) { if (string.IsNullOrEmpty(Item.Folder.Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueContentDialog_UnableToEject_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(false); } else { foreach (TabViewItem Tab in TabViewContainer.ThisPage.TabViewControl.TabItems.Select((Obj) => Obj as TabViewItem).Where((Tab) => Tab.Content is Frame frame && CommonAccessCollection.FrameFileControlDic.ContainsKey(frame) && Path.GetPathRoot(CommonAccessCollection.FrameFileControlDic[frame].CurrentFolder?.Path) == Item.Folder.Path).ToArray()) { await TabViewContainer.ThisPage.CleanUpAndRemoveTabItem(Tab).ConfigureAwait(true); } if (await FullTrustProcessController.Current.EjectPortableDevice(Item.Folder.Path).ConfigureAwait(true)) { ShowEjectNotification(); } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueContentDialog_UnableToEject_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(false); } } } }
private async void ClearRecycleBin_Click(object sender, RoutedEventArgs e) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_WarningTitle"), Content = Globalization.GetString("QueueDialog_EmptyRecycleBin_Content"), PrimaryButtonText = Globalization.GetString("Common_Dialog_ContinueButton"), CloseButtonText = Globalization.GetString("Common_Dialog_CancelButton") }; if (await Dialog.ShowAsync().ConfigureAwait(true) == ContentDialogResult.Primary) { await ActivateLoading(true, Globalization.GetString("RecycleBinEmptyingText")).ConfigureAwait(true); if (await FullTrustProcessController.Current.EmptyRecycleBinAsync().ConfigureAwait(true)) { await ActivateLoading(false).ConfigureAwait(true); FileCollection.Clear(); HasFile.Visibility = Visibility.Visible; ClearRecycleBin.IsEnabled = false; } else { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_RecycleBinEmptyError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); await ActivateLoading(false).ConfigureAwait(true); } } }
private async void Save_Click(object sender, RoutedEventArgs e) { try { if (CurrentEncoding != null) { try { using (FileStream Stream = FileSystemStorageItemBase.Create(TextFile.Path, StorageItemTypes.File, CreateOption.ReplaceExisting).GetFileStreamFromFile(AccessMode.Write)) using (StreamWriter Writer = new StreamWriter(Stream, CurrentEncoding)) { await Writer.WriteAsync(Text.Text).ConfigureAwait(true); } } catch { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_CouldReadWriteFile_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync().ConfigureAwait(true); } Frame.GoBack(); } else { InvalidTip.IsOpen = true; } } catch { InvalidTip.IsOpen = true; } }
private async void Location_Click(object sender, RoutedEventArgs e) { if (SearchResultList.SelectedItem is FileSystemStorageItemBase Item) { try { StorageFolder ParentFolder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(Item.Path)); if (WeakToFileControl.TryGetTarget(out FileControl Control)) { Frame.GoBack(); await Control.OpenTargetFolder(ParentFolder).ConfigureAwait(true); await JumpListController.Current.AddItem(JumpListGroup.Recent, ParentFolder).ConfigureAwait(true); if (Control.Presenter.FileCollection.FirstOrDefault((SItem) => SItem.Path == Item.Path) is FileSystemStorageItemBase Target) { Control.Presenter.ItemPresenter.ScrollIntoView(Target); Control.Presenter.SelectedItem = Target; } } } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(Location_Click)}"); QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LocateFolderFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } } }
private void BindLanguageOptions() { Dictionary <string, Node> cultureNodes = this._module.GetCultureRootNodesBySite(base.PageEngine.CurrentSite); HtmlGenericControl listControl = new HtmlGenericControl("ul"); listControl.EnableViewState = false; foreach (KeyValuePair <string, Node> cultureNode in cultureNodes) { string languageAsText = Globalization.GetNativeLanguageTextFromCulture(cultureNode.Key); switch (this._module.DisplayMode) { case DisplayMode.Text: AddLanguageLink(cultureNode.Key, cultureNode.Value, listControl, languageAsText, false); break; case DisplayMode.Flag: AddLanguageLink(cultureNode.Key, cultureNode.Value, listControl, languageAsText, true); break; case DisplayMode.DropDown: AddDropDownOption(cultureNode.Key, languageAsText); break; } // Also add the language and root url to the list of possible redirectable urls. We can use this // later to redirect to the root node that corresponds with the browser language if there is no // specific page requested. if (cultureNode.Key != base.PageEngine.RootNode.Culture) { this._homePagesForLanguages.Add(Globalization.GetLanguageFromCulture(cultureNode.Key), UrlHelper.GetUrlFromNode(cultureNode.Value)); } } if (this._module.DisplayMode == DisplayMode.Text || this._module.DisplayMode == DisplayMode.Flag) { this.plhLanguageLinks.Controls.Add(listControl); } }
private async void SearchResultList_DoubleTapped(object sender, Windows.UI.Xaml.Input.DoubleTappedRoutedEventArgs e) { if ((e.OriginalSource as FrameworkElement).DataContext is FileSystemStorageItemBase Item) { try { string ParentFolderPath = Path.GetDirectoryName(Item.Path); if (WeakToFileControl.TryGetTarget(out FileControl Control)) { Frame.GoBack(); await Control.CurrentPresenter.DisplayItemsInFolder(ParentFolderPath).ConfigureAwait(true); await JumpListController.Current.AddItemAsync(JumpListGroup.Recent, ParentFolderPath).ConfigureAwait(true); if (Control.CurrentPresenter.FileCollection.FirstOrDefault((SItem) => SItem == Item) is FileSystemStorageItemBase Target) { Control.CurrentPresenter.ItemPresenter.ScrollIntoView(Target); Control.CurrentPresenter.SelectedItem = Target; } } } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(Location_Click)}"); QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LocateFolderFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } } }
private async Task Initialize() { if (MediaFile.FileType == ".mp3" || MediaFile.FileType == ".flac" || MediaFile.FileType == ".wma" || MediaFile.FileType == ".m4a" || MediaFile.FileType == ".alac") { MusicCover.Visibility = Visibility.Visible; MediaPlaybackItem Item = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(MediaFile)); MediaItemDisplayProperties Props = Item.GetDisplayProperties(); Props.Type = Windows.Media.MediaPlaybackType.Music; Props.MusicProperties.Title = MediaFile.DisplayName; try { Props.MusicProperties.AlbumArtist = await GetMusicCoverAsync().ConfigureAwait(true); } catch (Exception) { Cover.Visibility = Visibility.Collapsed; } Item.ApplyDisplayProperties(Props); Display.Text = $"{Globalization.GetString("Media_Tip_Text")} {MediaFile.DisplayName}"; MVControl.Source = Item; } else { MusicCover.Visibility = Visibility.Collapsed; MediaPlaybackItem Item = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(MediaFile)); MediaItemDisplayProperties Props = Item.GetDisplayProperties(); Props.Type = Windows.Media.MediaPlaybackType.Video; Props.VideoProperties.Title = MediaFile.DisplayName; Item.ApplyDisplayProperties(Props); MVControl.Source = Item; } }
private string GetArtist() { try { using (FileStream FileStream = MediaFile.GetFileStreamFromFile(AccessMode.Read)) using (var TagFile = TagLib.File.Create(new StreamFileAbstraction(MediaFile.Name, FileStream, FileStream))) { if (TagFile.Tag.AlbumArtists != null && TagFile.Tag.AlbumArtists.Length != 0) { string Artist = ""; if (TagFile.Tag.AlbumArtists.Length == 1) { return(TagFile.Tag.AlbumArtists[0]); } else { Artist = TagFile.Tag.AlbumArtists[0]; } foreach (var item in TagFile.Tag.AlbumArtists) { Artist = Artist + "/" + item; } return(Artist); } else { return(Globalization.GetString("UnknownText")); } } } catch { return(Globalization.GetString("UnknownText")); } }
private void settingLanguage_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (AppPrefs.Instance.language != settingLanguage.SelectedIndex) { AppPrefs.Instance.language = settingLanguage.SelectedIndex; Globalization.SetSelectedLanguage(settingLanguage.SelectedIndex); // This will apply some translations but not all since some are created in code instead of being tagged on the xaml Globalization.ApplyTranslations(this); if (tabControl.Items.Count > 1) { for (int i = 1; i < tabControl.Items.Count; ++i) { Globalization.ApplyTranslations(tabControl.Items[i] as DependencyObject); } } MessageBox.Show( Globalization.Translate("Restart_Msg"), Globalization.Translate("Restart"), MessageBoxButton.OK); } }
private async void DeleteFile_Click(object sender, RoutedEventArgs e) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_WarningTitle"), PrimaryButtonText = Globalization.GetString("Common_Dialog_ContinueButton"), Content = Globalization.GetString("QueueDialog_DeleteFile_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CancelButton") }; if ((await Dialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary) { foreach (SecureAreaStorageItem Item in SecureGridView.SelectedItems.ToArray()) { SecureCollection.Remove(Item); if (!Item.PermanentDelete()) { LogTracer.Log(new Win32Exception(Marshal.GetLastWin32Error()), "Delete encrypted file failed"); } } } }
public async Task Commit() { UIFunc.ShowLoading(U.StandartLoggingText); var result = await WebServiceFunc.SubmitLogin(Model); UIFunc.HideLoading(); if (!result.Item1) { var errtext = (string.IsNullOrEmpty(result.Item3) ? Globalization.T("(!)LoginError") : result.Item3); await UIFunc.AlertError(errtext); return; } var userProfileRowId = result.Item2.Value; var aspxauth = result.Item4; UserOptions.SetUsernamePassword(Model.email, Model.password, userProfileRowId); UserOptions.SetAspxauth(aspxauth); await NavFunc.RestartApp(); }
/// <summary> /// 异步启动蓝牙的配对过程 /// </summary> /// <param name="DeviceInfo"></param> /// <returns></returns> private async Task PairAsync(DeviceInformation DeviceInfo) { DevicePairingKinds PairKinds = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ConfirmPinMatch; DeviceInformationCustomPairing CustomPairing = DeviceInfo.Pairing.Custom; CustomPairing.PairingRequested += CustomPairInfo_PairingRequested; DevicePairingResult PairResult = await CustomPairing.PairAsync(PairKinds, DevicePairingProtectionLevel.EncryptionAndAuthentication); CustomPairing.PairingRequested -= CustomPairInfo_PairingRequested; if (PairResult.Status == DevicePairingResultStatus.Paired) { BluetoothWatcher.Stop(); BluetoothDeviceCollection.Clear(); BluetoothWatcher.Start(); } else { Tips.Text = Globalization.GetString("BluetoothUI_Tips_Text_4"); } }
public void VerificarMensagensNovas() { int userId = HttpContext.Session.GetInt32("ID") ?? 0; DateTime dataUltimoAcesso = _db.Int_DP_Usuarios .Where(a => a.Id == userId) .Select(s => s.UltimoLogin) .FirstOrDefault(); DateTime dataUltimoAcesso2 = Globalization.ConverterData(HttpContext.Session.GetString("UltimoAcesso")); List <Mensagem> mensagem = _db.Int_DP_Mensagens .Where(a => a.Data >= dataUltimoAcesso2) .OrderByDescending(b => b.Data) .ToList(); if (mensagem.Count > 0) { ViewBag.NovaMensagem = mensagem; } HttpContext.Session.SetString("Visualizado", "true"); }
private async void SecureFilePropertyDialog_Loading(Windows.UI.Xaml.FrameworkElement sender, object args) { StorageFile Item = (await StorageItem.GetStorageItem().ConfigureAwait(true)) as StorageFile; FileSize = StorageItem.Size; FileName = StorageItem.Name; FileType = StorageItem.DisplayType; using (Stream EncryptFileStream = await Item.OpenStreamForReadAsync().ConfigureAwait(true)) { byte[] DecryptByteBuffer = new byte[20]; await EncryptFileStream.ReadAsync(DecryptByteBuffer, 0, DecryptByteBuffer.Length).ConfigureAwait(true); if (Encoding.UTF8.GetString(DecryptByteBuffer).Split('$', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() is string Info) { string[] InfoGroup = Info.Split('|'); if (InfoGroup.Length == 2) { Level = Convert.ToInt32(InfoGroup[0]) == 128 ? "AES-128bit" : "AES-256bit"; } else { Level = Globalization.GetString("UnknownText"); } } else { Level = Globalization.GetString("UnknownText"); } } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FileSize))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FileName))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FileType))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Level))); }
public async Task OpenTargetFolder(StorageFolder Folder) { if (Folder == null) { throw new ArgumentNullException(nameof(Folder), "Argument could not be null"); } try { if (string.IsNullOrEmpty(Folder.Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_TipTitle"), Content = Globalization.GetString("QueueDialog_CouldNotAccess_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } else { if (AnimationController.Current.IsEnableAnimation) { Frame.Navigate(typeof(FileControl), new Tuple <WeakReference <TabViewItem>, string[]>(WeakToTabItem, new string[] { Folder.Path }), new DrillInNavigationTransitionInfo()); } else { Frame.Navigate(typeof(FileControl), new Tuple <WeakReference <TabViewItem>, string[]>(WeakToTabItem, new string[] { Folder.Path }), new SuppressNavigationTransitionInfo()); } } } catch (Exception ex) { LogTracer.Log(ex, "An error was threw when entering device"); } }
/// <summary> /// 异步启动蓝牙的配对过程 /// </summary> /// <param name="DeviceInfo"></param> /// <returns></returns> private async Task PairAsync(BluetoothDeivceData Device) { try { if (Device.DeviceInfo.Pairing.CanPair) { DeviceInformationCustomPairing CustomPairing = Device.DeviceInfo.Pairing.Custom; CustomPairing.PairingRequested += CustomPairInfo_PairingRequested; DevicePairingResult PairResult = await CustomPairing.PairAsync(DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ConfirmPinMatch, DevicePairingProtectionLevel.EncryptionAndAuthentication); CustomPairing.PairingRequested -= CustomPairInfo_PairingRequested; if (PairResult.Status == DevicePairingResultStatus.Paired) { Device.Update(); } else { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Tips.Text = Globalization.GetString("BluetoothUI_Tips_Text_4"); Tips.Visibility = Visibility.Visible; }); } } else { LogTracer.Log($"Unable pair with Bluetooth device: \"{Device.Name}\", reason: CanPair property return false"); } } catch (Exception ex) { LogTracer.Log(ex, $"Unable pair with Bluetooth device: \"{Device.Name}\""); } }
public QuickStartModifiedDialog(QuickStartType Type) { InitializeComponent(); this.Type = Type; if (AppThemeController.Current.Theme == ElementTheme.Dark) { Icon.Source = new BitmapImage(new Uri("ms-appx:///Assets/AddImage_Light.png")); } else { Icon.Source = new BitmapImage(new Uri("ms-appx:///Assets/AddImage_Dark.png")); } switch (Type) { case QuickStartType.Application: { Protocol.PlaceholderText = Globalization.GetString("QuickStart_Protocol_Application_PlaceholderText"); GetImageAutomatic.Visibility = Visibility.Visible; PickLogo.Visibility = Visibility.Collapsed; PickApp.Visibility = Visibility.Visible; break; } case QuickStartType.WebSite: { Protocol.PlaceholderText = Globalization.GetString("QuickStart_Protocol_Web_PlaceholderText"); GetImageAutomatic.Visibility = Visibility.Visible; PickLogo.Visibility = Visibility.Visible; PickApp.Visibility = Visibility.Collapsed; break; } } }
private async void LibraryProperties_Click(object sender, RoutedEventArgs e) { if (LibraryGrid.SelectedItem is LibraryFolder Library) { FileSystemStorageFolder Folder = await FileSystemStorageFolder.CreateFromExistingStorageItem(Library.Folder); await Folder.LoadMorePropertiesAsync(); AppWindow NewWindow = await AppWindow.TryCreateAsync(); NewWindow.RequestSize(new Size(420, 600)); NewWindow.RequestMoveRelativeToCurrentViewContent(new Point(Window.Current.Bounds.Width / 2 - 200, Window.Current.Bounds.Height / 2 - 300)); NewWindow.PersistedStateId = "Properties"; NewWindow.Title = Globalization.GetString("Properties_Window_Title"); NewWindow.TitleBar.ExtendsContentIntoTitleBar = true; NewWindow.TitleBar.ButtonBackgroundColor = Colors.Transparent; NewWindow.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent; ElementCompositionPreview.SetAppWindowContent(NewWindow, new PropertyBase(NewWindow, Folder)); WindowManagementPreview.SetPreferredMinSize(NewWindow, new Size(420, 600)); await NewWindow.TryShowAsync(); } }
public override async Task Init() { //UserProfileRowId = new Guid("2fd3c1cb-be1a-4444-8131-c44447d3b6bc"); HeaderTitle = Globalization.T("Profile"); IsBackVisible = U.IsBackVisible; AllPatientTabs.ForEach(q => PatientHeaderModels.Add(q, new PatientHeaderModel())); CommitCommand = CommandFunc.CreateAsync(Commit, () => !HasModelErrors()); CancelCommand = CommandFunc.CreateAsync(Cancel); LogoutCommand = CommandFunc.CreateAsync(Logout); ChangePasswordCommand = CommandFunc.CreateAsync(ChangePassword); LocaleChooseCommand = CommandFunc.CreateAsync(async() => await Globalization.SwitchLocale()); U.RequestMainThread(async() => { if (!await LoadData()) { return; } CalcAll(); }); }
public ActionResult Excluir(int id) { Log log = new Log(); int user_id = HttpContext.Session.GetInt32("ID") ?? 0; try { Usuario usuario = _db.Int_DP_Usuarios.Find(id); string usuario_temp = usuario.Login; usuario.Ativo = 0; usuario.Login = string.Concat(usuario.Login, Globalization.HoraAtualBR().Day.ToString(), Globalization.HoraAtualBR().Second.ToString(), Globalization.HoraAtualBR().Minute.ToString()); //_db.Int_Dp_Usuarios.Remove(usuario); _db.SaveChanges(); TempData["UsuarioExcluido"] = "O usuário '" + usuario_temp + "' foi excluido!"; log.ExcluirUsuario(user_id, id); _db.Int_DP_Logs.Add(log); } catch (Exception exp) { TempData["UsuarioErro"] = "Ocorreu um erro ao tentar excluir o usuário"; log.ExcluirUsuario_Erro(user_id, id, exp); _db.Int_DP_Logs.Add(log); } finally { _db.SaveChanges(); } return RedirectToAction("Index"); }
private async void PairOrCancelButton_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; BluetoothControl.SelectedItem = btn.DataContext; LastSelectIndex = BluetoothControl.SelectedIndex; if (btn.Content.ToString() == Globalization.GetString("PairText")) { await PairAsync(BluetoothDeviceCollection[LastSelectIndex].DeviceInfo).ConfigureAwait(false); } else { var list = BluetoothDeviceCollection[BluetoothControl.SelectedIndex]; var UnPairResult = await list.DeviceInfo.Pairing.UnpairAsync(); if (UnPairResult.Status == DeviceUnpairingResultStatus.Unpaired || UnPairResult.Status == DeviceUnpairingResultStatus.AlreadyUnpaired) { list.OnPropertyChanged("CancelOrPairButton"); list.OnPropertyChanged("Name"); list.OnPropertyChanged("IsPaired"); } } }
public ZipDialog(FileSystemStorageItemBase StorageItem) { InitializeComponent(); if (StorageItem.StorageType == Windows.Storage.StorageItemTypes.File) { FName.Text = $"{Path.GetFileNameWithoutExtension(StorageItem.Name)}.zip"; } else { FName.Text = $"{StorageItem.Name}.zip"; } if (FName.Text != Path.GetExtension(FName.Text)) { FName.Select(0, FName.Text.Length - 4); } ZipMethod.Items.Add(Globalization.GetString("Zip_Dialog_Level_1")); ZipMethod.Items.Add(Globalization.GetString("Zip_Dialog_Level_2")); ZipMethod.Items.Add(Globalization.GetString("Zip_Dialog_Level_3")); ZipMethod.SelectedIndex = 1; }
private async void NavigationButton_Click(object sender, RoutedEventArgs e) { await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-broadfilesystemaccess")); try { ToastContentBuilder Builder = new ToastContentBuilder() .SetToastScenario(ToastScenario.Reminder) .AddText(Globalization.GetString("Toast_BroadFileSystemAccess_Text_1")) .AddText(Globalization.GetString("Toast_BroadFileSystemAccess_Text_2")) .AddButton(Globalization.GetString("Toast_BroadFileSystemAccess_ActionButton_1"), ToastActivationType.Foreground, "Restart") .AddButton(new ToastButtonDismiss(Globalization.GetString("Toast_BroadFileSystemAccess_ActionButton_2"))); ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(Builder.GetToastContent().GetXml())); } catch (Exception ex) { LogTracer.Log(ex, "Toast notification could not be sent"); } finally { await ApplicationView.GetForCurrentView().TryConsolidateAsync(); } }
/// <summary> /// 创建蓝牙的检测器,检测器将定期检测蓝牙设备 /// </summary> public void CreateBluetoothWatcher() { if (BluetoothWatcher != null) { BluetoothWatcher.Added -= BluetoothWatcher_Added; BluetoothWatcher.Updated -= BluetoothWatcher_Updated; BluetoothWatcher.Removed -= BluetoothWatcher_Removed; BluetoothWatcher.EnumerationCompleted -= BluetoothWatcher_EnumerationCompleted; BluetoothWatcher.Stop(); BluetoothWatcher = null; Progress.IsActive = true; StatusText.Text = Globalization.GetString("BluetoothUI_Status_Text"); } //根据指定的筛选条件创建检测器 BluetoothWatcher = DeviceInformation.CreateWatcher("System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"", new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" }, DeviceInformationKind.AssociationEndpoint); BluetoothWatcher.Added += BluetoothWatcher_Added; BluetoothWatcher.Updated += BluetoothWatcher_Updated; BluetoothWatcher.Removed += BluetoothWatcher_Removed; BluetoothWatcher.EnumerationCompleted += BluetoothWatcher_EnumerationCompleted; BluetoothWatcher.Start(); }
public QuickStartModifiedDialog(QuickStartItem Item) { InitializeComponent(); Type = Item.Type; IsUpdate = true; switch (Item.Type) { case QuickStartType.Application: { Protocol.PlaceholderText = Globalization.GetString("QuickStart_Protocol_Application_PlaceholderText"); GetImageAutomatic.Visibility = Visibility.Visible; PickLogo.Visibility = Visibility.Collapsed; PickApp.Visibility = Visibility.Visible; Icon.Source = Item.Image; DisplayName.Text = Item.DisplayName; Protocol.Text = Item.Protocol.ToString(); QuickItem = Item; break; } case QuickStartType.WebSite: { Protocol.PlaceholderText = Globalization.GetString("QuickStart_Protocol_Web_PlaceholderText"); GetImageAutomatic.Visibility = Visibility.Visible; PickLogo.Visibility = Visibility.Visible; PickApp.Visibility = Visibility.Collapsed; Icon.Source = Item.Image; DisplayName.Text = Item.DisplayName; Protocol.Text = Item.Protocol.ToString(); QuickItem = Item; break; } } }
/// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A System.Globalization.CultureInfo. If null is passed, the current culture is assumed.</param> /// <param name="value">The System.Object to convert.</param> /// <param name="destinationType">The System.Type to convert the value parameter to.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value, Type destinationType) { IEnumerable<IEntity> collection = (IEnumerable<IEntity>)value; return string.Join(",", collection.Select(t => t.ToString()).ToArray()); }
private async void SetAsWallpaper_Click(object sender, RoutedEventArgs e) { try { if (!UserProfilePersonalizationSettings.IsSupported()) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_SetWallpaperNotSupport_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(false); } else { if (Flip.SelectedItem is PhotoDisplaySupport Photo) { if (await Photo.PhotoFile.GetStorageItem().ConfigureAwait(true) is StorageFile File) { StorageFile TempFile = await File.CopyAsync(ApplicationData.Current.LocalFolder, Photo.PhotoFile.Name, NameCollisionOption.GenerateUniqueName); try { if (await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(TempFile)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_SetWallpaperSuccess_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(false); } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_SetWallpaperFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(false); } } finally { await TempFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_SetWallpaperFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(false); } } } } catch { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_SetWallpaperFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(false); } }
public bool TryDecodeValue( Globalization.Charset defaultCharset, bool enableFallback, bool allowControlCharacters, bool enable2047, bool enableJisDetection, bool enableUtf8Detection, bool enableDbcsDetection, out string charsetName, out string cultureName, out EncodingScheme encodingScheme, out string value) { charsetName = null; cultureName = null; encodingScheme = EncodingScheme.None; value = null; var stringBuilder = Internal.ScratchPad.GetStringBuilder(System.Math.Min(1024, iterator.TotalLength)); char[] charBuffer = null; byte[] byteBuffer = null; var currentPosition1 = iterator.CurrentPosition; var whitespaceOnly = false; var flag1 = false; if (defaultCharset != null && (enableJisDetection || enableUtf8Detection || enableDbcsDetection && Globalization.FeInboundCharsetDetector.IsSupportedFarEastCharset(defaultCharset))) { defaultCharset = this.DetectValueCharset(defaultCharset, enableJisDetection, enableUtf8Detection, enableDbcsDetection, out encodingScheme); flag1 = true; } System.Text.Decoder decoder1 = null; string lastEncodedWordCharsetName = null; if (!enable2047) iterator.SkipToEof(); else { string lastEncodedWordLanguage = null; Globalization.Charset charset1 = null; System.Text.Decoder decoder2 = null; var flag2 = true; string encodedWordCharsetName; while (true) { this.ParseRawFragment(ref whitespaceOnly); if (!iterator.Eof) { var currentPosition2 = iterator.CurrentPosition; string encodedWordLanguage; byte bOrQ; ValuePosition encodedWordContentStart; ValuePosition encodedWordContentEnd; if (!this.ParseEncodedWord(lastEncodedWordCharsetName, lastEncodedWordLanguage, ref byteBuffer, out encodedWordCharsetName, out encodedWordLanguage, out bOrQ, out encodedWordContentStart, out encodedWordContentEnd)) whitespaceOnly = false; else { if (lastEncodedWordCharsetName == null) { encodingScheme = EncodingScheme.Rfc2047; charsetName = encodedWordCharsetName; cultureName = encodedWordLanguage; } lastEncodedWordCharsetName = encodedWordCharsetName; if (currentPosition1 != currentPosition2 && !whitespaceOnly) { if (!flag2) { this.FlushDecoder(decoder2, allowControlCharacters, ref byteBuffer, ref charBuffer, stringBuilder); flag2 = true; } if (decoder1 == null) { if (defaultCharset == null || !defaultCharset.IsAvailable) { if (!enableFallback) break; } else { decoder1 = defaultCharset.GetEncoding() .GetDecoder(); } } if (decoder1 != null) this.ConvertRawFragment(currentPosition1, currentPosition2, decoder1, allowControlCharacters, ref charBuffer, stringBuilder); else this.ZeroExpandFragment(currentPosition1, currentPosition2, allowControlCharacters, stringBuilder); } Globalization.Charset charset2; if (!Globalization.Charset.TryGetCharset(encodedWordCharsetName, out charset2)) { if (!flag2) { this.FlushDecoder(decoder2, allowControlCharacters, ref byteBuffer, ref charBuffer, stringBuilder); flag2 = true; } if (enableFallback) decoder2 = null; else goto label_25; } else if (charset2 != charset1) { if (!flag2) { this.FlushDecoder(decoder2, allowControlCharacters, ref byteBuffer, ref charBuffer, stringBuilder); flag2 = true; } if (!charset2.IsAvailable) { if (enableFallback) decoder2 = null; else goto label_32; } else { decoder2 = charset2.GetEncoding() .GetDecoder(); charset1 = charset2; } } if (decoder2 != null) { this.DecodeEncodedWord(bOrQ, decoder2, encodedWordContentStart, encodedWordContentEnd, allowControlCharacters, ref byteBuffer, ref charBuffer, stringBuilder); flag2 = false; } else this.ZeroExpandFragment(currentPosition2, iterator.CurrentPosition, allowControlCharacters, stringBuilder); currentPosition1 = iterator.CurrentPosition; whitespaceOnly = true; } } else goto label_39; } charsetName = defaultCharset == null ? null : defaultCharset.Name; return false; label_25: charsetName = encodedWordCharsetName; return false; label_32: charsetName = encodedWordCharsetName; return false; label_39: if (!flag2) this.FlushDecoder(decoder2, allowControlCharacters, ref byteBuffer, ref charBuffer, stringBuilder); } if (currentPosition1 != iterator.CurrentPosition) { if (lastEncodedWordCharsetName == null) { charsetName = !flag1 || encodingScheme != EncodingScheme.None || (defaultCharset == null || defaultCharset.IsSevenBit) || defaultCharset.AsciiSupport != Globalization.CodePageAsciiSupport.Complete ? (defaultCharset == null ? null : defaultCharset.Name) : Globalization.Charset.ASCII.Name; } if (decoder1 == null) { if (defaultCharset == null || !defaultCharset.IsAvailable) { if (!enableFallback) { charsetName = defaultCharset == null ? null : defaultCharset.Name; return false; } decoder1 = null; } else { decoder1 = defaultCharset.GetEncoding() .GetDecoder(); } } if (decoder1 != null) this.ConvertRawFragment(currentPosition1, iterator.CurrentPosition, decoder1, allowControlCharacters, ref charBuffer, stringBuilder); else this.ZeroExpandFragment(currentPosition1, iterator.CurrentPosition, allowControlCharacters, stringBuilder); } Internal.ScratchPad.ReleaseStringBuilder(); value = stringBuilder.ToString(); return true; }
/// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A System.Globalization.CultureInfo. If null is passed, the current culture is assumed.</param> /// <param name="value">The System.Object to convert.</param> /// <param name="destinationType">The System.Type to convert the value parameter to.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value, Type destinationType) { if (!(value is IEntity)) return null; return ((IEntity)value).ToString(); }
/// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A System.Globalization.CultureInfo. If null is passed, the current culture is assumed.</param> /// <param name="value">The System.Object to convert.</param> /// <param name="destinationType">The System.Type to convert the value parameter to.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertTo(ComponentModel.ITypeDescriptorContext context, Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) return (bool)value ? "Male" : "Female"; return base.ConvertTo(context, culture, value, destinationType); }
internal static DateTime Parse(string s, Globalization.DateTimeFormatInfo dateTimeFormatInfo, Globalization.DateTimeStyles dateTimeStyles) { throw new NotImplementedException(); }
public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { string s = value as string; if (s != null) { var margins = s.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (margins.Length == 1) { double uniformLength; if (double.TryParse(margins[0], out uniformLength)) { return new Thickness(uniformLength); } } if (margins.Length == 2) { double leftright, topbottom; if (double.TryParse(margins[0], out leftright) && double.TryParse(margins[1], out topbottom)) { return new Thickness(leftright, topbottom, leftright, topbottom); } } if (margins.Length == 4) { double left, right, top, bottom; if (double.TryParse(margins[0], out left) && double.TryParse(margins[1], out top) && double.TryParse(margins[2], out right) && double.TryParse(margins[3], out bottom)) { return new Thickness(left, top, right, bottom); } } } return base.ConvertFrom(context, culture, value); }
internal static DateTime ParseExact(string s, string format, Globalization.DateTimeFormatInfo dateTimeFormatInfo, Globalization.DateTimeStyles style) { throw new NotImplementedException(); }
public static BigInteger ToBigInteger(this string value, Globalization.NumberStyles numberStyles = Globalization.NumberStyles.HexNumber) { value = numberStyles == Globalization.NumberStyles.HexNumber ? value.Substring(2) : value; var bigInteger = BigInteger.Parse(value, numberStyles); return bigInteger; }
public object Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { return true.Equals(value) ? Visibility.Visible : Visibility.Hidden; }
public object ConvertBack(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { throw FxTrace.Exception.AsError(new NotImplementedException()); }
public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { return ((string)value).ToLower() == "true"; }
public abstract IDictionary<string, string> GetResources(string context, Globalization.CultureInfo uiCulture);
public object ConvertBack(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { return value; }
public override object ConvertTo(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value, Type destinationType) { return ((double)value).ToString(); }
/// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param> /// <param name="value">The System.Object to convert.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { return DateTime.Parse((string)value); }
/// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A System.Globalization.CultureInfo. If null is passed, the current culture is assumed.</param> /// <param name="value">The System.Object to convert.</param> /// <param name="destinationType">The System.Type to convert the value parameter to.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value, Type destinationType) { return ((DateTime)value).ToLongDateString() + " " + ((DateTime)value).ToLongTimeString(); }
private Globalization.Charset DetectValueCharset(Globalization.Charset defaultCharset, bool enableJisDetection, bool enableUtf8Detection, bool enableDbcsDetection, out EncodingScheme encodingScheme) { var valueIterator = new ValueIterator(iterator.Lines, iterator.LinesMask); var inboundCharsetDetector = new Globalization.FeInboundCharsetDetector(defaultCharset.CodePage, false, enableJisDetection, enableUtf8Detection, enableDbcsDetection); while (!valueIterator.Eof) { inboundCharsetDetector.AddBytes(valueIterator.Bytes, valueIterator.Offset, valueIterator.Length, false); valueIterator.Get(valueIterator.Length); } inboundCharsetDetector.AddBytes(null, 0, 0, true); var codePageChoice = inboundCharsetDetector.GetCodePageChoice(); if (codePageChoice != defaultCharset.CodePage) defaultCharset = Globalization.Charset.GetCharset(codePageChoice); encodingScheme = inboundCharsetDetector.PureAscii ? (!(defaultCharset.Name == "iso-2022-jp") || inboundCharsetDetector.Iso2022KrLikely ? EncodingScheme.None : EncodingScheme.Jis) : (inboundCharsetDetector.Iso2022JpLikely || inboundCharsetDetector.Iso2022KrLikely ? EncodingScheme.Jis : EncodingScheme.EightBit); return defaultCharset; }
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { throw new NotSupportedException(); }
private async void Delete_Click(object sender, RoutedEventArgs e) { if (Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down)) { PhotoDisplaySupport Item = PhotoCollection[Flip.SelectedIndex]; Retry: try { await FullTrustProcessController.Current.DeleteAsync(Item.PhotoFile.Path, true).ConfigureAwait(true); PhotoCollection.Remove(Item); Behavior.InitAnimation(InitOption.Full); } catch (FileCaputureException) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_Item_Captured_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } catch (FileNotFoundException) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DeleteItemError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_RefreshButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } catch (InvalidOperationException) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_UnauthorizedDelete_Content"), PrimaryButtonText = Globalization.GetString("Common_Dialog_GrantButton"), CloseButtonText = Globalization.GetString("Common_Dialog_CancelButton") }; if (await dialog.ShowAsync().ConfigureAwait(true) == ContentDialogResult.Primary) { if (await FullTrustProcessController.Current.SwitchToAdminModeAsync().ConfigureAwait(true)) { goto Retry; } else { QueueContentDialog ErrorDialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DenyElevation_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await ErrorDialog.ShowAsync().ConfigureAwait(true); } } } catch (Exception) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DeleteItemError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } } else { DeleteDialog Dialog = new DeleteDialog(Globalization.GetString("QueueDialog_DeleteFile_Content")); if ((await Dialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary) { PhotoDisplaySupport Item = PhotoCollection[Flip.SelectedIndex]; Retry: try { await FullTrustProcessController.Current.DeleteAsync(Item.PhotoFile.Path, Dialog.IsPermanentDelete).ConfigureAwait(true); PhotoCollection.Remove(Item); Behavior.InitAnimation(InitOption.Full); } catch (FileCaputureException) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_Item_Captured_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } catch (FileNotFoundException) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DeleteItemError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_RefreshButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } catch (InvalidOperationException) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_UnauthorizedDelete_Content"), PrimaryButtonText = Globalization.GetString("Common_Dialog_GrantButton"), CloseButtonText = Globalization.GetString("Common_Dialog_CancelButton") }; if (await dialog.ShowAsync().ConfigureAwait(true) == ContentDialogResult.Primary) { if (await FullTrustProcessController.Current.SwitchToAdminModeAsync().ConfigureAwait(true)) { goto Retry; } else { QueueContentDialog ErrorDialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DenyElevation_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await ErrorDialog.ShowAsync().ConfigureAwait(true); } } } catch (Exception) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DeleteItemError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync().ConfigureAwait(true); } } } }
/// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param> /// <param name="value">The System.Object to convert.</param> /// <returns>An System.Object that represents the converted value.</returns> public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value) { if (string.IsNullOrEmpty((string)value)) return null; return DateTime.Parse((string)value); }
private async Task Initialize() { try { ExitLocker = new ManualResetEvent(false); Cancellation = new CancellationTokenSource(); LoadQueue = new Queue <int>(); MainPage.ThisPage.IsAnyTaskRunning = true; Behavior.Attach(Flip); List <FileSystemStorageItemBase> FileList = FileSystemStorageItemBase.Open(Path.GetDirectoryName(SelectedPhotoPath), ItemFilters.Folder).GetChildrenItems(SettingControl.IsDisplayHiddenItem, ItemFilters.File).Where((Item) => Item.Type.Equals(".png", StringComparison.OrdinalIgnoreCase) || Item.Type.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || Item.Type.Equals(".bmp", StringComparison.OrdinalIgnoreCase)).ToList(); if (FileList.Count == 0) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("Queue_Dialog_ImageReadError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); Frame.GoBack(); } else { int LastSelectIndex = FileList.FindIndex((Photo) => Photo.Path.Equals(SelectedPhotoPath, StringComparison.OrdinalIgnoreCase)); if (LastSelectIndex < 0 || LastSelectIndex >= FileList.Count) { LastSelectIndex = 0; } PhotoCollection = new ObservableCollection <PhotoDisplaySupport>(FileList.Select((Item) => new PhotoDisplaySupport(Item))); Flip.ItemsSource = PhotoCollection; if (!await PhotoCollection[LastSelectIndex].ReplaceThumbnailBitmapAsync().ConfigureAwait(true)) { CouldnotLoadTip.Visibility = Visibility.Visible; } for (int i = LastSelectIndex - 5 > 0 ? LastSelectIndex - 5 : 0; i <= (LastSelectIndex + 5 < PhotoCollection.Count - 1 ? LastSelectIndex + 5 : PhotoCollection.Count - 1) && !Cancellation.IsCancellationRequested; i++) { await PhotoCollection[i].GenerateThumbnailAsync().ConfigureAwait(true); } if (!Cancellation.IsCancellationRequested) { Flip.SelectedIndex = LastSelectIndex; Flip.SelectionChanged += Flip_SelectionChanged; Flip.SelectionChanged += Flip_SelectionChanged1; await EnterAnimation.BeginAsync().ConfigureAwait(true); } } } catch (Exception ex) { CouldnotLoadTip.Visibility = Visibility.Visible; LogTracer.Log(ex, "An error was threw when initialize PhotoViewer"); } finally { MainPage.ThisPage.IsAnyTaskRunning = false; ExitLocker.Set(); } }
public object ConvertBack(object value, Type targetType, object parameter, Globalization.CultureInfo culture) { return Visibility.Visible.Equals(value); }