1 //------------------------------------------------------------------------------
2 // <copyright file="GuidConverter.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 //------------------------------------------------------------------------------
9 namespace System.ComponentModel {
10 using Microsoft.Win32;
11 using System.ComponentModel.Design.Serialization;
12 using System.Diagnostics;
13 using System.Globalization;
14 using System.Reflection;
15 using System.Runtime.InteropServices;
16 using System.Runtime.Remoting;
17 using System.Runtime.Serialization.Formatters;
18 using System.Security.Permissions;
22 /// type converter to convert globally unique identifier objects to and from various
23 /// other representations.</para>
25 [HostProtection(SharedState = true)]
26 public class GuidConverter : TypeConverter {
29 /// <para>Gets a value indicating whether this
30 /// converter can convert an object in the given source type to a globally unique identifier object
31 /// using the context.</para>
33 public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
34 if (sourceType == typeof(string)) {
37 return base.CanConvertFrom(context, sourceType);
41 /// <para>Gets a value indicating whether this converter can
42 /// convert an object to the given destination type using the context.</para>
44 public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
45 if (destinationType == typeof(InstanceDescriptor)) {
48 return base.CanConvertTo(context, destinationType);
53 /// the given object to a globally unique identifier object.</para>
55 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
56 if (value is string) {
57 string text = ((string)value).Trim();
58 return new Guid(text);
60 return base.ConvertFrom(context, culture, value);
64 /// Converts the given object to another type. The most common types to convert
65 /// are to and from a string object. The default implementation will make a call
66 /// to ToString on the object if the object is valid and if the destination
67 /// type is string. If this cannot convert to the desitnation type, this will
68 /// throw a NotSupportedException.
70 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
71 if (destinationType == null) {
72 throw new ArgumentNullException("destinationType");
75 if (destinationType == typeof(InstanceDescriptor) && value is Guid) {
76 ConstructorInfo ctor = typeof(Guid).GetConstructor(new Type[] {typeof(string)});
78 return new InstanceDescriptor(ctor, new object[] {value.ToString()});
82 return base.ConvertTo(context, culture, value, destinationType);