コード例 #1
0
            /// <summary>
            /// Writes the JSON representation of the object.
            /// </summary>
            /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
            /// <param name="value">The value.</param>
            /// <param name="serializer">The calling serializer.</param>
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                Type valueType = value.GetType();

                // We don't want to use the type name of the enum itself; instead we marshal
                // it as a decimal number inside of a string
                if (valueType.GetTypeInfo().IsEnum)
                {
                    value     = ((Enum)value).ToString("D");
                    valueType = typeof(String);
                }

                PropertyValidation.ValidatePropertyValue(WebApiResources.SerializingPhrase(), value);

                //write out as an object with type information
                writer.WriteStartObject();
                writer.WritePropertyName(TypePropertyName);

                // Check that the Type we're claiming is safely deserializable
                String typeName = valueType.FullName;

                if (!PropertyValidation.IsValidTypeString(typeName))
                {
                    throw new PropertyTypeNotSupportedException(TypePropertyName, valueType);
                }

                writer.WriteValue(typeName);
                writer.WritePropertyName(ValuePropertyName);
                writer.WriteValue(value);
                writer.WriteEndObject();
            }
コード例 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="managedType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private Task <Object> GetServiceInstanceAsync(
            Type managedType,
            Guid serviceIdentifier,
            CancellationToken cancellationToken)
        {
            CheckForDisposed();
            IVssClientService clientService;

            try
            {
                // Create our instance of the managed service object.
                clientService = (IVssClientService)Activator.CreateInstance(managedType);
            }
            catch (MissingMemberException ex)
            {
                throw new ArgumentException(WebApiResources.GetServiceArgumentError(managedType), ex);
            }


            //  We successfully created an object, initialize him and finally set the
            //  return value.
            clientService.Initialize(this);

            return(Task.FromResult <Object>(clientService));
        }
コード例 #3
0
            /// <summary>
            /// Because ReferenceLinks is a dictionary of either a single
            /// ReferenceLink or an array of ReferenceLinks, we need custom
            /// deserialization to correctly rebuild the dictionary.
            /// </summary>
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                var unresolvedLinks = serializer.Deserialize <Dictionary <String, object> >(reader);

                if (unresolvedLinks == null)
                {
                    return(null);
                }

                var links = new Dictionary <String, Object>();

                foreach (var entry in unresolvedLinks)
                {
                    if (String.IsNullOrEmpty(entry.Key))
                    {
                        throw new JsonSerializationException(WebApiResources.InvalidReferenceLinkFormat());
                    }

                    JToken token = entry.Value as JToken;
                    if (token != null)
                    {
                        switch (token.Type)
                        {
                        case JTokenType.Array:
                            using (var tokenReader = token.CreateReader())
                            {
                                links[entry.Key] = serializer.Deserialize <IList <ReferenceLink> >(tokenReader);
                            }
                            break;

                        case JTokenType.Object:
                            using (var tokenReader = token.CreateReader())
                            {
                                links[entry.Key] = serializer.Deserialize <ReferenceLink>(tokenReader);
                            }
                            break;

                        default:
                            throw new JsonSerializationException(WebApiResources.InvalidReferenceLinkFormat());
                        }
                    }
                    else if (entry.Value is ReferenceLink || entry.Value is IList <ReferenceLink> )
                    {
                        links[entry.Key] = entry.Value;
                    }
                    else
                    {
                        throw new JsonSerializationException(WebApiResources.InvalidReferenceLinkFormat());
                    }
                }

                return(new ReferenceLinks {
                    referenceLinks = links
                });
            }
コード例 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="managedType"></param>
        /// <returns></returns>
        private async Task <Object> GetClientInstanceAsync(
            Type managedType,
            Guid serviceIdentifier,
            CancellationToken cancellationToken,
            VssHttpRequestSettings settings,
            DelegatingHandler[] handlers)
        {
            CheckForDisposed();
            ILocationService locationService = await GetServiceAsync <ILocationService>(cancellationToken).ConfigureAwait(false);

            ILocationDataProvider locationData = await locationService.GetLocationDataAsync(serviceIdentifier, cancellationToken).ConfigureAwait(false);

            if (locationData == null)
            {
                throw new VssServiceException(WebApiResources.ServerDataProviderNotFound(serviceIdentifier));
            }

            String serviceLocationString = await locationData.LocationForCurrentConnectionAsync(
                ServiceInterfaces.LocationService2,
                LocationServiceConstants.SelfReferenceIdentifier,
                cancellationToken).ConfigureAwait(false);

            // This won't ever be null because of compat code in ServerDataProvider
            Uri clientBaseUri = new Uri(serviceLocationString);

            VssHttpClientBase toReturn = null;

            if (settings != null)
            {
                toReturn = (VssHttpClientBase)Activator.CreateInstance(managedType, clientBaseUri, Credentials, settings, handlers);
            }
            else
            {
                toReturn = (VssHttpClientBase)Activator.CreateInstance(managedType, clientBaseUri, m_pipeline, false /* disposeHandler */);
            }

            ApiResourceLocationCollection resourceLocations = await locationData.GetResourceLocationsAsync(cancellationToken).ConfigureAwait(false);

            toReturn.SetResourceLocations(resourceLocations);

            return(toReturn);
        }
コード例 #5
0
 public VssResourceNotFoundException(Guid locationId, Uri serverBaseUri)
     : this(WebApiResources.ResourceNotFoundOnServerMessage(locationId, serverBaseUri))
 {
 }
コード例 #6
0
 public VssInvalidApiResourceVersionException(String apiResourceVersionString)
     : base(WebApiResources.InvalidApiVersionStringMessage(apiResourceVersionString))
 {
 }
コード例 #7
0
 public VssRequestContentTypeNotSupportedException(String contentType, String httpMethod, IEnumerable <String> validContentTypes)
     : base(WebApiResources.RequestContentTypeNotSupported(contentType, httpMethod, String.Join(", ", validContentTypes)))
 {
 }
コード例 #8
0
 public VssApiUnsafeCrossOriginRequestException(String origin)
     : base(WebApiResources.UnsafeCrossOriginRequest(origin))
 {
 }
 public ProxyAuthenticationRequiredException()
     : base(WebApiResources.ProxyAuthenticationRequired())
 {
     this.HelpLink = HelpLinkUrl;
 }
コード例 #10
0
 public VssInvalidPreviewVersionException(ApiResourceVersion requestedVersion)
     : base(WebApiResources.PreviewVersionNotSuppliedMessage(requestedVersion.ToString()))
 {
 }
コード例 #11
0
 public ExtensibleServiceTypeNotRegisteredException(Type managedType)
     : base(WebApiResources.ExtensibleServiceTypeNotRegistered(managedType.Name))
 {
 }
コード例 #12
0
 public VssVersionNotSupportedException(ApiResourceLocation location, Version requestedVersion, Version minSupportedVersion, Uri serverBaseUri)
     : base(WebApiResources.ClientResourceVersionNotSupported(location.Area + ":" + location.ResourceName + " " + location.Id, requestedVersion, serverBaseUri, minSupportedVersion))
 {
 }
コード例 #13
0
 public VssVersionOutOfRangeException(Version requestedVersion, Version maxSupportedVersion)
     : base(WebApiResources.ApiVersionOutOfRange(requestedVersion, maxSupportedVersion))
 {
 }
コード例 #14
0
 public VssVersionOutOfRangeException(ApiResourceVersion requestedApiVersion, string routeMatchedExceptVersion)
     : base(WebApiResources.ApiVersionOutOfRangeForRoute(requestedApiVersion, routeMatchedExceptVersion))
 {
 }
コード例 #15
0
        public static JToken Map(
            this JToken token,
            Dictionary <JTokenType, Func <JToken, JToken> > mapFuncs)
        {
            // no map funcs, just clones
            mapFuncs = mapFuncs ?? new Dictionary <JTokenType, Func <JToken, JToken> >();

            Func <JToken, JToken> mapperFunc;

            // process token
            switch (token.Type)
            {
            case JTokenType.Array:
                JArray newArray = new JArray();
                foreach (JToken item in token.Children())
                {
                    JToken child = item;
                    if (child.HasValues)
                    {
                        child = child.Map(mapFuncs);
                    }

                    if (mapFuncs.TryGetValue(child.Type, out mapperFunc))
                    {
                        child = mapperFunc(child);
                    }

                    newArray.Add(child);
                }

                return(newArray);

            case JTokenType.Object:
                JObject copy = new JObject();
                foreach (JProperty prop in token.Children <JProperty>())
                {
                    JToken child = prop.Value;
                    if (child.HasValues)
                    {
                        child = child.Map(mapFuncs);
                    }

                    if (mapFuncs.TryGetValue(child.Type, out mapperFunc))
                    {
                        child = mapperFunc(child);
                    }

                    copy.Add(prop.Name, child);
                }

                return(copy);

            case JTokenType.String:
                if (mapFuncs.TryGetValue(JTokenType.String, out mapperFunc))
                {
                    return(mapperFunc(token));
                }

                return(token);

            case JTokenType.Boolean:
            case JTokenType.Null:
            case JTokenType.Guid:
                return(token);

            default:
                throw new NotSupportedException(WebApiResources.UnexpectedTokenType());
            }
        }
コード例 #16
0
            /// <summary>
            /// Reads the JSON representation of the object.
            /// </summary>
            /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
            /// <param name="objectType">Type of the object.</param>
            /// <param name="existingValue">The existing value of object being read.</param>
            /// <param name="serializer">The calling serializer.</param>
            /// <returns>The object value.</returns>
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                if (reader.TokenType == JsonToken.StartObject)
                {
                    JObject valueInfo = serializer.Deserialize <JObject>(reader);
                    if (!valueInfo.TryGetValue(TypePropertyName, out JToken typeToken) ||
                        !valueInfo.TryGetValue(ValuePropertyName, out JToken valueToken))
                    {
                        // The following block is for compatability with old code behavior.
                        // The old code blindly took the first argument add treated it as the $type string,
                        // It blindly took the second argument and treated it as the $value object.
                        IEnumerator <JToken> tokenEnumerator = valueInfo.Values().GetEnumerator();
                        if (tokenEnumerator.MoveNext())
                        {
                            typeToken = tokenEnumerator.Current;
                            if (tokenEnumerator.MoveNext())
                            {
                                valueToken = tokenEnumerator.Current;
                            }
                            else
                            {
                                throw new InvalidOperationException(WebApiResources.DeserializationCorrupt());
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException(WebApiResources.DeserializationCorrupt());
                        }
                    }

                    string typeToCreate = typeToken.ToObject <string>();

                    //make sure the string is a valid type,
                    //an arbitrary type string with nested generics could overflow the
                    //stack for a DOS.
                    if (!PropertyValidation.TryGetValidType(typeToCreate, out Type type))
                    {
                        throw new InvalidOperationException(WebApiResources.DeserializationCorrupt());
                    }

                    //deserialize the type
                    return(valueToken.ToObject(type));
                }
                else if (reader.TokenType == JsonToken.Boolean ||
                         reader.TokenType == JsonToken.Bytes ||
                         reader.TokenType == JsonToken.Date ||
                         reader.TokenType == JsonToken.Float ||
                         reader.TokenType == JsonToken.Integer ||
                         reader.TokenType == JsonToken.String)
                {
                    // Allow the JSON to simply specify "name": value syntax if type information is not necessary.
                    return(serializer.Deserialize(reader));
                }
                else if (reader.TokenType == JsonToken.Null)
                {
                    return(null);
                }
                else
                {
                    throw new InvalidOperationException(WebApiResources.DeserializationCorrupt());
                }
            }
コード例 #17
0
 public ExtensibleServiceTypeNotValidException(Type managedType, Type extensibleType)
     : base(WebApiResources.ExtensibleServiceTypeNotValid(managedType.Name, extensibleType.Name))
 {
 }
コード例 #18
0
 public VssApiResourceDuplicateIdException(Guid locationId)
     : base(WebApiResources.ApiResourceDuplicateIdMessage(locationId))
 {
 }
コード例 #19
0
 public VssVersionNotSpecifiedException(String httpMethod)
     : base(WebApiResources.VersionNotSuppliedMessage(httpMethod))
 {
 }
コード例 #20
0
 public VssApiResourceDuplicateRouteNameException(string routeName)
     : base(WebApiResources.ApiResourceDuplicateRouteNameMessage(routeName))
 {
 }
コード例 #21
0
 public VssResourceNotFoundException(Guid locationId)
     : this(WebApiResources.ResourceNotRegisteredMessage(locationId))
 {
 }
コード例 #22
0
 public VssVersionOutOfRangeException(ApiResourceVersion requestedApiVersion, IEnumerable <string> routesMatchedExceptVersion)
     : base(WebApiResources.ApiVersionOutOfRangeForRoutes(requestedApiVersion, string.Join(", ", routesMatchedExceptVersion)))
 {
 }
コード例 #23
0
 public CannotGetUnattributedClientException(Type clientType)
     : base(WebApiResources.CannotGetUnattributedClient(clientType.Name))
 {
 }