The WebConvert class is a collection of conversion routines designed for use with the web.
Exemplo n.º 1
0
            public StringBuilder GetSkipToken()
            {
                object[] skipTokenProperties = this.GetSkipTokenProperties();
                bool     flag = true;

                for (int i = 0; i < skipTokenProperties.Length; i++)
                {
                    string str;
                    object obj2 = skipTokenProperties[i];
                    if (obj2 == null)
                    {
                        str = "null";
                    }
                    else if (!WebConvert.TryKeyPrimitiveToString(obj2, out str))
                    {
                        throw new InvalidOperationException(System.Data.Services.Strings.Serializer_CannotConvertValue(obj2));
                    }
                    if (!flag)
                    {
                        this.skipToken.Append(',');
                    }
                    this.skipToken.Append(str);
                    flag = false;
                }
                return(this.skipToken);
            }
Exemplo n.º 2
0
 internal static bool TryKeyPrimitiveToString(object value, out string result)
 {
     if (IsBinaryValue(value))
     {
         return(TryKeyBinaryToString(value, out result));
     }
     return(WebConvert.TryKeyPrimitiveToString(value, out result));
 }
Exemplo n.º 3
0
        private static IEnumerable <KeyValuePair <string, object> > ParseETagValue(IList <ResourceProperty> etagProperties, string ifMatchHeaderValue)
        {
            bool flag;

            if (ifMatchHeaderValue == "*")
            {
                return(WebUtil.EmptyKeyValuePairStringObject);
            }
            string      stringToUnescape = ifMatchHeaderValue.Substring("W/\"".Length, (ifMatchHeaderValue.Length - "W/\"".Length) - 1);
            KeyInstance instance         = null;
            Exception   innerException   = null;

            try
            {
                flag = KeyInstance.TryParseNullableTokens(Uri.UnescapeDataString(stringToUnescape), out instance);
            }
            catch (DataServiceException exception2)
            {
                flag           = false;
                innerException = exception2;
            }
            if (!flag)
            {
                throw DataServiceException.CreatePreConditionFailedError(System.Data.Services.Strings.Serializer_ETagValueDoesNotMatch, innerException);
            }
            if (instance.PositionalValues.Count != etagProperties.Count)
            {
                throw DataServiceException.CreatePreConditionFailedError(System.Data.Services.Strings.Serializer_ETagValueDoesNotMatch);
            }
            KeyValuePair <string, object>[] pairArray = new KeyValuePair <string, object> [etagProperties.Count];
            for (int i = 0; i < pairArray.Length; i++)
            {
                ResourceProperty property    = etagProperties[i];
                object           targetValue = null;
                string           text        = (string)instance.PositionalValues[i];
                if (text != "null")
                {
                    try
                    {
                        flag = WebConvert.TryKeyStringToPrimitive(text, property.Type, out targetValue);
                    }
                    catch (OverflowException exception3)
                    {
                        flag           = false;
                        innerException = exception3;
                    }
                    if (!flag)
                    {
                        throw DataServiceException.CreatePreConditionFailedError(System.Data.Services.Strings.Serializer_ETagValueDoesNotMatch, innerException);
                    }
                }
                pairArray[i] = new KeyValuePair <string, object>(etagProperties[i].Name, targetValue);
            }
            return(pairArray);
        }
Exemplo n.º 4
0
        /// <summary>Tries to convert values to the keys of the specified type.</summary>
        /// <param name="type">Type with key information for conversion.</param>
        /// <returns>true if all values were converted; false otherwise.</returns>
        internal bool TryConvertValues(ResourceType type)
        {
            Debug.Assert(type != null, "type != null");
            Debug.Assert(!this.IsEmpty, "!this.IsEmpty -- caller should check");
            Debug.Assert(type.KeyProperties.Count == this.ValueCount, "type.KeyProperties.Count == this.ValueCount -- will change with containment");
            if (this.namedValues != null)
            {
                for (int i = 0; i < type.KeyProperties.Count; i++)
                {
                    ResourceProperty property = type.KeyProperties[i];
                    object           unconvertedValue;
                    if (!this.namedValues.TryGetValue(property.Name, out unconvertedValue))
                    {
                        return(false);
                    }

                    string valueText = (string)unconvertedValue;
                    object convertedValue;
                    if (!WebConvert.TryKeyStringToPrimitive(valueText, property.Type, out convertedValue))
                    {
                        return(false);
                    }

                    this.namedValues[property.Name] = convertedValue;
                }
            }
            else
            {
                Debug.Assert(this.positionalValues != null, "positionalValues != null -- otherwise this is Empty");
                for (int i = 0; i < type.KeyProperties.Count; i++)
                {
                    string valueText = (string)this.positionalValues[i];
                    object convertedValue;
                    if (!WebConvert.TryKeyStringToPrimitive(valueText, type.KeyProperties[i].Type, out convertedValue))
                    {
                        return(false);
                    }

                    this.positionalValues[i] = convertedValue;
                }
            }

            return(true);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Tries to extract the WellKnownTextSQL portion from an astoria spatial literal.
        /// </summary>
        /// <param name="spatialLiteral">The spatial literal.</param>
        /// <param name="prefix">The prefix.</param>
        /// <param name="wellKnownTextSql">The well known text SQL.</param>
        /// <returns>true if the extract was successful, false otherwise.</returns>
        private static bool TryExtractWellKnownTextSqlFromSpatialLiteral(string spatialLiteral, string prefix, out string wellKnownTextSql)
        {
            var worked = WebConvert.TryRemovePrefix(prefix, ref spatialLiteral);

            if (!worked)
            {
                wellKnownTextSql = null;
                return(false);
            }

            worked = WebConvert.TryRemoveQuotes(ref spatialLiteral);
            if (!worked)
            {
                wellKnownTextSql = null;
                return(false);
            }

            wellKnownTextSql = spatialLiteral;
            return(true);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Converts the given value to the expected type as per XML serializer rules.
        /// Make sure these rules are in sync with PlainXmlSerializer.
        /// </summary>
        /// <param name="value">value to the converted</param>
        /// <param name="propertyName">name of the property whose value is getting converted</param>
        /// <param name="typeToBeConverted">clr type to which the value needs to be converted to</param>
        /// <returns>object which is in sync with the properties type</returns>
        internal static object ConvertValuesForXml(object value, string propertyName, Type typeToBeConverted)
        {
            Debug.Assert(WebUtil.IsPrimitiveType(typeToBeConverted), "WebUtil.IsPrimitiveType(typeToBeConverted)");
            Debug.Assert(value == null || value is string, "This method should be used only for converting string to a primitve value.");

            string stringValue = value as string;

            if (stringValue != null)
            {
                try
                {
                    value = WebConvert.StringToPrimitive(stringValue, typeToBeConverted);
                }
                catch (FormatException e)
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_ErrorInConvertingPropertyValue(propertyName, typeToBeConverted), e);
                }
            }

            return(value);
        }
Exemplo n.º 7
0
        private static string GetObjectKey(object resource, ResourceType resourceType, DataServiceProviderWrapper provider, string containerName)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append(containerName);
            builder.Append('(');
            IList <ResourceProperty> keyProperties = resourceType.KeyProperties;

            for (int i = 0; i < keyProperties.Count; i++)
            {
                string           str;
                ResourceProperty resourceProperty = keyProperties[i];
                object           obj2             = WebUtil.GetPropertyValue(provider, resource, resourceType, resourceProperty, null);
                if (obj2 == null)
                {
                    throw new InvalidOperationException(System.Data.Services.Strings.Serializer_NullKeysAreNotSupported(resourceProperty.Name));
                }
                if (i == 0)
                {
                    if (keyProperties.Count != 1)
                    {
                        builder.Append(resourceProperty.Name);
                        builder.Append('=');
                    }
                }
                else
                {
                    builder.Append(',');
                    builder.Append(resourceProperty.Name);
                    builder.Append('=');
                }
                if (!WebConvert.TryKeyPrimitiveToString(obj2, out str))
                {
                    throw new InvalidOperationException(System.Data.Services.Strings.Serializer_CannotConvertValue(obj2));
                }
                builder.Append(str);
            }
            builder.Append(')');
            return(builder.ToString());
        }
Exemplo n.º 8
0
        internal static string GetETagValue(object resource, ResourceType resourceType, ICollection <ResourceProperty> etagProperties, IDataService service, bool getMethod)
        {
            StringBuilder builder = new StringBuilder();
            bool          flag    = true;

            builder.Append("W/\"");
            foreach (ResourceProperty property in etagProperties)
            {
                object obj2;
                string str;
                if (getMethod)
                {
                    obj2 = GetPropertyValue(service.Provider, resource, resourceType, property, null);
                }
                else
                {
                    obj2 = service.Updatable.GetValue(resource, property.Name);
                }
                if (flag)
                {
                    flag = false;
                }
                else
                {
                    builder.Append(',');
                }
                if (obj2 == null)
                {
                    str = "null";
                }
                else if (!WebConvert.TryKeyPrimitiveToString(obj2, out str))
                {
                    throw new InvalidOperationException(System.Data.Services.Strings.Serializer_CannotConvertValue(obj2));
                }
                builder.Append(str);
            }
            builder.Append('"');
            return(builder.ToString());
        }
Exemplo n.º 9
0
 internal bool TryConvertValues(ResourceType type)
 {
     if (this.namedValues != null)
     {
         for (int i = 0; i < type.KeyProperties.Count; i++)
         {
             object           obj2;
             object           obj3;
             ResourceProperty property = type.KeyProperties[i];
             if (!this.namedValues.TryGetValue(property.Name, out obj2))
             {
                 return(false);
             }
             string text = (string)obj2;
             if (!WebConvert.TryKeyStringToPrimitive(text, property.Type, out obj3))
             {
                 return(false);
             }
             this.namedValues[property.Name] = obj3;
         }
     }
     else
     {
         for (int j = 0; j < type.KeyProperties.Count; j++)
         {
             object obj4;
             string str2 = (string)this.positionalValues[j];
             if (!WebConvert.TryKeyStringToPrimitive(str2, type.KeyProperties[j].Type, out obj4))
             {
                 return(false);
             }
             this.positionalValues[j] = obj4;
         }
     }
     return(true);
 }
Exemplo n.º 10
0
        /// <summary>Parses a token that starts with a digit.</summary>
        /// <returns>The kind of token recognized.</returns>
        private ExpressionTokenKind ParseFromDigit()
        {
            Debug.Assert(this.IsValidDigit || ('-' == this.ch), "this.IsValidDigit || ('-' == this.ch)");
            ExpressionTokenKind result;
            int  tokenPos  = this.textPos;
            char?startChar = this.ch;

            this.NextChar();
            if (startChar == '0' && (this.ch == 'x' || this.ch == 'X'))
            {
                result = ExpressionTokenKind.BinaryLiteral;
                do
                {
                    this.NextChar();
                }while (this.ch.HasValue && WebConvert.IsCharHexDigit(this.ch.Value));
            }
            else
            {
                result = ExpressionTokenKind.IntegerLiteral;
                while (this.IsValidDigit)
                {
                    this.NextChar();
                }

                // DateTimeOffset and Guids will have '-' in them
                if (this.ch == '-')
                {
                    if (this.TryParseDateTimeoffset(tokenPos))
                    {
                        return(ExpressionTokenKind.DateTimeOffsetLiteral);
                    }
                    else if (this.TryParseGuid(tokenPos))
                    {
                        return(ExpressionTokenKind.GuidLiteral);
                    }
                }

                // Guids will have alpha-numeric characters along with '-', so if a letter is encountered
                // try to see if this is Guid or not.
                if (this.ch.HasValue && Char.IsLetter(this.ch.Value))
                {
                    if (this.TryParseGuid(tokenPos))
                    {
                        return(ExpressionTokenKind.GuidLiteral);
                    }
                }

                if (this.ch == '.')
                {
                    result = ExpressionTokenKind.DoubleLiteral;
                    this.NextChar();
                    this.ValidateDigit();

                    do
                    {
                        this.NextChar();
                    }while (this.IsValidDigit);
                }

                if (this.ch == 'E' || this.ch == 'e')
                {
                    result = ExpressionTokenKind.DoubleLiteral;
                    this.NextChar();
                    if (this.ch == '+' || this.ch == '-')
                    {
                        this.NextChar();
                    }

                    this.ValidateDigit();
                    do
                    {
                        this.NextChar();
                    }while (this.IsValidDigit);
                }

                if (this.ch == 'M' || this.ch == 'm')
                {
                    result = ExpressionTokenKind.DecimalLiteral;
                    this.NextChar();
                }
                else if (this.ch == 'd' || this.ch == 'D')
                {
                    result = ExpressionTokenKind.DoubleLiteral;
                    this.NextChar();
                }
                else if (this.ch == 'L' || this.ch == 'l')
                {
                    result = ExpressionTokenKind.Int64Literal;
                    this.NextChar();
                }
                else if (this.ch == 'f' || this.ch == 'F')
                {
                    result = ExpressionTokenKind.SingleLiteral;
                    this.NextChar();
                }
                else
                {
                    string valueStr = this.text.Substring(tokenPos, this.textPos - tokenPos);
                    result = MakeBestGuessOnNoSuffixStr(valueStr, result);
                }
            }

            return(result);
        }
Exemplo n.º 11
0
 internal static bool TryKeyBinaryToString(object binaryValue, out string result)
 {
     byte[] buffer = (byte[])binaryValue.GetType().InvokeMember("ToArray", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, binaryValue, null, CultureInfo.InvariantCulture);
     return(WebConvert.TryKeyPrimitiveToString(buffer, out result));
 }
Exemplo n.º 12
0
 private static bool QuotesAreValid(string text)
 {
     return(WebConvert.TryRemoveQuotes(ref text));
 }
        // Get the access token via straight http post request doing client credential flow
        private async Task <String> GetAppOnlyAccessTokenWithHttpRequest(string resource, string tenantId)
        {
            /**
             * use the tenant specific endpoint for requesting the app-only access token
             */
            string tokenIssueEndpoint = appConfig.TokenIssueingUri.Replace("common", tenantId);

            /**
             * sign the assertion with the private key
             */
            string           certfile = Server.MapPath(appConfig.ClientCertificatePfx);
            X509Certificate2 cert     = new X509Certificate2(
                certfile,
                appConfig.ClientCertificatePfxPassword,
                X509KeyStorageFlags.MachineKeySet);

            /**
             * Example building assertion using Json Tokenhandler.
             * Sort of cheating, but just if someone wonders ... there are always more ways to do something :-)
             */
            Dictionary <string, string> claims = new Dictionary <string, string>()
            {
                { "sub", appConfig.ClientId },
                { "jti", Guid.NewGuid().ToString() },
            };

            JwtSecurityTokenHandler tokenHandler       = new JwtSecurityTokenHandler();
            X509SigningCredentials  signingCredentials = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);

            JwtSecurityToken selfSignedToken = new JwtSecurityToken(
                appConfig.ClientId,
                tokenIssueEndpoint,
                claims.Select(c => new Claim(c.Key, c.Value)),
                DateTime.UtcNow,
                DateTime.UtcNow.Add(TimeSpan.FromMinutes(15)),
                signingCredentials);

            string signedAssertion = tokenHandler.WriteToken(selfSignedToken);

            //---- End example with Json Tokenhandler... now to the fun part doing it all ourselves ...

            /**
             * Example building assertion from scratch with Crypto APIs
             */
            JObject clientAssertion = new JObject();

            clientAssertion.Add("aud", tokenIssueEndpoint);
            clientAssertion.Add("iss", appConfig.ClientId);
            clientAssertion.Add("sub", appConfig.ClientId);
            clientAssertion.Add("jti", Guid.NewGuid().ToString());
            clientAssertion.Add("nbf", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(-5)));
            clientAssertion.Add("exp", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(15)));

            string assertionPayload = clientAssertion.ToString(Newtonsoft.Json.Formatting.None);

            X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(cert);
            RSACryptoServiceProvider  rsa     = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;
            RSACryptoServiceProvider  newRsa  = GetCryptoProviderForSha256(rsa);
            SHA256Cng sha = new SHA256Cng();

            JObject header     = new JObject(new JProperty("alg", "RS256"));
            string  thumbprint = WebConvert.Base64UrlEncoded(WebConvert.HexStringToBytes(cert.Thumbprint));

            header.Add(new JProperty("x5t", thumbprint));

            string encodedHeader  = WebConvert.Base64UrlEncoded(header.ToString());
            string encodedPayload = WebConvert.Base64UrlEncoded(assertionPayload);

            string signingInput = String.Concat(encodedHeader, ".", encodedPayload);

            byte[] signature = newRsa.SignData(Encoding.UTF8.GetBytes(signingInput), sha);

            signedAssertion = string.Format("{0}.{1}.{2}",
                                            encodedHeader,
                                            encodedPayload,
                                            WebConvert.Base64UrlEncoded(signature));

            /**
             * build the request payload
             */
            FormUrlEncodedContent tokenRequestForm;

            tokenRequestForm = new FormUrlEncodedContent(
                new[] {
                new KeyValuePair <string, string>("resource", appConfig.ExchangeResourceUri),
                new KeyValuePair <string, string>("client_id", appConfig.ClientId),
                new KeyValuePair <string, string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
                new KeyValuePair <string, string>("client_assertion", signedAssertion),
                new KeyValuePair <string, string>("grant_type", "client_credentials"),
            }
                );

            /*
             * Do the web request
             */
            HttpClient client = new HttpClient();

            Task <string> requestString  = tokenRequestForm.ReadAsStringAsync();
            StringContent requestContent = new StringContent(requestString.Result);

            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            requestContent.Headers.Add("client-request-id", System.Guid.NewGuid().ToString());
            requestContent.Headers.Add("return-client-request-id", "true");
            requestContent.Headers.Add("UserAgent", "MatthiasLeibmannsAppOnlyAppSampleBeta/0.1");

            HttpResponseMessage response       = client.PostAsync(tokenIssueEndpoint, requestContent).Result;
            JObject             jsonResponse   = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            JsonSerializer      jsonSerializer = new JsonSerializer();

            if (response.IsSuccessStatusCode == true)
            {
                AADClientCredentialSuccessResponse s = (AADClientCredentialSuccessResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialSuccessResponse));
                return(s.access_token);
            }

            AADClientCredentialErrorResponse e = (AADClientCredentialErrorResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialErrorResponse));

            throw new Exception(e.error_description);
        }
Exemplo n.º 14
0
        private Expression PromoteExpression(Expression expr, Type type, bool exact, bool isTypeCast = false)
        {
            Debug.Assert(expr != null, "expr != null");
            Debug.Assert(type != null, "type != null");
            if (expr.Type == type)
            {
                return(expr);
            }

            ConstantExpression ce = null;

            if (type == typeof(DateTime))
            {
                // Sometimes if the property type is DateTime? in provider, we pass the type as DateTimeOffset?
                // to ODataLib and it puts a Convert node to convert DateTimeOffset to DateTimeOffset?. Hence
                // to reach to the constant value, we need to handle the Convert node.
                if (expr.Type == typeof(DateTimeOffset) || expr.Type == typeof(DateTimeOffset?))
                {
                    if (expr.NodeType == ExpressionType.Convert)
                    {
                        ce = ((UnaryExpression)expr).Operand as ConstantExpression;
                    }
                }
            }

            if (ce == null)
            {
                ce = expr as ConstantExpression;
            }

            if (ce != null)
            {
                if (ce == ExpressionUtils.NullLiteral)
                {
                    if (WebUtil.TypeAllowsNull(type))
                    {
                        return(Expression.Constant(null, type));
                    }
                }
                else
                {
                    string text;
                    if (this.literals.TryGetValue(ce, out text))
                    {
                        Type   target = WebUtil.GetNonNullableType(type);
                        object value  = null;
                        if (ce.Type == typeof(string) && (target == typeof(Type) || target == typeof(ResourceType)))
                        {
                            // No qoutes required when the function is a cast
                            if (isTypeCast || WebConvert.TryRemoveQuotes(ref text))
                            {
                                ResourceType resourceType = this.tryResolveResourceType(text);
                                if (resourceType != null)
                                {
                                    if (target == typeof(Type))
                                    {
                                        if (resourceType.CanReflectOnInstanceType)
                                        {
                                            value = resourceType.InstanceType;
                                        }
                                    }
                                    else
                                    {
                                        if (resourceType.CanReflectOnInstanceType == false)
                                        {
                                            value = resourceType;
                                        }
                                    }
                                }
                            }
                        }
                        else if ((type == typeof(DateTime) || type == typeof(DateTime?)) &&
                                 (expr.Type == typeof(DateTimeOffset) || expr.Type == typeof(DateTimeOffset?)))
                        {
                            // Since the URI parser in ODataLib will always convert Constants as DateTimeOffset,
                            // and WCF DS Server supports DateTime clr type, we need to do the conversion whenever required.
                            value = WebUtil.ConvertDateTimeOffsetToDateTime((DateTimeOffset)ce.Value);
                        }
                        else
                        {
                            switch (Type.GetTypeCode(ce.Type))
                            {
                            case TypeCode.Int32:
                            case TypeCode.Int64:
                                value = ParseNumber(text, target);
                                break;

                            case TypeCode.Double:
                                if (target == typeof(decimal))
                                {
                                    value = ParseNumber(text, target);
                                }

                                break;
                            }
                        }

                        if (value != null)
                        {
                            return(Expression.Constant(value, type));
                        }
                    }
                }
            }

            if (IsCompatibleWith(expr.Type, type))
            {
                // (type != typeof(object) || expr.Type.IsValueType) part is added
                // to prevent cast to System.Object from non-value types (objects).
                if (type.IsValueType || exact && (type != typeof(object) || expr.Type.IsValueType))
                {
                    return(Expression.Convert(expr, type));
                }

                return(expr);
            }

            // Allow promotion from nullable to non-nullable by directly accessing underlying value.
            if (WebUtil.IsNullableType(expr.Type) && type.IsValueType)
            {
                Expression valueAccessExpression = Expression.Property(expr, "Value");
                valueAccessExpression = this.PromoteExpression(valueAccessExpression, type, exact, isTypeCast);
                return(valueAccessExpression);
            }

            return(null);
        }