public TargetSourceDirective CreateTargetSource(PropertyTreeNavigator nav, IUriContext uriContext) { if (nav.IsProperty) { Exception error; try { Uri uri = Utility.NewUri(nav.Value.ToString()); uri = Utility.CombineUri(uriContext, uri); return(new TargetSourceDirective(uri)); } catch (ArgumentException e) { error = e; } catch (UriFormatException e) { error = e; } Errors.BadSourceDirective(error, nav.FileLocation); return(null); } else { return(nav.Bind <TargetSourceDirective>()); } }
/// <summary> /// Return an object that should be set on the targetObject's targetProperty /// for this markup extension. For ColorConvertedBitmapExtension, this is the object found in /// a resource dictionary in the current parent chain that is keyed by ResourceKey /// </summary> /// <returns> /// The object to set on this property. /// </returns> public override object ProvideValue(IServiceProvider serviceProvider) { if (_image == null) { throw new InvalidOperationException(SR.Get(SRID.ColorConvertedBitmapExtensionNoSourceImage)); } if (_sourceProfile == null) { throw new InvalidOperationException(SR.Get(SRID.ColorConvertedBitmapExtensionNoSourceProfile)); } // [BreakingChange] // (NullReferenceException in ColorConvertedBitmapExtension.ProvideValue) // We really should throw an ArgumentNullException here for serviceProvider. // Save away the BaseUri. IUriContext uriContext = serviceProvider.GetService(typeof(IUriContext)) as IUriContext; if (uriContext == null) { throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionNoContext, GetType().Name, "IUriContext")); } _baseUri = uriContext.BaseUri; Uri imageUri = GetResolvedUri(_image); Uri sourceProfileUri = GetResolvedUri(_sourceProfile); Uri destinationProfileUri = GetResolvedUri(_destinationProfile); ColorContext sourceContext = new ColorContext(sourceProfileUri); ColorContext destinationContext = destinationProfileUri != null ? new ColorContext(destinationProfileUri) : new ColorContext(PixelFormats.Default); BitmapDecoder decoder = BitmapDecoder.Create( imageUri, BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None ); BitmapSource bitmap = decoder.Frames[0]; FormatConvertedBitmap formatConverted = new FormatConvertedBitmap(bitmap, PixelFormats.Bgra32, null, 0.0); object result = formatConverted; try { ColorConvertedBitmap colorConverted = new ColorConvertedBitmap(formatConverted, sourceContext, destinationContext, PixelFormats.Bgra32); result = colorConverted; } catch (FileFormatException) { // Gracefully ignore non-matching profile // If the file contains a bad color context, we catch the exception here // since color transform isn't possible // with the given color context. } return(result); }
internal static Uri GetUriFromUriContext(IUriContext context, Uri original) { if (!original.IsAbsoluteUri && (context != null) && context.BaseUri != null) { return new Uri(context.BaseUri, original); } return original; }
internal static Uri GetUriFromUriContext(IUriContext context, Uri original) { if (!original.IsAbsoluteUri && (context != null) && context.BaseUri != null) { return(new Uri(context.BaseUri, original)); } return(original); }
static void CopyContextFromParent(object component, IUriContext parent) { var uc = component as IUriContext; if (uc != null) { uc.BaseUri = parent.BaseUri; } }
/// <summary> /// Converts the SVG source file to <see cref="Uri"/> /// </summary> /// <param name="serviceProvider"> /// Object that can provide services for the markup extension. /// </param> /// <returns> /// Returns the valid <see cref="Uri"/> of the SVG source path if /// successful; otherwise, it returns <see langword="null"/>. /// </returns> private Uri GetUri(IServiceProvider serviceProvider) { if (String.IsNullOrEmpty(_svgPath)) { return(null); } Uri svgSource; if (Uri.TryCreate(_svgPath, UriKind.RelativeOrAbsolute, out svgSource)) { if (svgSource.IsAbsoluteUri) { return(svgSource); } else { // Try getting a local file in the same directory.... string svgPath = _svgPath; if (_svgPath[0] == '\\' || _svgPath[0] == '/') { svgPath = _svgPath.Substring(1); } svgPath = svgPath.Replace('/', '\\'); Assembly assembly = Assembly.GetExecutingAssembly(); string localFile = Path.Combine(Path.GetDirectoryName( assembly.Location), svgPath); if (File.Exists(localFile)) { return(new Uri(localFile)); } // Try getting it as resource file... IUriContext uriContext = serviceProvider.GetService( typeof(IUriContext)) as IUriContext; if (uriContext != null && uriContext.BaseUri != null) { return(new Uri(uriContext.BaseUri, svgSource)); } else { string asmName = assembly.GetName().Name; string uriString = String.Format( "pack://application:,,,/{0};component/{1}", asmName, _svgPath); return(new Uri(uriString)); } } } return(null); }
public static Uri CombineUri(IUriContext uriContext, Uri uri) { if (!uri.IsAbsoluteUri) { if (uriContext != null && uriContext.BaseUri != null) { var buri = uriContext.BaseUri; if (!buri.IsAbsoluteUri) { buri = new Uri("file://" + Directory.GetCurrentDirectory()); } uri = new Uri(buri, uri); } } return(uri); }
internal static UriHolder GetUriFromUriContext(ITypeDescriptorContext context, object inputString) { UriHolder uriHolder = new UriHolder(); if (inputString is string) { uriHolder.OriginalUri = new Uri((string)inputString, UriKind.RelativeOrAbsolute); } else { Debug.Assert(inputString is Uri); uriHolder.OriginalUri = (Uri)inputString; } if (uriHolder.OriginalUri.IsAbsoluteUri == false) { //Debug.Assert (context != null, "Context should not be null"); if (context != null) { IUriContext iuc = (IUriContext)context.GetService(typeof(IUriContext)); //Debug.Assert (iuc != null, "IUriContext should not be null here"); if (iuc != null) { // the base uri is NOT "" if (iuc.BaseUri != null) { uriHolder.BaseUri = iuc.BaseUri; if (!uriHolder.BaseUri.IsAbsoluteUri) { uriHolder.BaseUri = new Uri(BaseUriHelper.BaseUri, uriHolder.BaseUri); } } // uriHolder.BaseUriString != "" else { // if we reach here, the base uri we got from IUriContext is "" // and the inputString is a relative uri. Here we resolve it to // application's base uriHolder.BaseUri = BaseUriHelper.BaseUri; } } // iuc != null } // context!= null } // uriHolder.OriginalUri.IsAbsoluteUri == false return(uriHolder); }
internal void InitFrom(IXmlLineInfo lineInfo, IUriContext uriContext, IDictionary <string, string> prefixMap, bool isExpressNamespace) { if (lineInfo != null) { LinePosition = lineInfo.LinePosition; LineNumber = lineInfo.LineNumber; } if (uriContext != null) { BaseUri = uriContext.BaseUri; } _prefixMap = prefixMap; _isExpressNamespace = isExpressNamespace; }
public bool Equals(ResourceDictionary x, ResourceDictionary y) { if (x == null && y == null) { return(true); } if (x == null || y == null) { return(false); } IUriContext a = x; IUriContext b = y; return(Uri.Compare(a.BaseUri, b.BaseUri, UriComponents.Path, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0); }
/// <summary> /// ConvertFrom - Converts the specified object to a FontFamily. /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo cultureInfo, object o) { if ((o != null) && (o.GetType() == typeof(string))) { string s = o as string; if (s == null || s.Length == 0) { throw GetConvertFromException(s); } // Logic below is similar to TypeConverterHelper.GetUriFromUriContext, // except that we cannot treat font family string as a Uri, // and that we handle cases when context is null. Uri baseUri = null; if (context != null) { IUriContext iuc = (IUriContext)context.GetService(typeof(IUriContext)); if (iuc != null) { if (iuc.BaseUri != null) { baseUri = iuc.BaseUri; if (!baseUri.IsAbsoluteUri) { baseUri = new Uri(BaseUriHelper.BaseUri, baseUri); } } else { // If we reach here, the base uri we got from IUriContext is "". // Here we resolve it to application's base baseUri = BaseUriHelper.BaseUri; } } } return(new FontFamily(baseUri, s)); } return(base.ConvertFrom(context, cultureInfo, o));; }
public override void SetUriBase(XamlType xamlType, object obj, Uri baseUri) { try { IUriContext context = obj as IUriContext; if (context != null) { context.BaseUri = baseUri; } } catch (Exception exception) { if (CriticalExceptions.IsCriticalException(exception)) { throw; } throw this.CreateException(System.Xaml.SR.Get("AddDictionary", new object[] { xamlType }), exception); } }
// IActivationProvider implementation public object ActivateComponent(IServiceProvider serviceProvider, object component) { IUriContext uc = component as IUriContext; if (uc != null) { IUriContext sourceContext = (IUriContext)serviceProvider.GetService(typeof(IUriContext)); if (sourceContext != null) { Uri u = sourceContext.BaseUri; if (u != null) { uc.BaseUri = u; } } } return(component); }
/// <summary>Returns an object that should be set on the property where this extension is applied. For <see cref="T:System.Windows.ColorConvertedBitmapExtension" />, this is the completed <see cref="T:System.Windows.Media.Imaging.ColorConvertedBitmap" />.</summary> /// <param name="serviceProvider">An object that can provide services for the markup extension. This service is expected to provide results for <see cref="T:System.Windows.Markup.IUriContext" />.</param> /// <returns>A <see cref="T:System.Windows.Media.Imaging.ColorConvertedBitmap" /> based on the values passed to the constructor.</returns> // Token: 0x06000859 RID: 2137 RVA: 0x0001B1C4 File Offset: 0x000193C4 public override object ProvideValue(IServiceProvider serviceProvider) { if (this._image == null) { throw new InvalidOperationException(SR.Get("ColorConvertedBitmapExtensionNoSourceImage")); } if (this._sourceProfile == null) { throw new InvalidOperationException(SR.Get("ColorConvertedBitmapExtensionNoSourceProfile")); } IUriContext uriContext = serviceProvider.GetService(typeof(IUriContext)) as IUriContext; if (uriContext == null) { throw new InvalidOperationException(SR.Get("MarkupExtensionNoContext", new object[] { base.GetType().Name, "IUriContext" })); } this._baseUri = uriContext.BaseUri; Uri resolvedUri = this.GetResolvedUri(this._image); Uri resolvedUri2 = this.GetResolvedUri(this._sourceProfile); Uri resolvedUri3 = this.GetResolvedUri(this._destinationProfile); ColorContext sourceColorContext = new ColorContext(resolvedUri2); ColorContext destinationColorContext = (resolvedUri3 != null) ? new ColorContext(resolvedUri3) : new ColorContext(PixelFormats.Default); BitmapDecoder bitmapDecoder = BitmapDecoder.Create(resolvedUri, BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None); BitmapSource source = bitmapDecoder.Frames[0]; FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0.0); object result = formatConvertedBitmap; try { ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap(formatConvertedBitmap, sourceColorContext, destinationColorContext, PixelFormats.Bgra32); result = colorConvertedBitmap; } catch (FileFormatException) { } return(result); }
public static object Load(System.Xaml.XamlReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } object root = null; try { root = Load(reader, null); } catch (Exception e) { IUriContext uriContext = reader as IUriContext; Uri baseUri = (uriContext != null) ? uriContext.BaseUri : null; // Don't wrap critical exceptions or already-wrapped exceptions. if (MS.Internal.CriticalExceptions.IsCriticalException(e) || !ShouldReWrapException(e, baseUri)) { throw; } RewrapException(e, baseUri); } finally { if (TraceMarkup.IsEnabled) { TraceMarkup.Trace(TraceEventType.Stop, TraceMarkup.Load, root); } EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Event.WClientParseXmlEnd); #if DEBUG_CLR_MEM if (clrTracingEnabled && (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance)) { CLRProfilerControl.CLRLogWriteLine("End_XamlParse_{0}", pass); } #endif // DEBUG_CLR_MEM } return(root); }
internal override void SetLineInfo(IXmlLineInfo lineInfo, IDictionary<string, string> prefixMap, IUriContext uriContext) { this.lineInfo = lineInfo; this.prefixMap = prefixMap; this.uriContext = uriContext; }
internal virtual void SetLineInfo(IXmlLineInfo lineInfo, IDictionary<string, string> prefixMap, IUriContext uriContext) { }
/// <summary> /// Get BaseUri for a dependency object inside a tree. /// /// </summary> /// <param name="element">Dependency Object</param> /// <returns>BaseUri for the element</returns> /// <remarks> /// Callers must have FileIOPermission(FileIOPermissionAccess.PathDiscovery) for the given Uri to call this API. /// </remarks> internal static Uri GetBaseUriCore(DependencyObject element) { Uri baseUri = null; DependencyObject doCurrent; if (element == null) { throw new ArgumentNullException("element"); } try { // // Search the tree to find the closest parent which implements // IUriContext or have set value for BaseUri property. // doCurrent = element; while (doCurrent != null) { // Try to get BaseUri property value from current node. baseUri = doCurrent.GetValue(BaseUriProperty) as Uri; if (baseUri != null) { // Got the right node which is the closest to original element. // Stop searching here. break; } IUriContext uriContext = doCurrent as IUriContext; if (uriContext != null) { // If the element implements IUriContext, and if the BaseUri // is not null, just take the BaseUri from there. // and stop the search loop. baseUri = uriContext.BaseUri; if (baseUri != null) { break; } } // // The current node doesn't contain BaseUri value, // try its parent node in the tree. UIElement uie = doCurrent as UIElement; if (uie != null) { // Do the tree walk up doCurrent = uie.GetUIParent(true); } else { ContentElement ce = doCurrent as ContentElement; if (ce != null) { doCurrent = ce.Parent; } else { Visual vis = doCurrent as Visual; if (vis != null) { // Try the Visual tree search doCurrent = VisualTreeHelper.GetParent(vis); } else { // Not a Visual. // Stop here for the tree searching to aviod an infinite loop. break; } } } } } finally { // // Putting the permission demand in finally block can prevent from exposing a bogus // and dangerous uri to the code in upper frame. // if (baseUri != null) { SecurityHelper.DemandUriDiscoveryPermission(baseUri); } } return(baseUri); }
public TargetSourceDirective CreateTargetSource(PropertyTreeNavigator nav, IUriContext uriContext) { if (nav.IsProperty) { Exception error; try { Uri uri = new Uri(nav.Value.ToString(), UriKind.RelativeOrAbsolute); uri = Utility.CombineUri(uriContext, uri); return new TargetSourceDirective(uri); } catch (ArgumentException e) { error = e; } catch (UriFormatException e) { error = e; } Errors.BadSourceDirective(error, nav.FileLocation); return null; } else { return nav.Bind<TargetSourceDirective>(); } }
public override object ProvideValue(IServiceProvider serviceProvider) { IProvideValueTarget provideValue = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; if (provideValue == null || provideValue.TargetObject == null) { return(null); // throw new NotSupportedException("The IProvideValueTarget is not supported"); } if (provideValue.TargetObject.GetType().FullName == "System.Windows.SharedDp") { return(this); } DependencyObject targetObject = provideValue.TargetObject as DependencyObject; if (targetObject == null) { Debug.Fail(string.Format("can't persist type {0}, not a dependency object", provideValue.TargetObject)); throw new NotSupportedException(); } DependencyProperty targetProperty = provideValue.TargetProperty as DependencyProperty; if (targetProperty == null) { Debug.Fail(string.Format("can't persist type {0}, not a dependency property", provideValue.TargetProperty)); throw new NotSupportedException(); } Func <DependencyObject, Window> getParent = null; getParent = new Func <DependencyObject, Window>(ui => { var uie = ui; while (!(uie is Window) && uie != null) { uie = LogicalTreeHelper.GetParent(uie); } if (uie == null) { if (ui is UserControl) { var uc = ui as UserControl; if (uc.Parent != null) { return(getParent(uc.Parent)); } else { return(Application.Current.MainWindow); } } return(ui is FrameworkElement ? getParent((ui as FrameworkElement).Parent) : null); } return(uie as Window); }); #region key if (key == null) { IUriContext uriContext = (IUriContext)serviceProvider.GetService(typeof(IUriContext)); if (uriContext == null) { // fallback to default value if no key available DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(targetProperty, targetObject.GetType()); return(descriptor.GetValue(targetObject)); } // UIElements have a 'PersistId' property that we can use to generate a unique key if (targetObject is UIElement) { Func <DependencyObject, string, object> foo = (dp, name) => { var en = dp.GetLocalValueEnumerator(); while (en.MoveNext()) { if (en.Current.Property.Name.ToLower() == name.ToLower()) { return(en.Current.Value); } } return(null); }; string persistID = (foo(targetObject, "Name") ?? ((UIElement)targetObject).PersistId) + ""; var window = getParent(targetObject as UIElement); //System.Diagnostics.Debug.Assert(window!=null,"Main window is <Null>"); var windowName = window == null ? "" : window.Name; key = string.Format("{0}.{1}[{2}.{3}]{4}", uriContext.BaseUri.PathAndQuery, targetObject.GetType().Name, windowName, persistID, targetProperty.Name); } // use parent-child relation to generate unique key else if (LogicalTreeHelper.GetParent(targetObject) is UIElement) { UIElement parent = (UIElement)LogicalTreeHelper.GetParent(targetObject); int i = 0; foreach (object c in LogicalTreeHelper.GetChildren(parent)) { if (c == targetObject) { key = string.Format("{0}.{1}[{2}].{3}[{4}].{5}", uriContext.BaseUri.PathAndQuery, parent.GetType().Name, parent.PersistId, targetObject.GetType().Name, i, targetProperty.Name); break; } i++; } } //TODO:should do something clever here to get a good key for tags like GridViewColumn if (key == null) { Debug.Fail(string.Format("don't know how to automatically get a key for objects of type {0}\n use Key='...' option", targetObject.GetType())); // fallback to default value if no key available DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(targetProperty, targetObject.GetType()); return(descriptor.GetValue(targetObject)); } else { //Debug.WriteLine(string.Format("key={0}", key)); } } #endregion if (!UserSettingsStorage.Dictionary.ContainsKey(key)) { UserSettingsStorage.Dictionary[key] = defaultValue; } object value = ConvertFromString(targetObject, targetProperty, UserSettingsStorage.Dictionary[key]); SetBinding(targetObject, targetProperty, key); return(value); }
internal override void SetLineInfo(IXmlLineInfo lineInfo, IDictionary <string, string> prefixMap, IUriContext uriContext) { this.lineInfo = lineInfo; this.prefixMap = prefixMap; this.uriContext = uriContext; }
/// <summary> /// Converts the SVG source file to <see cref="Uri"/> /// </summary> /// <param name="serviceProvider"> /// Object that can provide services for the markup extension. /// </param> /// <returns> /// Returns the valid <see cref="Uri"/> of the SVG source path if /// successful; otherwise, it returns <see langword="null"/>. /// </returns> private Uri ResolveUri(IServiceProvider serviceProvider) { if (string.IsNullOrWhiteSpace(_svgPath)) { return(null); } Uri svgSource; if (Uri.TryCreate(_svgPath, UriKind.RelativeOrAbsolute, out svgSource)) { if (svgSource.IsAbsoluteUri) { return(svgSource); } // Try getting a local file in the same directory.... string svgPath = _svgPath; if (_svgPath[0] == '\\' || _svgPath[0] == '/') { svgPath = _svgPath.Substring(1); } svgPath = svgPath.Replace('/', '\\'); var assembly = this.GetExecutingAssembly(); if (assembly != null) { string localFile = Path.Combine(Path.GetDirectoryName(assembly.Location), svgPath); if (File.Exists(localFile)) { return(new Uri(localFile)); } } // Try getting it as resource file... IUriContext uriContext = serviceProvider.GetService(typeof(IUriContext)) as IUriContext; if (uriContext != null && uriContext.BaseUri != null) { return(new Uri(uriContext.BaseUri, svgSource)); } string asmName = _appName; // It should not be the DotNetProjects.SVGImage.dll, which contains this extension... if (assembly != null && !string.Equals("DotNetProjects.SVGImage", assembly.GetName().Name, StringComparison.OrdinalIgnoreCase)) { asmName = assembly.GetName().Name; } svgPath = _svgPath; if (_svgPath.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { svgPath = svgPath.TrimStart('/'); } // A little hack to display preview in design mode bool designTime = DesignerProperties.GetIsInDesignMode(new DependencyObject()); if (designTime && !string.IsNullOrWhiteSpace(_appName)) { string uriDesign = string.Format("/{0};component/{1}", _appName, svgPath); return(new Uri(uriDesign, UriKind.Relative)); } string uriString = string.Format("pack://application:,,,/{0};component/{1}", asmName, svgPath); return(new Uri(uriString)); } return(null); }
internal virtual void SetLineInfo(IXmlLineInfo lineInfo, IDictionary <string, string> prefixMap, IUriContext uriContext) { }
internal static Uri GetBaseUriCore(DependencyObject element) { Uri uri = null; if (element != null) { try { DependencyObject dependencyObject = element; while (true) { if (dependencyObject == null) { return(uri); } uri = (dependencyObject.GetValue(BaseUriProperty) as Uri); if (uri != null) { return(uri); } IUriContext uriContext = dependencyObject as IUriContext; if (uriContext != null) { uri = uriContext.BaseUri; if (uri != null) { return(uri); } } UIElement uIElement = dependencyObject as UIElement; if (uIElement != null) { dependencyObject = uIElement.GetUIParent(true); } else { ContentElement contentElement = dependencyObject as ContentElement; if (contentElement != null) { dependencyObject = contentElement.Parent; } else { Visual visual = dependencyObject as Visual; if (visual == null) { break; } dependencyObject = VisualTreeHelper.GetParent(visual); } } } return(uri); } finally { if (uri != null) { SecurityHelper.DemandUriDiscoveryPermission(uri); } } } throw new ArgumentNullException(nameof(element)); }