Newtonsoft.Json.Linq.JToken.ToObject()

Here are the examples of the csharp api Newtonsoft.Json.Linq.JToken.ToObject() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

582 Examples 7

19 Source : DynamicJsonResponse.cs
with Apache License 2.0
from Autodesk-Forge

internal void _ArrayDetection (ref JContainer obj) {
			bool bArray =true ;
			foreach ( JProperty prop in (obj as JObject).Properties () ) {
				int val =0 ;
				if ( Int32.TryParse (prop.Name, out val) != true ) {
					bArray =false ;
					break ;
				}
			}
			if ( bArray == true ) {
				JArray jarr =new JArray () ;
				foreach ( JProperty item in obj )
					jarr.Add (item.Value) ;
				obj =jarr ;
			}
			int nb =obj.Count ;
			for ( int i =0 ; i < nb ; i++ ) {
				JObject sub =null ;
				JProperty prop =obj.ElementAtOrDefault (i) as JProperty ;
				if ( prop != null ) {
					if ( prop.Value.GetType () == typeof (JObject) )
						sub =prop.Value.ToObject<JObject> () ;
				} else {
					sub =obj.ElementAtOrDefault (i) as JObject ;
				}
				if ( sub != null ) {
					JContainer container =sub as JContainer ;
					_ArrayDetection (ref container) ;
					if ( prop != null )
						prop.Value.Replace (container) ;
					else
						sub.Replace (container) ;
				}
			}
		}

19 Source : EMFPipe.cs
with Apache License 2.0
from awslabs

public override void OnNext(IEnvelope<T> value)
        {
            var jo = new JObject();

            if (value.Data is IEnumerable<KeyValuePair<string, string>> dic)
            {
                foreach (var kvp in dic.Where(i => KeyIsNotReservedProperty(i.Key)))
                    jo[CleanKeyName(kvp.Key)] = kvp.Value;
            }
            else if (value.Data is IEnumerable<KeyValuePair<string, JToken>> jt)
            {
                foreach (var kvp in jt.Where(i => KeyIsNotReservedProperty(i.Key)))
                    jo[CleanKeyName(kvp.Key)] = kvp.Value;
            }
            else
            {
                _context.Logger.LogWarning("{0} only supports sources that output a type that inherits from IEnumerable<KeyValuePair<string, string>> or IEnumerable<KeyValuePair<string, JToken>>", nameof(EMFPipe<T>));
                return;
            }

            foreach (var m in _metric.Metrics)
            {
                if (jo.TryGetValue(m.Name, StringComparison.CurrentCultureIgnoreCase, out JToken mVal))
                {
                    // The metric property MUST be a numeric, so if it has been parsed as a string,
                    // we need to convert it to a double so that CW can convert it properly.
                    if (mVal.Type == JTokenType.String && double.TryParse(mVal.ToObject<string>(), out double val))
                    {
                        jo.Remove(m.Name);
                        jo[m.Name] = val;
                    }

                    continue;
                }

                // If the object doesn't have the property specified in the MetricName, use a default value.
                jo[m.Name] = m.Value ?? 1;
            }

            // Conform with the latest spec: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
            var joEMF = new JObject();
            joEMF["Timestamp"] = Utility.ToEpochMilliseconds(value.Timestamp);
            joEMF["CloudWatchMetrics"] = _jArray;
            jo["_aws"] = joEMF;

            _subject.OnNext(new Envelope<JObject>(jo, value.Timestamp, value.BookmarkData, value.Position));
        }

19 Source : CompilerHostController.cs
with MIT License
from Azure

private static Dictionary<string, string> TryExtract(JToken jsonBody, string key)
        {
            try
            {
                return jsonBody[key].ToObject<Dictionary<string, string>>();
            }
            catch (Exception)
            {
                return null;
            }
        }

19 Source : GeoMasterDataProvider.cs
with MIT License
from Azure

public async Task<IDictionary<string, string[]>> GetStickySlotSettingNames(string subscriptionId, string resourceGroupName, string name)
        {
            string path = SitePathUtility.GetSitePath(subscriptionId, resourceGroupName, name);
            path = path + "/config/slotConfigNames";
            GeoMasterResponse geoMasterResponse = null;
            geoMasterResponse = await HttpGet<GeoMasterResponse>(path);
            Dictionary<string, string[]> stickyToSlotSettings = new Dictionary<string, string[]>();
            foreach (var item in geoMasterResponse.Properties)
            {
                var val = new string[0];
                if (item.Value != null && item.Value is Newtonsoft.Json.Linq.JArray)
                {
                    var jArray = (Newtonsoft.Json.Linq.JArray)item.Value;
                    val = jArray.ToObject<string[]>();
                }
                stickyToSlotSettings.Add(item.Key, val);
            }
            return stickyToSlotSettings;
        }

19 Source : HostingEnvironmentController.cs
with MIT License
from Azure

private async Task<DiagnosticStampData> GetHostingEnvironmentPostBody(string hostingEnvironmentName)
        {
            var dataProviders = new DataProviders.DataProviders((DataProviderContext)HttpContext.Items[HostConstants.DataProviderContextKey]);
            dynamic postBody = await dataProviders.Observer.GetHostingEnvironmentPostBody(hostingEnvironmentName);
            JObject bodyObject = (JObject)postBody;
            return bodyObject.ToObject<DiagnosticStampData>();
        }

19 Source : SitesController.cs
with MIT License
from Azure

private async Task<DiagnosticSiteData> GetSitePostBody(string subscriptionId, string resourceGroupName, string siteName)
        {
            var dataProviders = new DataProviders.DataProviders((DataProviderContext)HttpContext.Items[HostConstants.DataProviderContextKey]);
            string stampName = await dataProviders.Observer.GetStampName(subscriptionId, resourceGroupName, siteName);
            dynamic postBody = await dataProviders.Observer.GetSitePostBody(stampName, siteName);
            JObject bodyObject = (JObject)postBody;
            var sitePostBody = bodyObject.ToObject<DiagnosticSiteData>();
            return sitePostBody;
        }

19 Source : KustoDeserializationTests.cs
with MIT License
from Azure

[Fact]
        public void TestKustoDataTableConverter()
        {
            var dt = new DataTable();

            // When arrays or objects come from kusto they have column type 'object'
            // and come as types JArray and JObject respectively

            dt.Columns.Add("String", typeof(string));
            dt.Columns.Add("Array", typeof(object));
            dt.Columns.Add("Object", typeof(object));

            var arr = new JArray(new string[] { "test" });
            var obj = JObject.FromObject(new { Test = "Test" });

            dt.Rows.Add("test", arr, obj);

            var table = dt.ToDataTableResponseObject();

            var serialized = JsonConvert.SerializeObject(table);

            var deserialized = JsonConvert.DeserializeObject<DataTableResponseObject>(serialized);

            var dataTable = deserialized.ToDataTable();

            replacedert.Equal(dt.Rows[0][0].ToString(), dataTable.Rows[0][0].ToString());

            replacedert.Equal(((JArray)dt.Rows[0][1]).ToObject<string[]>(), ((JArray)dataTable.Rows[0][1]).ToObject<string[]>());

            replacedert.Equal(dt.Rows[0][2], dataTable.Rows[0][2]);
        }

19 Source : CosmosExceptionFactory.cs
with MIT License
from Azure

internal static (Error, string) GetErrorFromStream(
            Stream content)
        {
            using (content)
            {
                if (content != null
               && content.CanRead)
                {
                    using (StreamReader streamReader = new StreamReader(content))
                    {
                        string errorContent = streamReader.ReadToEnd();
                        try
                        {
                            JObject errorObj = JObject.Parse(errorContent);
                            Error error = errorObj.ToObject<Error>();
                            if (error != null)
                            {
                                StringBuilder message = new StringBuilder();
                                foreach (var err in errorObj)
                                {
                                    message
                                        .Append(Environment.NewLine)
                                        .Append(err.Key)
                                        .Append(" : ")
                                        .Append(err.Value);
                                }
                                message.Append(Environment.NewLine);
                                // Error format is not consistent across modes
                                return (error, message.ToString());
                            }
                        }
                        catch (Newtonsoft.Json.JsonReaderException)
                        {
                        }

                        // Content is not Json
                        content.Position = 0;
                        return (null, errorContent);
                    }
                }

                return (null, null);
            }
        }

19 Source : DocumentAnalyzer.cs
with MIT License
from Azure

internal static ParreplacedionKeyInternal ExtractParreplacedionKeyValue<T>(T data, ParreplacedionKeyDefinition parreplacedionKeyDefinition, Func<T, JToken> convertToJToken)
        {
            return ParreplacedionKeyInternal.FromObjectArray(
                parreplacedionKeyDefinition.Paths.Select(path =>
                {
                    IReadOnlyList<string> parts = PathParser.GetPathParts(path);
                    Debug.replacedert(parts.Count >= 1, "Parreplacedion key component definition path is invalid.");

                    JToken token = convertToJToken(data);

                    foreach (string part in parts)
                    {
                        if (token == null)
                        {
                            break;
                        }

                        token = token[part];
                    }

                    return token != null ? token.ToObject<object>() : Undefined.Value;
                }).ToArray(),
                false);
        }

19 Source : ContractTests.cs
with MIT License
from Azure

[TestMethod]
        public async Task ItemStreamContractVerifier()
        {
            string ParreplacedionKey = "/pk";
            Container container = await this.database.CreateContainerAsync(
                new ContainerProperties(id: Guid.NewGuid().ToString(), parreplacedionKeyPath: ParreplacedionKey),
                cancellationToken: this.cancellationToken);

            int totalCount = 4;
            Dictionary<string, ToDoActivity> toDoActivities = new Dictionary<string, ToDoActivity>();
            // Create 3 constant items;
            for (int i = 0; i < totalCount; i++)
            {
                ToDoActivity toDoActivity = new ToDoActivity()
                {
                    id = "toDoActivity" + i,
                    status = "InProgress",
                    cost = 9000 + i,
                    description = "Constant to do activity",
                    taskNum = i
                };

                toDoActivities.Add(toDoActivity.id, toDoActivity);

                await container.CreateItemAsync<ToDoActivity>(toDoActivity);
            }

            List<FeedIterator> FeedIterators = new List<FeedIterator>();

            // The stream contract should return the same contract as read feed.
            // {
            //    "_rid": "containerRid",
            //    "Doreplacedents": [{
            //        "id": "03230",
            //        "_rid": "qHVdAImeKAQBAAAAAAAAAA==",
            //        "_self": "dbs\/qHVdAA==\/colls\/qHVdAImeKAQ=\/docs\/qHVdAImeKAQBAAAAAAAAAA==\/",
            //        "_etag": "\"410000b0-0000-0000-0000-597916b00000\"",
            //        "_attachments": "attachments\/",
            //        "_ts": 1501107886
            //    }],
            //    "_count": 1
            // }

            FeedIterator sereplacederator =
                container.GereplacedemQueryStreamIterator();
            FeedIterators.Add(sereplacederator);

            QueryRequestOptions options = new QueryRequestOptions()
            {
                MaxItemCount = 4,
                MaxConcurrency = 1,
            };

            FeedIterator queryIterator = container.GereplacedemQueryStreamIterator(
                    queryText: @"select * from t where t.id != """" ",
                    requestOptions: options);

            FeedIterators.Add(queryIterator);
            foreach (FeedIterator iterator in FeedIterators)
            {
                int count = 0;
                while (iterator.HasMoreResults)
                {
                    ResponseMessage response = await iterator.ReadNextAsync(this.cancellationToken);
                    response.EnsureSuccessStatusCode();

                    using (StreamReader sr = new StreamReader(response.Content))
                    {
                        string jsonString = await sr.ReadToEndAsync();
                        replacedert.IsNotNull(jsonString);
                        JObject jObject = JsonConvert.DeserializeObject<JObject>(jsonString);
                        replacedert.IsNotNull(jObject["Doreplacedents"]);
                        replacedert.IsNotNull(jObject["_rid"]);
                        replacedert.IsNotNull(jObject["_count"]);
                        replacedert.IsTrue(jObject["_count"].ToObject<int>() >= 0);
                        foreach (JObject item in jObject["Doreplacedents"])
                        {
                            count++;
                            replacedert.IsNotNull(item["id"]);
                            ToDoActivity createdItem = toDoActivities[item["id"].ToString()];

                            replacedert.AreEqual(createdItem.taskNum, item["taskNum"].ToObject<int>());
                            replacedert.AreEqual(createdItem.cost, item["cost"].ToObject<double>());
                            replacedert.AreEqual(createdItem.description, item["description"].ToString());
                            replacedert.AreEqual(createdItem.status, item["status"].ToString());
                            replacedert.IsNotNull(item["_rid"]);
                            replacedert.IsNotNull(item["_self"]);
                            replacedert.IsNotNull(item["_etag"]);
                            replacedert.IsNotNull(item["_attachments"]);
                            replacedert.IsNotNull(item["_ts"]);
                        }
                    }
                }

                replacedert.AreEqual(totalCount, count);
            }
        }

19 Source : CosmosDatabaseTests.cs
with MIT License
from Azure

[TestMethod]
        public async Task DatabaseQueryIterator()
        {
            List<Cosmos.Database> deleteList = new List<Cosmos.Database>();
            try
            {
                string firstDb = "Abcdefg";
                string secondDb = "Bcdefgh";
                string thirdDb = "Zoo";

                DatabaseResponse createResponse2 = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(secondDb);
                deleteList.Add(createResponse2.Database);
                DatabaseResponse createResponse = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(firstDb);
                deleteList.Add(createResponse.Database);
                DatabaseResponse createResponse3 = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(thirdDb);
                deleteList.Add(createResponse3.Database);

                using (FeedIterator<DatabaseProperties> feedIterator =
                   this.cosmosClient.GetDatabaseQueryIterator<DatabaseProperties>(
                       new QueryDefinition("select c.id From c where c.id = @id ")
                       .WithParameter("@id", createResponse.Database.Id),
                       requestOptions: new QueryRequestOptions() { MaxItemCount = 1 }))
                {
                    FeedResponse<DatabaseProperties> iterator = await feedIterator.ReadNextAsync(this.cancellationToken);
                    replacedert.AreEqual(1, iterator.Resource.Count());
                    replacedert.AreEqual(firstDb, iterator.First().Id);

                    replacedert.IsFalse(feedIterator.HasMoreResults);
                }

                using (FeedIterator feedIterator =
                    this.cosmosClient.GetDatabaseQueryStreamIterator(
                        "select value c.id From c "))
                {
                    while (feedIterator.HasMoreResults)
                    {
                        using (ResponseMessage response = await feedIterator.ReadNextAsync(this.cancellationToken))
                        {
                            response.EnsureSuccessStatusCode();
                            using(StreamReader streamReader = new StreamReader(response.Content))
                            using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
                            {
                                // Output will be:
                                // { "_rid":"","Databases":["Zoo","Abcdefg","Bcdefgh"],"_count":3}
                                JObject jObject = await JObject.LoadAsync(jsonTextReader);
                                replacedert.IsNotNull(jObject["_rid"].ToString());
                                replacedert.IsTrue(jObject["Databases"].ToObject<JArray>().Count > 0);
                                replacedert.IsTrue(jObject["_count"].ToObject<int>() > 0);
                            }
                        }
                    }
                }

                List<string> ids = new List<string>();
                using (FeedIterator<string> feedIterator =
                    this.cosmosClient.GetDatabaseQueryIterator<string>(
                        "select value c.id From c "))
                {
                    while (feedIterator.HasMoreResults)
                    {
                        FeedResponse<string> iterator = await feedIterator.ReadNextAsync(this.cancellationToken);
                        ids.AddRange(iterator);
                    }
                }
                
                replacedert.IsTrue(ids.Count >= 2);
            }
            finally
            {
                foreach (Cosmos.Database database in deleteList)
                {
                    await database.DeleteAsync(cancellationToken: this.cancellationToken);
                }
            }
        }

19 Source : JTokenToSqlScalarExpression.cs
with MIT License
from Azure

public static SqlScalarExpression Convert(JToken token)
        {
            if (token == null)
            {
                return Undefined;
            }

            switch (token.Type)
            {
                case JTokenType.Array:
                    {
                        List<SqlScalarExpression> items = new List<SqlScalarExpression>();
                        foreach (JToken element in token)
                        {
                            items.Add(JTokenToSqlScalarExpression.Convert(element));
                        }

                        return SqlArrayCreateScalarExpression.Create(items.ToArray());
                    }

                case JTokenType.Boolean:
                    {
                        SqlBooleanLiteral literal = SqlBooleanLiteral.Create(token.ToObject<bool>());
                        return SqlLiteralScalarExpression.Create(literal);
                    }

                case JTokenType.Null:
                    {
                        SqlNullLiteral literal = SqlNullLiteral.Singleton;
                        return SqlLiteralScalarExpression.Create(literal);
                    }

                case JTokenType.Integer:
                case JTokenType.Float:
                    {
                        SqlNumberLiteral literal = SqlNumberLiteral.Create(token.ToObject<double>());
                        return SqlLiteralScalarExpression.Create(literal);
                    }

                case JTokenType.Object:
                    {
                        List<SqlObjectProperty> properties = new List<SqlObjectProperty>();

                        foreach (JProperty prop in (JToken)token)
                        {
                            SqlPropertyName name = SqlPropertyName.Create(prop.Name);
                            JToken value = prop.Value;
                            SqlScalarExpression expression = JTokenToSqlScalarExpression.Convert(value);
                            SqlObjectProperty property = SqlObjectProperty.Create(name, expression);
                            properties.Add(property);
                        }

                        return SqlObjectCreateScalarExpression.Create(properties.ToArray());
                    }

                case JTokenType.String:
                    {
                        SqlStringLiteral literal = SqlStringLiteral.Create(token.ToObject<string>());
                        return SqlLiteralScalarExpression.Create(literal);
                    }

                default:
                    throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, "Unsupported JsonType {0}", token.Type));
            }
        }

19 Source : TraceTests.cs
with MIT License
from Azure

[TestMethod]
        [Timeout(5000)]
        public void ValidateStoreResultSerialization()
        {
            HashSet<string> storeResultProperties = typeof(StoreResult).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.Name).ToHashSet<string>();
            string datumKey = "ClientStats";
            Trace trace = Trace.GetRootTrace("Test");
            ClientSideRequestStatisticsTraceDatum datum = new ClientSideRequestStatisticsTraceDatum(DateTime.UtcNow);
            trace.AddDatum(datumKey, datum);

            StoreResult storeResult = new StoreResult(
                storeResponse: new StoreResponse(),
                exception: null,
                parreplacedionKeyRangeId: 42.ToString(),
                lsn: 1337,
                quorumAckedLsn: 23,
                requestCharge: 3.14,
                currentReplicaSetSize: 4,
                currentWriteQuorum: 3,
                isValid: true,
                storePhysicalAddress: new Uri("http://storephysicaladdress.com"),
                globalCommittedLSN: 1234,
                numberOfReadRegions: 13,
                itemLSN: 15,
                sessionToken: new SimpleSessionToken(42),
                usingLocalLSN: true,
                activityId: Guid.Empty.ToString(),
                backendRequestDurationInMs: "4.2",
                retryAfterInMs: "42",
                transportRequestStats: TraceWriterBaselineTests.CreateTransportRequestStats());

            StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(
                            DateTime.MinValue,
                            DateTime.MaxValue,
                            storeResult,
                            ResourceType.Doreplacedent,
                            OperationType.Query,
                            new Uri("http://someUri1.com"));

            ((List<StoreResponseStatistics>)datum.GetType().GetField("storeResponseStatistics", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(datum)).Add(storeResponseStatistics);

            CosmosTraceDiagnostics diagnostics = new CosmosTraceDiagnostics(trace);
            string json = diagnostics.ToString();
            JObject jObject = JObject.Parse(json);
            JObject storeResultJObject = jObject["data"][datumKey]["StoreResponseStatistics"][0]["StoreResult"].ToObject<JObject>();
            List<string> jsonPropertyNames = storeResultJObject.Properties().Select(p => p.Name).ToList();

            storeResultProperties.Add("BELatencyInMs");
            storeResultProperties.Remove(nameof(storeResult.BackendRequestDurationInMs));
            storeResultProperties.Add("TransportException");
            storeResultProperties.Remove(nameof(storeResult.Exception));
            storeResultProperties.Add("transportRequestTimeline");
            storeResultProperties.Remove(nameof(storeResult.TransportRequestStats));

            foreach (string key in jsonPropertyNames)
            {
                replacedert.IsTrue(storeResultProperties.Remove(key), $"Json contains key:{key} not a storeresult property");
            }

            replacedert.AreEqual(0, storeResultProperties.Count, $"Json is missing properties: {string.Join(';', storeResultProperties)}");
        }

19 Source : EncryptionProcessor.cs
with MIT License
from Azure

private static (TypeMarker, byte[]) Serialize(JToken propertyValue)
        {
            return propertyValue.Type switch
            {
                JTokenType.Boolean => (TypeMarker.Boolean, SqlSerializerFactory.GetDefaultSerializer<bool>().Serialize(propertyValue.ToObject<bool>())),
                JTokenType.Float => (TypeMarker.Double, SqlSerializerFactory.GetDefaultSerializer<double>().Serialize(propertyValue.ToObject<double>())),
                JTokenType.Integer => (TypeMarker.Long, SqlSerializerFactory.GetDefaultSerializer<long>().Serialize(propertyValue.ToObject<long>())),
                JTokenType.String => (TypeMarker.String, SqlVarcharSerializer.Serialize(propertyValue.ToObject<string>())),
                _ => throw new InvalidOperationException($"Invalid or Unsupported Data Type Preplaceded : {propertyValue.Type}. "),
            };

19 Source : EncryptionContainer.cs
with MIT License
from Azure

private async Task<List<T>> DecryptChangeFeedDoreplacedentsAsync<T>(
            IReadOnlyCollection<JObject> doreplacedents,
            CancellationToken cancellationToken)
        {
            List<T> decrypreplacedems = new List<T>(doreplacedents.Count);
            if (typeof(T) == typeof(DecryptableItem))
            {
                foreach (JToken value in doreplacedents)
                {
                    DecryptableItemCore item = new DecryptableItemCore(
                        value,
                        this.Encryptor,
                        this.CosmosSerializer);

                    decrypreplacedems.Add((T)(object)item);
                }
            }
            else
            {
                foreach (JObject doreplacedent in doreplacedents)
                {
                    CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(null);
                    using (diagnosticsContext.CreateScope("DecryptChangeFeedDoreplacedentsAsync<"))
                    {
                        (JObject decryptedDoreplacedent, DecryptionContext _) = await EncryptionProcessor.DecryptAsync(
                            doreplacedent,
                            this.Encryptor,
                            diagnosticsContext,
                            cancellationToken);

                        decrypreplacedems.Add(decryptedDoreplacedent.ToObject<T>());
                    }
                }
            }

            return decrypreplacedems;
        }

19 Source : EncryptionProcessor.cs
with MIT License
from Azure

public static async Task<(Stream, DecryptionContext)> DecryptAsync(
            Stream input,
            Encryptor encryptor,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            if (input == null)
            {
                return (input, null);
            }

            Debug.replacedert(input.CanSeek);
            Debug.replacedert(encryptor != null);
            Debug.replacedert(diagnosticsContext != null);

            JObject itemJObj = EncryptionProcessor.RetrieveItem(input);
            JObject encryptionPropertiesJObj = EncryptionProcessor.RetrieveEncryptionProperties(itemJObj);

            if (encryptionPropertiesJObj == null)
            {
                input.Position = 0;
                return (input, null);
            }

            EncryptionProperties encryptionProperties = encryptionPropertiesJObj.ToObject<EncryptionProperties>();
            DecryptionContext decryptionContext = encryptionProperties.EncryptionAlgorithm switch
            {
                CosmosEncryptionAlgorithm.MdeAeadAes256CbcHmac256Randomized => await EncryptionProcessor.MdeEncAlgoDecryptObjectAsync(
                    itemJObj,
                    encryptor,
                    encryptionProperties,
                    diagnosticsContext,
                    cancellationToken),
                CosmosEncryptionAlgorithm.AEAes256CbcHmacSha256Randomized => await EncryptionProcessor.LegacyEncAlgoDecryptContentAsync(
                    itemJObj,
                    encryptionProperties,
                    encryptor,
                    diagnosticsContext,
                    cancellationToken),
                _ => throw new NotSupportedException($"Encryption Algorithm : {encryptionProperties.EncryptionAlgorithm} is not supported."),
            };

19 Source : EncryptionProcessor.cs
with MIT License
from Azure

public static async Task<(JObject, DecryptionContext)> DecryptAsync(
            JObject doreplacedent,
            Encryptor encryptor,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            Debug.replacedert(doreplacedent != null);

            Debug.replacedert(encryptor != null);

            JObject encryptionPropertiesJObj = EncryptionProcessor.RetrieveEncryptionProperties(doreplacedent);

            if (encryptionPropertiesJObj == null)
            {
                return (doreplacedent, null);
            }

            EncryptionProperties encryptionProperties = encryptionPropertiesJObj.ToObject<EncryptionProperties>();
            DecryptionContext decryptionContext = encryptionProperties.EncryptionAlgorithm switch
            {
                CosmosEncryptionAlgorithm.MdeAeadAes256CbcHmac256Randomized => await EncryptionProcessor.MdeEncAlgoDecryptObjectAsync(
                    doreplacedent,
                    encryptor,
                    encryptionProperties,
                    diagnosticsContext,
                    cancellationToken),
                CosmosEncryptionAlgorithm.AEAes256CbcHmacSha256Randomized => await EncryptionProcessor.LegacyEncAlgoDecryptContentAsync(
                    doreplacedent,
                    encryptionProperties,
                    encryptor,
                    diagnosticsContext,
                    cancellationToken),
                _ => throw new NotSupportedException($"Encryption Algorithm : {encryptionProperties.EncryptionAlgorithm} is not supported."),
            };

19 Source : LegacyEncryptionProcessorTests.cs
with MIT License
from Azure

private static async Task<JObject> VerifyEncryptionSucceeded(TestDoc testDoc)
        {
            Stream encryptedStream = await EncryptionProcessor.EncryptAsync(
                testDoc.ToStream(),
                LegacyEncryptionProcessorTests.mockEncryptor.Object,
                LegacyEncryptionProcessorTests.encryptionOptions,
                new CosmosDiagnosticsContext(),
                CancellationToken.None);

            JObject encryptedDoc = EncryptionProcessor.BaseSerializer.FromStream<JObject>(encryptedStream);
            
            replacedert.AreEqual(testDoc.Id, encryptedDoc.Property("id").Value.Value<string>());
            replacedert.AreEqual(testDoc.PK, encryptedDoc.Property(nameof(TestDoc.PK)).Value.Value<string>());
            replacedert.AreEqual(testDoc.NonSensitive, encryptedDoc.Property(nameof(TestDoc.NonSensitive)).Value.Value<string>());
            replacedert.IsNull(encryptedDoc.Property(nameof(TestDoc.SensitiveStr)));
            replacedert.IsNull(encryptedDoc.Property(nameof(TestDoc.SensitiveInt)));

            JProperty eiJProp = encryptedDoc.Property(Constants.EncryptedInfo);
            replacedert.IsNotNull(eiJProp);
            replacedert.IsNotNull(eiJProp.Value);
            replacedert.AreEqual(JTokenType.Object, eiJProp.Value.Type);
            EncryptionProperties encryptionProperties = ((JObject)eiJProp.Value).ToObject<EncryptionProperties>();

            replacedert.IsNotNull(encryptionProperties);
            replacedert.AreEqual(LegacyEncryptionProcessorTests.dekId, encryptionProperties.DataEncryptionKeyId);
            replacedert.AreEqual(2, encryptionProperties.EncryptionFormatVersion);
            replacedert.IsNotNull(encryptionProperties.EncryptedData);

            return encryptedDoc;
        }

19 Source : MdeEncryptionProcessorTests.cs
with MIT License
from Azure

private static async Task<JObject> VerifyEncryptionSucceeded(TestDoc testDoc)
        {
            Stream encryptedStream = await EncryptionProcessor.EncryptAsync(
                 testDoc.ToStream(),
                 MdeEncryptionProcessorTests.mockEncryptor.Object,
                 MdeEncryptionProcessorTests.encryptionOptions,
                 new CosmosDiagnosticsContext(),
                 CancellationToken.None);

            JObject encryptedDoc = EncryptionProcessor.BaseSerializer.FromStream<JObject>(encryptedStream);

            replacedert.AreEqual(testDoc.Id, encryptedDoc.Property("id").Value.Value<string>());
            replacedert.AreEqual(testDoc.PK, encryptedDoc.Property(nameof(TestDoc.PK)).Value.Value<string>());
            replacedert.AreEqual(testDoc.NonSensitive, encryptedDoc.Property(nameof(TestDoc.NonSensitive)).Value.Value<string>());
            replacedert.IsNotNull(encryptedDoc.Property(nameof(TestDoc.SensitiveInt)).Value.Value<string>());
            replacedert.AreNotEqual(testDoc.SensitiveInt, encryptedDoc.Property(nameof(TestDoc.SensitiveInt)).Value.Value<string>()); // not equal since value is encrypted

            JProperty eiJProp = encryptedDoc.Property(Constants.EncryptedInfo);
            replacedert.IsNotNull(eiJProp);
            replacedert.IsNotNull(eiJProp.Value);
            replacedert.AreEqual(JTokenType.Object, eiJProp.Value.Type);
            EncryptionProperties encryptionProperties = ((JObject)eiJProp.Value).ToObject<EncryptionProperties>();

            replacedert.IsNotNull(encryptionProperties);
            replacedert.AreEqual(MdeEncryptionProcessorTests.dekId, encryptionProperties.DataEncryptionKeyId);
            replacedert.AreEqual(3, encryptionProperties.EncryptionFormatVersion);
            replacedert.IsNull(encryptionProperties.EncryptedData);
            replacedert.IsNotNull(encryptionProperties.EncryptedPaths);

            if (testDoc.SensitiveStr == null)
            {
                replacedert.IsNull(encryptedDoc.Property(nameof(TestDoc.SensitiveStr)).Value.Value<string>()); // since null value is not encrypted
                replacedert.AreEqual(TestDoc.PathsToEncrypt.Count - 1, encryptionProperties.EncryptedPaths.Count());
            }
            else
            {
                replacedert.IsNotNull(encryptedDoc.Property(nameof(TestDoc.SensitiveStr)).Value.Value<string>());
                replacedert.AreNotEqual(testDoc.SensitiveStr, encryptedDoc.Property(nameof(TestDoc.SensitiveStr)).Value.Value<string>()); // not equal since value is encrypted
                replacedert.AreEqual(TestDoc.PathsToEncrypt.Count, encryptionProperties.EncryptedPaths.Count());
            }

            return encryptedDoc;
        }

19 Source : LibraryConverter.cs
with MIT License
from Azure

public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            JObject library = JObject.Load(reader);

            if (library.ContainsKey("jar"))
            {
                return library.ToObject<JarLibrary>();
            }

            if (library.ContainsKey("egg"))
            {
                return library.ToObject<EggLibrary>();
            }

            if (library.ContainsKey("whl"))
            {
                return library.ToObject<WheelLibrary>();
            }

            if (library.ContainsKey("maven"))
            {
                return library.ToObject<MavenLibrary>();
            }

            if (library.ContainsKey("pypi"))
            {
                return library.ToObject<PythonPyPiLibrary>();
            }

            if (library.ContainsKey("cran"))
            {
                return library.ToObject<RCranLibrary>();
            }

            throw new NotSupportedException("Library not recognized");
        }

19 Source : SecretScopeConverter.cs
with MIT License
from Azure

public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            var scope = JObject.Load(reader);

            var backendType = scope["backend_type"].ToObject<ScopeBackendType>();
            switch (backendType)
            {
                case ScopeBackendType.DATABRICKS:
                    return scope.ToObject<DatabricksSecretScope>();
                case ScopeBackendType.AZURE_KEYVAULT:
                    return scope.ToObject<AzureKeyVaultSecretScope>();
                default:
                    throw new NotSupportedException("SecretScope backend type not recognized: " + backendType);
            }
        }

19 Source : FunctionMetadataJsonReader.cs
with MIT License
from Azure

public virtual async Task<ImmutableArray<FunctionMetadata>> ReadMetadataAsync()
        {
            string metadataFile = Path.Combine(_options.Value.FunctionMetadataFileDrectory, FileName);

            if (File.Exists(metadataFile))
            {
                using (var fs = File.OpenText(metadataFile))
                {
                    using (var js = new JsonTextReader(fs))
                    {
                        JArray functionMetadataJson = (JArray)await JToken.ReadFromAsync(js);

                        var functionList = new List<FunctionMetadata>();

                        foreach (JObject function in functionMetadataJson)
                        {
                            FunctionMetadata metadata = function.ToObject<FunctionMetadata>();

                            // We need to re-add these by going through the BindingMetadata factory
                            metadata.Bindings.Clear();

                            JArray bindingArray = (JArray)function["bindings"];
                            if (bindingArray == null || bindingArray.Count == 0)
                            {
                                throw new FormatException("At least one binding must be declared.");
                            }

                            foreach (JObject binding in bindingArray)
                            {
                                metadata.Bindings.Add(BindingMetadata.Create(binding));
                            }

                            functionList.Add(metadata);
                        }

                        return functionList.ToImmutableArray();
                    }
                }
            }
            else
            {
                return ImmutableArray<FunctionMetadata>.Empty;
            }
        }

19 Source : Startup.cs
with MIT License
from Azure

private static WorkerConfigDescription GetWorkerConfigDescription(string workerConfigPath)
        {
            if (!File.Exists(workerConfigPath))
            {
                throw new FileNotFoundException($"The file '{workerConfigPath}' was not found.");
            }

            WorkerConfigDescription workerDescription;

            using (var fs = File.OpenText(workerConfigPath))
            using (var js = new JsonTextReader(fs))
            {
                JObject workerDescriptionJObject = (JObject)JToken.ReadFrom(js)["description"];
                workerDescription = workerDescriptionJObject.ToObject<WorkerConfigDescription>();

                if (workerDescription is null)
                {
                    throw new InvalidOperationException($"The property 'description' is required in '{workerConfigPath}'.");
                }
            }

            return workerDescription;
        }

19 Source : BindingHelper.cs
with MIT License
from Azure

public StartOrchestrationArgs JObjectToStartOrchestrationArgs(JObject input, DurableClientAttribute attr)
        {
            return input?.ToObject<StartOrchestrationArgs>();
        }

19 Source : EventGridExtensionConfigProvider.cs
with MIT License
from Azure

private async Task<HttpResponseMessage> ProcessAsync(HttpRequestMessage req)
        {
            // webjobs.script uses req.GetQueryNameValuePairs();
            // which requires webapi.core...but this does not work for .netframework2.0
            // TODO change this once webjobs.script is migrated
            var functionName = HttpUtility.ParseQueryString(req.RequestUri.Query)["functionName"];
            if (String.IsNullOrEmpty(functionName) || !_listeners.ContainsKey(functionName))
            {
                _logger.LogInformation($"cannot find function: '{functionName}', available function names: [{string.Join(", ", _listeners.Keys.ToArray())}]");
                return new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent($"cannot find function: '{functionName}'") };
            }

            IEnumerable<string> eventTypeHeaders = null;
            string eventTypeHeader = null;
            if (req.Headers.TryGetValues("aeg-event-type", out eventTypeHeaders))
            {
                eventTypeHeader = eventTypeHeaders.First();
            }

            if (String.Equals(eventTypeHeader, "SubscriptionValidation", StringComparison.OrdinalIgnoreCase))
            {
                string jsonArray = await req.Content.ReadreplacedtringAsync();
                SubscriptionValidationEvent validationEvent = null;
                List<JObject> events = JsonConvert.DeserializeObject<List<JObject>>(jsonArray);
                // TODO remove unnecessary serialization
                validationEvent = ((JObject)events[0]["data"]).ToObject<SubscriptionValidationEvent>();
                SubscriptionValidationResponse validationResponse = new SubscriptionValidationResponse { ValidationResponse = validationEvent.ValidationCode };
                var returnMessage = new HttpResponseMessage(HttpStatusCode.OK);
                returnMessage.Content = new StringContent(JsonConvert.SerializeObject(validationResponse));
                _logger.LogInformation($"perform handshake with eventGrid for function: {functionName}");
                return returnMessage;
            }
            else if (String.Equals(eventTypeHeader, "Notification", StringComparison.OrdinalIgnoreCase))
            {
                JArray events = null;
                string requestContent = await req.Content.ReadreplacedtringAsync();
                var token = JToken.Parse(requestContent);
                if (token.Type == JTokenType.Array)
                {
                    // eventgrid schema
                    events = (JArray)token;
                }
                else if (token.Type == JTokenType.Object)
                {
                    // cloudevent schema
                    events = new JArray
                    {
                        token
                    };
                }

                List<Task<FunctionResult>> executions = new List<Task<FunctionResult>>();

                // Single Dispatch
                if (_listeners[functionName].SingleDispatch)
                {
                    foreach (var ev in events)
                    {
                        // replacedume each event is a JObject
                        TriggeredFunctionData triggerData = new TriggeredFunctionData
                        {
                            TriggerValue = ev
                        };
                        executions.Add(_listeners[functionName].Executor.TryExecuteAsync(triggerData, CancellationToken.None));
                    }
                    await Task.WhenAll(executions);
                }
                // Batch Dispatch
                else
                {
                    TriggeredFunctionData triggerData = new TriggeredFunctionData
                    {
                        TriggerValue = events
                    };
                    executions.Add(_listeners[functionName].Executor.TryExecuteAsync(triggerData, CancellationToken.None));
                }

                // FIXME without internal queuing, we are going to process all events in parallel
                // and return 500 if there's at least one failure...which will cause EventGrid to resend the entire payload
                foreach (var execution in executions)
                {
                    if (!execution.Result.Succeeded)
                    {
                        return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(execution.Result.Exception.Message) };
                    }
                }

                return new HttpResponseMessage(HttpStatusCode.Accepted);
            }
            else if (String.Equals(eventTypeHeader, "Unsubscribe", StringComparison.OrdinalIgnoreCase))
            {
                // TODO disable function?
                return new HttpResponseMessage(HttpStatusCode.Accepted);
            }

            return new HttpResponseMessage(HttpStatusCode.BadRequest);

        }

19 Source : EventGridExtensionConfigProvider.cs
with MIT License
from Azure

public T Convert(JToken input)
            {
                return input.ToObject<T>();
            }

19 Source : TestEntityClasses.cs
with MIT License
from Azure

public async Task<int> Get()
            {
                CloudBlockBlob environmentVariableBlob = this.blobContainer.GetBlockBlobReference(this.blobName);
                if (await environmentVariableBlob.ExistsAsync())
                {
                    var readStream = await environmentVariableBlob.OpenReadAsync();
                    using (var reader = new StreamReader(readStream))
                    {
                        string storedValueString = await reader.ReadToEndAsync();
                        int storedValue = JToken.Parse(storedValueString).ToObject<int>();
                        if (this.Value != storedValue)
                        {
                            throw new InvalidOperationException("Local state and blob state do not match.");
                        }

                        return this.Value;
                    }
                }
                else
                {
                    return this.Value;
                }
            }

19 Source : TaskEntityShim.cs
with MIT License
from Azure

private async Task ExecuteOutOfProcBatch()
        {
            object outOfProcResults = null;

            Task invokeTask = this.FunctionInvocationCallback();
            if (invokeTask is Task<object> resultTask)
            {
                outOfProcResults = await resultTask;
            }
            else
            {
                throw new InvalidOperationException("The WebJobs runtime returned a invocation task that does not support return values!");
            }

            var jObj = outOfProcResults as JObject;
            if (jObj == null)
            {
                throw new ArgumentException("Out of proc orchestrators must return a valid JSON schema.");
            }

            var outOfProcResult = jObj.ToObject<OutOfProcResult>();

            // determine what happened to the enreplacedy state
            bool stateWasCreated = !this.context.State.EnreplacedyExists && outOfProcResult.EnreplacedyExists;
            bool stateWasDeleted = this.context.State.EnreplacedyExists && !outOfProcResult.EnreplacedyExists;

            // update the state
            this.context.State.EnreplacedyExists = outOfProcResult.EnreplacedyExists;
            this.context.State.EnreplacedyState = outOfProcResult.EnreplacedyState;

            // emit trace if state was created
            if (stateWasCreated)
            {
                this.Config.TraceHelper.EnreplacedyStateCreated(
                        this.context.HubName,
                        this.context.Name,
                        this.context.InstanceId,
                        "", // operation name left blank because it is a batch
                        "", // operation id left blank because it is a batch
                        isReplay: false);
            }

            // for each operation, emit trace and send response message (if not a signal)
            for (int i = 0; i < this.OperationBatch.Count; i++)
            {
                var request = this.OperationBatch[i];
                var result = outOfProcResult.Results[i];

                if (!result.IsError)
                {
                    this.Config.TraceHelper.OperationCompleted(
                        this.context.HubName,
                        this.context.Name,
                        this.context.InstanceId,
                        request.Id.ToString(),
                        request.Operation,
                        this.Config.GetIntputOutputTrace(request.Input),
                        this.Config.GetIntputOutputTrace(result.Result),
                        result.DurationInMilliseconds,
                        isReplay: false);
                }
                else
                {
                    this.context.CaptureApplicationError(new OperationErrorException(
                        $"Error in operation '{request.Operation}': {result}"));

                    this.Config.TraceHelper.OperationFailed(
                        this.context.HubName,
                        this.context.Name,
                        this.context.InstanceId,
                        request.Id.ToString(),
                        request.Operation,
                        this.Config.GetIntputOutputTrace(request.Input),
                        this.Config.GetIntputOutputTrace(result.Result),
                        result.DurationInMilliseconds,
                        isReplay: false);
                }

                if (!request.IsSignal)
                {
                    var target = new OrchestrationInstance()
                    {
                        InstanceId = request.ParentInstanceId,
                        ExecutionId = request.ParentExecutionId,
                    };
                    var responseMessage = new ResponseMessage()
                    {
                        Result = result.Result,
                        ExceptionType = result.IsError ? "Error" : null,
                    };
                    this.context.SendResponseMessage(target, request.Id, responseMessage, !result.IsError);
                }
            }

            // send signal messages
            foreach (var signal in outOfProcResult.Signals)
            {
                var request = new RequestMessage()
                {
                    ParentInstanceId = this.context.InstanceId,
                    ParentExecutionId = null, // for enreplacedies, message sorter persists across executions
                    Id = Guid.NewGuid(),
                    IsSignal = true,
                    Operation = signal.Name,
                    Input = signal.Input,
                };
                var target = new OrchestrationInstance()
                {
                    InstanceId = EnreplacedyId.GetSchedulerIdFromEnreplacedyId(signal.Target),
                };
                this.context.SendOperationMessage(target, request);
            }

            if (stateWasDeleted)
            {
                this.Config.TraceHelper.EnreplacedyStateDeleted(
                        this.context.HubName,
                        this.context.Name,
                        this.context.InstanceId,
                        "", // operation name left blank because it is a batch
                        "", // operation id left blank because it is a batch
                        isReplay: false);
            }
        }

19 Source : DurableHttpRequest.cs
with MIT License
from Azure

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                var safeTokenSerializer = GetTokenSourceSerializer(serializer);

                JToken json = JToken.ReadFrom(reader);
                if (json.Type == JTokenType.Null)
                {
                    return null;
                }

                JObject jsonObject = (JObject)json;
                if (jsonObject.TryGetValue("kind", out JToken kindValue))
                {
                    if (Enum.TryParse((string)kindValue, out TokenSourceType tokenSourceKind) &&
                        tokenSourceKind == TokenSourceType.AzureManagedIdenreplacedy)
                    {
                        string resourceString = (string)jsonObject.GetValue("resource", StringComparison.Ordinal);

                        if (jsonObject.TryGetValue("options", out JToken optionsToken))
                        {
                            ManagedIdenreplacedyOptions managedIdenreplacedyOptions = optionsToken.ToObject<JObject>().ToObject<ManagedIdenreplacedyOptions>();
                            return new ManagedIdenreplacedyTokenSource(resourceString, managedIdenreplacedyOptions);
                        }

                        return new ManagedIdenreplacedyTokenSource(resourceString);
                    }

                    throw new NotSupportedException($"The token source kind '{kindValue.ToString(Formatting.None)}' is not supported.");
                }
                else if (jsonObject.TryGetValue("$type", StringComparison.Ordinal, out JToken clrTypeValue))
                {
                    Type runtimeType = Type.GetType((string)clrTypeValue, throwOnError: true);
                    return jsonObject.ToObject(runtimeType, safeTokenSerializer);
                }
                else
                {
                    // Don't know how to deserialize this - use default behavior (this may fail)
                    return jsonObject.ToObject(objectType);
                }
            }

19 Source : OutlookConverter.cs
with MIT License
from Azure

private static T GetPropertyValueIgnoreCase<T>(JObject input, string key, bool throwException = true)
        {
            JToken value;
            if (!input.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out value))
            {
                if (throwException)
                {
                    throw new InvalidOperationException($"The object needs to have a {key} field.");
                }
                return default(T);
            }
            return value.ToObject<T>();
        }

19 Source : OutlookConverter.cs
with MIT License
from Azure

public Message Convert(JObject input)
        {
            // Set up recipient(s)
            List<Recipient> recipientList = new List<Recipient>();

            JToken recipientToken = GetPropertyValueIgnoreCase<JToken>(input, "recipient", throwException: false)
                ?? GetPropertyValueIgnoreCase<JToken>(input, "recipients", throwException: false);

            if (recipientToken == null)
            {
                throw new InvalidOperationException("The object needs to have a 'recipient' or 'recipients' field.");
            }

            List<JObject> recipients;

            // MS Graph Message expects a list of recipients
            if (recipientToken is JArray)
            {
                // JArray -> List
                recipients = recipientToken.ToObject<List<JObject>>();
            }
            else
            {
                // List with one JObject
                recipients = new List<JObject>();
                recipients.Add(recipientToken.ToObject<JObject>());
            }

            if (recipients.Count == 0)
            {
                throw new InvalidOperationException("At least one recipient must be provided.");
            }

            foreach (JObject recip in recipients)
            {
                Recipient recipient = new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = GetPropertyValueIgnoreCase<string>(recip, "address"),
                        Name = GetPropertyValueIgnoreCase<string>(recip, "name", throwException: false),
                    },
                };
                recipientList.Add(recipient);
            }

            // Actually create message
            var msg = new Message
            {
                Body = new ItemBody
                {
                    Content = GetPropertyValueIgnoreCase<string>(input, "body"),
                    ContentType = BodyType.Text,
                },
                Subject = GetPropertyValueIgnoreCase<string>(input, "subject"),
                ToRecipients = recipientList,
            };

            return msg;
        }

19 Source : ExcelTests.cs
with MIT License
from Azure

private static bool ValuesEqual(string[] expectedValue, JToken actualValue)
        {
            var allButHeaderRow = ConvertJaggedArrayType(GetAllButHeaderRow());
            var value = actualValue.ToObject<JArray>().ToObject<string[][]>()[0];
            for(int i = 0; i < expectedValue.Length; i++)
            {
                if(expectedValue[i] != value[i])
                {
                    return false;
                }
            }
            return true;
        }

19 Source : ExcelTests.cs
with MIT License
from Azure

private static bool ValuesEqual(string[][] expectedValue, JToken actualValue)
        {
            var allButHeaderRow = ConvertJaggedArrayType(GetAllButHeaderRow());
            var value = actualValue.ToObject<JArray>().ToObject<string[][]>()[0];
            for (int i = 0; i < expectedValue.Length; i++)
            {
                if (expectedValue[0][i] != value[i])
                {
                    return false;
                }
            }
            return true;
        }

19 Source : ExcelTests.cs
with MIT License
from Azure

private static bool JTokenEqualsJaggedArray(JToken token, string[][] rows)
        {
            string[,] stringMultiArray = token.ToObject<JArray>().ToObject<string[,]>();
            int index = 0;
            foreach (var row in rows)
            {
                if (!string.Equals(stringMultiArray[index, 0], row[0]) || !string.Equals(stringMultiArray[index, 1], row[1]))
                {
                    return false;
                }
                index++;
            }
            return true;
        }

19 Source : Functions.cs
with MIT License
from Azure

[FunctionName("onConnection")]
            public static Task EventGridTest([EventGridTrigger]EventGridEvent eventGridEvent,
                [SignalR(HubName = "simplechat")]IAsyncCollector<SignalRMessage> signalRMessages)
            {
                if (eventGridEvent.EventType == "Microsoft.SignalRService.ClientConnectionConnected")
                {
                    var message = ((JObject)eventGridEvent.Data).ToObject<SignalREvent>();

                    return signalRMessages.AddAsync(
                        new SignalRMessage
                        {
                            ConnectionId = message.ConnectionId,
                            Target = "newConnection",
                            Arguments = new[] { new ChatMessage
                            {
                                // ConnectionId is not recommand to send to client directly.
                                // Here's a simple encryption for an easier sample.
                                ConnectionId = GetBase64EncodedString(message.ConnectionId),
                            }}
                        });
                }

                return Task.CompletedTask;
            }

19 Source : V3FormatFeedEntryUpdater.cs
with MIT License
from Azure

public JObject GetUpdatedFeedEntry(JObject feed, CoreToolsInfo coreToolsInfo)
        {
            var feedEntry = feed.ToObject<V3FormatFeedEntry>();

            UpdateCoreToolsReferences(feedEntry, coreToolsInfo);
            UpdateDotnetTemplatesToLatest(feedEntry, coreToolsInfo.MajorVersion);

            Helper.MergeObjectToJToken(feed, feedEntry);

            return feed;
        }

19 Source : V4FormatFeedEntryUpdater.cs
with MIT License
from Azure

public JObject GetUpdatedFeedEntry(JObject feed, CoreToolsInfo coreToolsInfo)
        {
            V4FormatFeedEntry feedEntry = feed.ToObject<V4FormatFeedEntry>();

            UpdateCoreToolsReferences(feedEntry.coreTools, coreToolsInfo.ArtifactsDirectory, coreToolsInfo.Version);
            UpdateDotnetTemplatesToLatest(feedEntry.workerRuntimes, coreToolsInfo.MajorVersion);

            Helper.MergeObjectToJToken(feed, feedEntry);

            return feed;
        }

19 Source : V4FormatFeedEntryUpdater.cs
with MIT License
from Azure

private static void UpdateDotnetTemplatesToLatest(IDictionary<string, IDictionary<string, object>> workerRuntimes, int coreToolsMajor)
        {
            if (!workerRuntimes.TryGetValue("dotnet", out IDictionary<string, object> dotnetInfo))
            {
                throw new Exception("Could not find 'dotnet' worker runtime information in the feed.");
            }

            foreach (KeyValuePair<string, object> keyValInfo in dotnetInfo)
            {
                string dotnetEntryLabel = keyValInfo.Key;
                JObject dotnetEntryToken = keyValInfo.Value as JObject;

                V4FormatDotnetEntry dotnetEntry = dotnetEntryToken?.ToObject<V4FormatDotnetEntry>() ?? throw new Exception($"Cannot parse 'dotnet' object in the feed with label '{dotnetEntryLabel}'");

                if (!_dotnetToTemplatesPrefix.TryGetValue(dotnetEntryLabel, out string templatePrefix))
                {
                    throw new Exception($"Cannot find the template package: Unidentified dotnet label '{dotnetEntryLabel}'.");
                }

                dotnetEntry.itemTemplates = Helper.GetTemplateUrl($"{templatePrefix}.ItemTemplates", coreToolsMajor);
                dotnetEntry.projectTemplates = Helper.GetTemplateUrl($"{templatePrefix}.ProjectTemplates", coreToolsMajor);

                Helper.MergeObjectToJToken(dotnetEntryToken, dotnetEntry);
            }
        }

19 Source : JsonServerlessProtocol.cs
with MIT License
from Azure

private ServerlessMessage SafeParseMessage<T>(JObject jObject) where T : ServerlessMessage
        {
            try
            {
                return jObject.ToObject<T>();
            }
            catch
            {
                return null;
            }
        }

19 Source : VirtualMachineExtensionImpl.cs
with MIT License
from Azure

public async override Task<IVirtualMachineExtension> UpdateAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            this.NullifySettingsIfEmpty();
            if (this.IsReference())
            {
                string extensionName = ResourceUtils.NameFromResourceId(Inner.Id);
                var resource = await Parent.Manager.Inner.VirtualMachineExtensions.GetAsync(
                    this.Parent.ResourceGroupName,
                    this.Parent.Name,
                    extensionName,
                    cancellationToken: cancellationToken);
                Inner.Publisher = resource.Publisher;
                Inner.VirtualMachineExtensionType = resource.VirtualMachineExtensionType;
                if (Inner.AutoUpgradeMinorVersion == null)
                {
                    Inner.AutoUpgradeMinorVersion = resource.AutoUpgradeMinorVersion;
                }
                IDictionary<string, object> existingPublicSettings = null;
                if (resource.Settings != null)
                {
                    if (resource.Settings is JObject)
                    {
                        // NOTE: Unlike Java, In C# the settings can be JObject which needs to be
                        // specially handled. In Java it is an Object that represents Dictionary.
                        //
                        var jObject = (JObject)(resource.Settings);
                        existingPublicSettings = jObject.ToObject<Dictionary<string, object>>();
                    }
                    else
                    {
                        existingPublicSettings = resource.Settings as IDictionary<string, object>;
                    }
                }
                if (existingPublicSettings != null && existingPublicSettings.Count > 0)
                {
                    IDictionary<string, object> newPublicSettings = Inner.Settings as IDictionary<string, object>;
                    if (newPublicSettings == null)
                    {
                        Inner.Settings = new Dictionary<string, object>();
                        newPublicSettings = Inner.Settings as IDictionary<string, object>;
                    }
                    foreach (var setting in existingPublicSettings)
                    {
                        if (!newPublicSettings.ContainsKey(setting.Key))
                        {
                            newPublicSettings.Add(setting.Key, setting.Value);
                        }
                    }
                }
            }
            return await this.CreateAsync(cancellationToken);
        }

19 Source : VirtualMachineExtensionImpl.cs
with MIT License
from Azure

private void InitializeSettings()
        {
            if (Inner.Settings == null)
            {
                this.publicSettings = new Dictionary<string, object>();
            }
            else if (Inner.Settings is JObject)
            {
                // NOTE: Unlike Java, In C# the settings can be JObject which needs to be
                // specially handled. In Java it is an Object that can be based to Dictionary.
                //
                var jObject = (JObject)(Inner.Settings);
                this.publicSettings = jObject.ToObject<Dictionary<string, object>>();
            }
            else
            {
                this.publicSettings = Inner.Settings as IDictionary<string, object>;
            }
            // Ensure inner settings references the same object
            //
            Inner.Settings = this.publicSettings;
            if (Inner.ProtectedSettings == null)
            {
                this.protectedSettings = new Dictionary<string, object>();
            }
            else if (Inner.ProtectedSettings is JObject)
            {
                // NOTE: Unlike Java, In C# the protectedSettings can be JObject which needs to be
                // specially handled. In Java it is an Object that can be based to Dictionary.
                //
                var jObject = (JObject)(Inner.ProtectedSettings);
                this.protectedSettings = jObject.ToObject<Dictionary<string, object>>();
            }
            else
            {
                this.protectedSettings = Inner.ProtectedSettings as IDictionary<string, object>;
            }
            // Ensure inner protected settings references the same object
            //
            Inner.ProtectedSettings = this.protectedSettings;
        }

19 Source : VirtualMachineScaleSetExtensionImpl.cs
with MIT License
from Azure

public IReadOnlyDictionary<string, object> PublicSettings()
        {
            if (Inner.Settings == null)
            {
                return new Dictionary<string, object>();
            }
            else if (Inner.Settings is JObject)
            {
                var jObject = (JObject)(Inner.Settings);
                return jObject.ToObject<Dictionary<string, object>>();
            }
            else
            {
                return this.Inner.Settings as Dictionary<string, object>;
            }
        }

19 Source : VirtualMachineScaleSetExtensionImpl.cs
with MIT License
from Azure

private IDictionary<string, object> EnsurePublicSettings()
        {
            if (Inner.Settings == null)
            {
                Inner.Settings = new Dictionary<string, object>();
                return (Dictionary<string, object>)Inner.Settings;
            }
            else if (Inner.Settings is JObject)
            {
                var jObject = (JObject)(Inner.Settings);
                Inner.Settings = jObject.ToObject<Dictionary<string, object>>();
                return (Dictionary<string, object>)Inner.Settings;
            }
            else
            {
                return (Dictionary<string, object>)Inner.Settings;
            }
        }

19 Source : VirtualMachineScaleSetExtensionImpl.cs
with MIT License
from Azure

private IDictionary<string, object> EnsureProtectedSettings()
        {
            if (Inner.ProtectedSettings == null)
            {
                Inner.ProtectedSettings = new Dictionary<string, object>();
                return (Dictionary<string, object>)Inner.ProtectedSettings;
            }
            else if (Inner.ProtectedSettings is JObject)
            {
                var jObject = (JObject)(Inner.ProtectedSettings);
                Inner.ProtectedSettings = jObject.ToObject<Dictionary<string, object>>();
                return (Dictionary<string, object>)Inner.ProtectedSettings;
            }
            else
            {
                return Inner.ProtectedSettings as Dictionary<string, object>;
            }
        }

19 Source : CallerResponse.cs
with MIT License
from Azure

public bool SetCompleted(JToken result)
        {
            T value;
            Func<object, bool> trueLikeValue = obj => obj != null && !0.Equals(obj) && !false.Equals(obj) && !"".Equals(obj);
            if (typeof(T) == typeof(bool))
            {
                var obj = result.ToObject<object>();
                value = (T)(object)(trueLikeValue(obj));
            }
            else if (typeof(T) == typeof(bool?))
            {
                var obj = result.ToObject<object>();
                value = obj == null ? (T)(object)(null) : (T)(object)(trueLikeValue(obj));
            }
            else
            {
                value = result.ToObject<T>();
            }
            return TrySetResult(value);
        }

19 Source : CallerResponse.cs
with MIT License
from Azure

public bool SetException(JToken error)
        {
            return TrySetException(error.ToObject<Exception>());
        }

19 Source : MutabilityWithReadOnly.cs
with MIT License
from Azure

private bool ValidateMutabilityValuesWithReadOnlyProperty(object mutable, RuleContext context, out object[] formatParameters)
        {
            string[] values = ((Newtonsoft.Json.Linq.JArray)mutable).ToObject<string[]>();
            string[] invalidValues = null;

            var resolver = new SchemaResolver(context?.GetServiceDefinition());
            Schema schema = resolver.Unwrap(context?.GetFirstAncestor<Schema>());

            if (schema.ReadOnly)
            {
                // Property with "readOnly": true must only have "read" value in x-ms-mutability extension.
                invalidValues = values.Except(ValidValuesForReadOnlyProperty, StringComparer.OrdinalIgnoreCase).ToArray();
            }
            else
            {
                // Property with "readOnly": false must have more than "read" value in x-ms-mutability extension.
                if (values.Length == 1)
                {
                    invalidValues = values.Contains(ValidValuesForReadOnlyProperty[0], StringComparer.OrdinalIgnoreCase) ?
                        ValidValuesForReadOnlyProperty : new string[0];
                }
            }

            bool isValid = invalidValues == null || invalidValues.Length == 0;
            formatParameters = isValid ? new object[0] : new string[] { String.Join(",", invalidValues) };

            return isValid;
        }

19 Source : JsonObjectConverter.cs
with MIT License
from Azure

public static object ConvertToObject(object value)
        {
            // Recursion guard to prevent stackoverflow
            RuntimeHelpers.EnsureSufficientExecutionStack();

            switch (value)
            {
                case JObject jObject:
                    return ConvertJObjectToObject(jObject);
                case JArray jArray:
                    return ConvertJArrayToObject(jArray);
                case JValue jValue:
                    return jValue.ToObject<object>();
                default:
                    return value;
            }
        }

19 Source : BlobLogTest.cs
with MIT License
from Azure

[SkippableFact]
        public async Task TestLogToBlob()
        {
            var storage = Requirements.RequireStorage();
            var ps = new PerfStorage(storage);
            var blob = await ps.GetBlobAsync("logs", true);
            try
            {
                var provider = new BlobLoggerProvider($"test/{nameof(TestLogToBlob)}", ".log", storage);
                var logger = provider.CreateLogger("test");
                var threadId = Thread.CurrentThread.ManagedThreadId;
                var dt1 = DateTime.UtcNow;
                for (int i = 0; i < 10; i++)
                {
                    logger.LogInformation("test from {TestClreplaced}.{MethodName}", nameof(BlobLogTest), nameof(TestLogToBlob));
                }
                var dt2 = DateTime.UtcNow;
                provider.Dispose();
                var paths = await blob.List("test/").ToListAsync();
                replacedert.Single(paths);
                using var ms = new MemoryStream();
                await blob.DownloadAsync(paths[0], ms);
                ms.Seek(0, SeekOrigin.Begin);
                using var sr = new StreamReader(ms);
                var obj = JsonConvert.DeserializeObject<JObject>(sr.ReadLine());
                var dt = obj["EventTime"].ToObject<DateTime>();
                replacedert.True(dt1 <= dt && dt <= dt2);
                replacedert.Equal(0, obj["EventId"].ToObject<int>());
                replacedert.Null(obj["EventName"].ToObject<string>());
                replacedert.Equal(threadId, obj["ThreadId"].ToObject<int>());
                replacedert.Equal("test", obj["Logger"].ToObject<string>());
                replacedert.Equal("test from BlobLogTest.TestLogToBlob", obj["Text"].ToObject<string>());
                replacedert.Null(obj["Exception"].ToObject<string>());
                replacedert.Equal("BlobLogTest", obj["TestClreplaced"].ToObject<string>());
                replacedert.Equal("TestLogToBlob", obj["MethodName"].ToObject<string>());
            }
            finally
            {
                var paths = await blob.List("test/").ToListAsync();
                foreach (var path in paths)
                {
                    await blob.DeleteIfExistsAsync(path);
                }
            }
        }

19 Source : DockerReportedConfig.cs
with MIT License
from Azure

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                JObject obj = JObject.Load(reader);

                // Pull out JToken values from json
                obj.TryGetValue("image", StringComparison.OrdinalIgnoreCase, out JToken jTokenImage);
                obj.TryGetValue("imageHash", StringComparison.OrdinalIgnoreCase, out JToken jTokenImageHash);

                var options = obj.ChunkedValue("createOptions", true)
                    .Take(Constants.TwinValueMaxChunks)
                    .Select(token => token?.ToString() ?? string.Empty)
                    .Join();

                if (obj.TryGetValue("digest", StringComparison.OrdinalIgnoreCase, out JToken jTokenDigest))
                {
                    return new DockerReportedConfig(jTokenImage?.ToString(), options, jTokenImageHash?.ToString(), Option.Maybe(jTokenDigest.ToObject<string>()));
                }
                else
                {
                    return new DockerReportedConfig(jTokenImage?.ToString(), options, jTokenImageHash?.ToString(), Option.None<string>());
                }
            }

See More Examples