/// <summary> /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be /// used as generic method and casting is not required. /// <example> /// iconconverter.ConvertTo<int>(context, culture, value); /// </example> /// </summary> public static T ConvertTo <T>(this IconConverter iconconverter, System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, Object value) { if (iconconverter == null) { throw new ArgumentNullException("iconconverter"); } return((T)iconconverter.ConvertTo(context, culture, value, typeof(T))); }
/// <summary> /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be /// used as generic method and casting is not required. /// <example> /// typeconverter.ConvertTo<int>(value); /// </example> /// </summary> public static T ConvertTo <T>(this IconConverter typeconverter, Object value) { if (typeconverter == null) { throw new ArgumentNullException("typeconverter"); } return((T)typeconverter.ConvertTo(value, typeof(T))); }
public static Image ConvertIconToImage(Icon icon) { IconConverter convert = new IconConverter(); object output = convert.ConvertTo(icon, typeof(Image)); if (output == null) { return(null); } return(output as Image); }
public IconConverterTest() { _icon = new Icon(Path.Combine("bitmaps", "TestIcon.ico")); _iconStr = _icon.ToString(); using (MemoryStream destStream = new MemoryStream()) { _icon.Save(destStream); _iconBytes = destStream.ToArray(); } _icoConv = new IconConverter(); _icoConvFrmTD = (IconConverter)TypeDescriptor.GetConverter(_icon); }
public static SingleDataDefinition FromJson(JToken obj) { var converterObj = (JObject)obj["converter"]; IValueConverter converter = null; if (converterObj != null) { var type = (string)converterObj["type"]; if (type == "color") { converter = ColorConverter.FromJson(converterObj); } else if (type == "generic") { converter = GenericReferenceConverter.FromJson(converterObj); } else if (type == "icon") { converter = IconConverter.FromJson(converterObj); } else if (type == "multiref") { converter = MultiReferenceConverter.FromJson(converterObj); } else if (type == "link") { converter = SheetLinkConverter.FromJson(converterObj); } else if (type == "tomestone") { converter = TomestoneOrItemReferenceConverter.FromJson(converterObj); } else if (type == "complexlink") { converter = ComplexLinkConverter.FromJson(converterObj); } else { throw new ArgumentException("Invalid converter type.", "obj"); } } return(new SingleDataDefinition() { Name = (string)obj["name"], Converter = converter }); }
private void CriarBotao16() { StdBEBotaoRibbon botao = new StdBEBotaoRibbon(); StdBEBotoesRibbon botoes = new StdBEBotoesRibbon(); botao.set_Descricao("Seguridad"); botao.set_Icon32(false); botao.set_Id(RibbonConstants.CIDBOTAO1); var pic = IconConverter.ImageToIPicture(Image.FromFile(@"C:\IconsStandard\16x16\operacoes.ico")); // Resource.operacoes.ToBitmap()) botao.set_Icon((stdole.StdPicture)pic); botoes.Insere(botao); PlataformaPrimavera.Ribbon.AdicionaBotoes(botoes, "Botoes", RibbonConstants.CIDGROUP); }
private void CriarBotao16() { StdBEBotaoRibbon botao = new StdBEBotaoRibbon(); StdBEBotoesRibbon botoes = new StdBEBotoesRibbon(); botao.set_Descricao("Segurança"); botao.set_Icon32(false); botao.set_Id(RibbonConstants.CIDBOTAO1); var pic = IconConverter.ImageToIPicture(Resource.operacoes.ToBitmap()); botao.set_Icon((stdole.StdPicture)pic); botoes.Insere(botao); plataformaPrimavera.Ribbon.AdicionaBotoes(botoes, "Botoes", RibbonConstants.CIDGROUP); }
private void UpdateServiceConnectionStatus() { var dte = (DTE2)GetService(typeof(SDTE)); var cbs = ((CommandBars)dte.CommandBars); var cb = cbs["OSBLE+"]; var toolsControl = cb.Controls["Log into OSBLE+"]; var loginButton = (CommandBarButton)toolsControl; if (_client.IsSendingData) { loginButton.Picture = (StdPicture)IconConverter.GetIPictureDispFromImage(Resources.login_active); loginButton.TooltipText = "Connected to OSBLE+"; } else { loginButton.Picture = (StdPicture)IconConverter.GetIPictureDispFromImage(Resources.login); loginButton.TooltipText = "Not connected to OSBLE+. Click to log in."; } }
private void ToggleProfileImage(bool hasSocial) { var dte = (DTE2)GetService(typeof(SDTE)); var cbs = ((CommandBars)dte.CommandBars); var cb = cbs["OSBLE+"]; var toolsControl = cb.Controls["My OSBLE+ Profile"]; var profileButton = (CommandBarButton)toolsControl; if (hasSocial) { profileButton.Picture = (StdPicture)IconConverter.GetIPictureDispFromImage(Resources.profile_new_social); profileButton.TooltipText = "New social activity detected"; } else { profileButton.Picture = (StdPicture)IconConverter.GetIPictureDispFromImage(Resources.profile); profileButton.TooltipText = "View your profile"; } }
void ToggleProfileImage(bool hasSocial) { var dte = GetService(typeof(SDTE)) as DTE2; var cbs = ((Microsoft.VisualStudio.CommandBars.CommandBars)dte.CommandBars); Microsoft.VisualStudio.CommandBars.CommandBar cb = cbs["OSBIDE Toolbar"]; Microsoft.VisualStudio.CommandBars.CommandBarControl toolsControl = cb.Controls["My OSBIDE Profile"]; Microsoft.VisualStudio.CommandBars.CommandBarButton profileButton = toolsControl as Microsoft.VisualStudio.CommandBars.CommandBarButton; if (hasSocial == true) { profileButton.Picture = (stdole.StdPicture)IconConverter.GetIPictureDispFromImage(Resources.profile_new_social); profileButton.TooltipText = "New social activity detected"; } else { profileButton.Picture = (stdole.StdPicture)IconConverter.GetIPictureDispFromImage(Resources.profile); profileButton.TooltipText = "View your profile"; } }
private void UpdateSendStatus() { var dte = GetService(typeof(SDTE)) as DTE2; var cbs = ((Microsoft.VisualStudio.CommandBars.CommandBars)dte.CommandBars); Microsoft.VisualStudio.CommandBars.CommandBar cb = cbs["OSBIDE Toolbar"]; Microsoft.VisualStudio.CommandBars.CommandBarControl toolsControl = cb.Controls["Log into OSBIDE"]; Microsoft.VisualStudio.CommandBars.CommandBarButton loginButton = toolsControl as Microsoft.VisualStudio.CommandBars.CommandBarButton; if (_client.IsSendingData == true) { loginButton.Picture = (stdole.StdPicture)IconConverter.GetIPictureDispFromImage(Resources.login_active); loginButton.TooltipText = "Connected to OSBIDE"; } else { loginButton.Picture = (stdole.StdPicture)IconConverter.GetIPictureDispFromImage(Resources.login); loginButton.TooltipText = "Not connected to OSBIDE. Click to log in."; } }
protected override System.Collections.ObjectModel.ObservableCollection <ICommandViewModel> CreateCommands() { var commands = base.CreateCommands(); var isElevated = DataContext.IsElevatedMode; if (State.IsActive || isElevated) { foreach (var action in State.StateDefinition.Actions.Where(a => a.IsVisible)) { // avoid capturing the loop variable var localAction = action; var cmd = ViewModelFactory.CreateViewModel <SimpleCommandViewModel.Factory>().Invoke(DataContext, this, action.Action.GetLabel(), action.Action.Description, () => ExecuteAction(localAction), null, null); // cmd.Icon = IconConverter.ToImage(action.Icon); commands.Add(cmd); } if (isElevated) { foreach (var action in State.StateDefinition.Actions.Where(a => a.IsVisible == false)) { // avoid capturing the loop variable var localAction = action; var cmd = ViewModelFactory.CreateViewModel <SimpleCommandViewModel.Factory>().Invoke(DataContext, this, action.Action.GetLabel(), action.Action.Description, () => ExecuteAction(localAction), null, null); cmd.Icon = IconConverter.ToImage(NamedObjects.Gui.Icons.ZetboxBase.warning_png.Find(FrozenContext)); commands.Add(cmd); } } } return(commands); }
public FileItem(string path) { if (!File.Exists(path)) { throw new FileNotFoundException("The file added to FileItem was not found!", path); } filePath = path; var fileInfo = new FileInfo(filePath); displayName = fileInfo.Name; mFileLength = fileInfo.Length; // // Get the File icon // var shinfo = new SHFILEINFO(); Win32.SHGetFileInfo(filePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON); if (true) { //The icon is returned in the hIcon member of the shinfo struct var imageConverter = new IconConverter(); Icon icon = Icon.FromHandle(shinfo.hIcon); try { fileIconImage = (Image) imageConverter.ConvertTo(icon, typeof(Image)); } catch (NotSupportedException) { } Win32.DestroyIcon(shinfo.hIcon); } }
private void ColorStarBeforEndIndex(int index) { int it = 0; while (it <= index && it < NbStars) { if ((((StarsRat)Stars[it]).FullStar == false)) { ((StarsRat)Stars[it]).StarIcon = IconConverter.IconToImageBrush("star-full"); ((StarsRat)Stars[it]).FullStar = true; } it++; } while (it < NbStars) { if ((((StarsRat)Stars[it]).FullStar == true)) { ((StarsRat)Stars[it]).StarIcon = IconConverter.IconToImageBrush("star-empty"); ((StarsRat)Stars[it]).FullStar = false; } it++; } }
private static void SetWarning(NotifyIcon ni) { Icon tmpIcon = ni.Icon; IconConverter icconv = new IconConverter(); Bitmap TargetBitmap = (Bitmap)icconv.ConvertTo(tmpIcon, typeof(Bitmap)); Bitmap OverlayBitmap = Properties.Resources.overlay; Bitmap ResultBitmap = new Bitmap(TargetBitmap.Width, TargetBitmap.Height, PixelFormat.Format32bppArgb); Graphics graph = Graphics.FromImage(ResultBitmap); graph.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; graph.DrawImage(TargetBitmap, 0, 0); graph.DrawImage(OverlayBitmap, 0, TargetBitmap.Height - OverlayBitmap.Height); IntPtr hIcon = ResultBitmap.GetHicon(); tmpIcon = Icon.FromHandle(hIcon); ni.Icon = tmpIcon; }
/// <summary> /// Converts entities: OpenWeather to CurrentWeatherModel /// </summary> /// <param name="externalApiWeather"></param> /// <returns cref="CurrentWeatherModel"></returns> public CurrentWeatherModel Convert(OpenWeather externalApiWeather) { try { if (externalApiWeather == null || externalApiWeather.Weather == null || externalApiWeather.Wind == null || externalApiWeather.Main == null) { throw new ArgumentNullException("Invalid input parameter."); } var openWeatherEntity = externalApiWeather.Weather.FirstOrDefault(); CurrentWeatherModel currentWeather = new CurrentWeatherModel { Date = externalApiWeather.Dt.ToDateTime().ToWeatherDateTimeFormat(externalApiWeather.Timezone), WeatherConditions = new WeatherConditionsModel { TemperatureFormat = WeatherUnitsFormatsConverter.GetTemperatureFormat(_wfProviderSettings.UnitsFormat), Humidity = externalApiWeather.Main.Humidity, Pressure = externalApiWeather.Main.Pressure, Temperature = (int)Math.Round(externalApiWeather.Main.Temp, 0), WeatherDescription = openWeatherEntity.Description, IconUrl = IconConverter.Generate(_wfProviderSettings.IconStorageAddress, openWeatherEntity.Icon), WindSpeed = Math.Round(externalApiWeather.Wind.Speed, 1) } }; return(currentWeather); } catch (Exception ex) { string errorMessage = "Something went wrond during convertion from OpenWeather to CurrentWeatherModel."; _logger.LogError(errorMessage, ex); throw new Exception(errorMessage, ex); } }
// Move to another method to avoid loading Zetbox.Objects private void InitializeClient(string[] args, ZetboxConfig config) { InitializeSplashScreenImageResource(); StartupScreen.ShowSplashScreen(Zetbox.Client.Properties.Resources.Startup_Message, Zetbox.Client.Properties.Resources.Startup_InitApp, 6); if (config.Server != null && config.Server.StartServer) { StartupScreen.SetInfo(Zetbox.Client.Properties.Resources.Startup_Server); serverDomain = new ServerDomainManager(); serverDomain.Start(config); } else { StartupScreen.SetInfo(Zetbox.Client.Properties.Resources.Startup_NoServerStart); } container = CreateMasterContainer(config); StartupScreen.SetInfo(Zetbox.Client.Properties.Resources.Startup_Launcher); // Make Gendarme happy var resources = this.Resources; resources.BeginInit(); resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/Zetbox.Client.WPF;component/AppResources.xaml", UriKind.Relative) }); // Create icon converter var iconConverter = new IconConverter(container.Resolve <IFrozenContext>(), container.Resolve <Func <IZetboxContext> >()); resources["IconConverter"] = iconConverter; resources["ImageCtrlConverter"] = new ImageCtrlConverter(iconConverter); // Init all Converter that are not using a Context var templateSelectorFactory = container.Resolve <Zetbox.Client.WPF.Toolkit.VisualTypeTemplateSelector.Factory>(); resources["defaultTemplateSelector"] = templateSelectorFactory(null); resources["listItemTemplateSelector"] = templateSelectorFactory("Zetbox.App.GUI.SingleLineKind"); resources["dashBoardTemplateSelector"] = templateSelectorFactory("Zetbox.App.GUI.DashboardKind"); // Manually add DefaultStyles and DefaultViews // Otherwise converter are unknown resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/Zetbox.Client.WPF;component/Styles/DefaultStyles.xaml", UriKind.Relative) }); resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/Zetbox.Client.WPF;component/Styles/DefaultHighlightColorDefinitions.xaml", UriKind.Relative) }); // Load registrated dictionaries from autofac foreach (var dict in container.Resolve <IEnumerable <Meta <ResourceDictionary> > >().Where(m => WPFHelper.RESOURCE_DICTIONARY_STYLE.Equals(m.Metadata[WPFHelper.RESOURCE_DICTIONARY_KIND])).Select(m => m.Value)) { resources.MergedDictionaries.Add(dict); } resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/Zetbox.Client.WPF;component/Styles/DefaultViews.xaml", UriKind.Relative) }); // Load registrated dictionaries from autofac foreach (var dict in container.Resolve <IEnumerable <Meta <ResourceDictionary> > >().Where(m => WPFHelper.RESOURCE_DICTIONARY_VIEW.Equals(m.Metadata[WPFHelper.RESOURCE_DICTIONARY_KIND])).Select(m => m.Value)) { resources.MergedDictionaries.Add(dict); } resources.EndInit(); // Init credentials explicit StartupScreen.SetInfo(Zetbox.Client.Properties.Resources.Startup_EnsuringCredentials); container.Resolve <ICredentialsResolver>().EnsureCredentials(); StartupScreen.SetInfo(Zetbox.Client.Properties.Resources.Startup_Launcher); // Tell icon converter that everything is initialized iconConverter.Initialized(); // Focus nightmare // http://stackoverflow.com/questions/673536/wpf-cant-set-focus-to-a-child-of-usercontrol/4785124#4785124 EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent, new RoutedEventHandler(FocusFixLoaded)); EventManager.RegisterClassHandler(typeof(Zetbox.Client.WPF.View.ZetboxBase.InstanceCollectionBase), UserControl.LoadedEvent, new RoutedEventHandler(FocusFixLoaded)); wpfResourcesInitialized = true; FixupDatabase(container.Resolve <Func <IZetboxContext> >()); IServiceControlManager scm = null; if (container.TryResolve <IServiceControlManager>(out scm)) { Logging.Log.Info("Starting Zetbox Services"); scm.Start(); } else { Logging.Log.Info("Service control manager not registered"); } StartupScreen.CanCloseOnWindowLoaded(); // delegate all business logic into another class, which // allows us to load the Zetbox.Objects assemblies _before_ // they are needed. var launcher = container.Resolve <Launcher>(); launcher.Show(args); }
/// <summary> /// Converts entities: OpenWeatherForecast to ForecastModel /// </summary> /// <param name="externalApiForecast"></param> /// <returns cref="ForecastModel"></returns> public ForecastModel Convert(OpenWeatherForecast externalApiForecast) { try { if (externalApiForecast == null || externalApiForecast.List == null || externalApiForecast.City == null) { throw new ArgumentNullException("Invalid input parameter."); } ForecastModel forecast = new ForecastModel { City = externalApiForecast.City.Name }; List <OpenWeather> weatherList = externalApiForecast.List.ToList <OpenWeather>(); if (weatherList.Count() == 0) { throw new Exception("External api forecast is empty."); } string temperatureFormat = WeatherUnitsFormatsConverter.GetTemperatureFormat(_wfProviderSettings.UnitsFormat); string nigthIconKey = _wfProviderSettings.NigthIconKey; string dayIconKey = _wfProviderSettings.DayIconKey; DateTime currentDay = weatherList[0].Dt.ToDateTime(); DateTime nextDay = currentDay; List <DetailedDailyForecastModel> detailedDailyForecasts = new List <DetailedDailyForecastModel>(); //contains icons' names to define most often in a day to set AvgWeatherConditions.IconUrl //contains weather states to define most often in a day to set AvgWeatherConditions.WeatherDescription List <WeatherDetails> weatherDetailsForAvg = new List <WeatherDetails>(); bool isLastDay = false; for (int i = 0; i < weatherList.Count(); i++) { var item = weatherList[i]; var weatherDetails = item.Weather.FirstOrDefault(); weatherDetailsForAvg.Add(weatherDetails); detailedDailyForecasts.Add(new DetailedDailyForecastModel { Time = nextDay.ToWeatherTimeFormat(item.Timezone), WeatherConditions = new WeatherConditionsModel { IconUrl = IconConverter.Generate(_wfProviderSettings.IconStorageAddress, weatherDetails.Icon), Humidity = item.Main.Humidity, Pressure = item.Main.Pressure, Temperature = (int)Math.Round(item.Main.Temp), WindSpeed = Math.Round(item.Wind.Speed, 1), TemperatureFormat = temperatureFormat, WeatherDescription = weatherDetails.Description } }); if (i + 1 < weatherList.Count()) { nextDay = weatherList[i + 1].Dt.ToDateTime(); } else { isLastDay = true; } if (currentDay.Date != nextDay.Date || isLastDay) { //for all days avg weather icon is the most often icon during the day var mostOftenWeatherDescription = weatherDetailsForAvg.GroupBy(i => i.Main) .OrderByDescending(i => i.Count()) .First(); var mostOftenIcon = mostOftenWeatherDescription .GroupBy(i => IconConverter.CutDNSymbol(i.Icon, dayIconKey, nigthIconKey)) .OrderByDescending(i => i.Count()) .First(); //generate full icon url with daytime symbol as most common icon string avgIconUrl = IconConverter.Generate( _wfProviderSettings.IconStorageAddress, mostOftenIcon.Key, dayIconKey ); var dailyForecast = new DailyForecastModel { Date = currentDay.ToWeatherDateFormat(item.Timezone), DetailedDailyForecasts = detailedDailyForecasts, AvgWeatherConditions = new WeatherConditionsModel { Humidity = (int)CalculateAverage(detailedDailyForecasts, i => i.WeatherConditions.Humidity, 0), Pressure = (int)CalculateAverage(detailedDailyForecasts, i => i.WeatherConditions.Pressure, 0), Temperature = (int)CalculateAverage(detailedDailyForecasts, i => i.WeatherConditions.Temperature, 0), WindSpeed = CalculateAverage(detailedDailyForecasts, i => i.WeatherConditions.WindSpeed, 1), IconUrl = avgIconUrl, WeatherDescription = mostOftenWeatherDescription.Key, //set most common weather state as average weather TemperatureFormat = temperatureFormat } }; //save day's forecast forecast.DailyForecasts.Add(dailyForecast); //clear objects for next day forecast detailedDailyForecasts = new List <DetailedDailyForecastModel>(); weatherDetailsForAvg = new List <WeatherDetails>(); //move to next day currentDay = nextDay; } } return(forecast); } catch (Exception ex) { string errorMessage = "Something went wrond during convertion from OpenWeatherForecast to ForecastModel."; _logger.LogError(errorMessage, ex); throw new Exception(errorMessage, ex); } }
public static stdole.IPictureDisp ImageToIPicture(System.Drawing.Image image) { return((stdole.IPictureDisp)IconConverter.GetIPictureDispFromPicture(image)); }