public void PopulateExpandoObjectAsRoot()
		{
			dynamic library = new ExpandoObject();

			library.Name = "1Items";
			library.ArticleArray = new Article[] { new Article("Article1") };
			library.ArticleList = new List<Article>() { new Article("Article1") };
			library.ArticleIList = new List<Article>() { new Article("Article1") };
			library.ArticleCollection = new ArticleCollection() { new Article("Article1") };
			library.StringArray = new[] { "Article1" };

			Assert.AreEqual(1, library.ArticleArray.Length);
			Assert.AreEqual(1, library.ArticleCollection.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.StringArray.Length);

			var settings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.Auto
			};

			string json = JsonConvert.SerializeObject(library, Formatting.Indented, settings);

			var expando = new ExpandoObject();
			JsonConvert.PopulateObject(json, expando, settings);
			dynamic result = expando;
			Assert.AreEqual(result.Name, library.Name);
			Assert.AreEqual(1, result.ArticleArray.Length);
			Assert.AreEqual(1, result.ArticleCollection.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.StringArray.Length);
		}
Example #2
0
 public JsonNetResult(object data)
 {
     Data = data;
     SerializerSettings = new JsonSerializerSettings()
     {
         ReferenceLoopHandling = ReferenceLoopHandling.Serialize
     };
 }
Example #3
0
        public static JsonWriter CreateFrom(StreamWriter streamWriter, JsonSerializerSettings settings)
        {
            var jw = new JsonTextWriter(streamWriter);

            // reader/writer specific
            // unset values won't override reader/writer set values
            jw.Formatting = settings.Formatting;
            jw.DateFormatHandling = settings.DateFormatHandling;
            jw.DateTimeZoneHandling = settings.DateTimeZoneHandling;
            jw.DateFormatString = settings.DateFormatString;
            jw.FloatFormatHandling = settings.FloatFormatHandling;
            jw.StringEscapeHandling = settings.StringEscapeHandling;
            jw.Culture = settings.Culture;

            return jw;
        }
Example #4
0
        public static BsonWriter CreateFrom(Stream stream, JsonSerializerSettings settings)
        {
            var bw = new BsonWriter(stream);

            // reader/writer specific
            // unset values won't override reader/writer set values
            bw.Formatting = settings.Formatting;
            bw.DateFormatHandling = settings.DateFormatHandling;
            bw.DateTimeZoneHandling = settings.DateTimeZoneHandling;
            bw.DateFormatString = settings.DateFormatString;
            bw.FloatFormatHandling = settings.FloatFormatHandling;
            bw.StringEscapeHandling = settings.StringEscapeHandling;
            bw.Culture = settings.Culture;

            return bw;
        }
        public void SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid()
        {
            const string contextKey = "k1";
            var someValue = Guid.NewGuid();

            Dictionary<string, Guid> inputContext = new Dictionary<string, Guid>();
            inputContext.Add(contextKey, someValue);

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.All,
                SpecialPropertyHandling = SpecialPropertyHandling.ReadAhead
            };
            string serializedString = JsonConvert.SerializeObject(inputContext, jsonSerializerSettings);

            Console.WriteLine(serializedString);

            var deserializedObject = (Dictionary<string, Guid>)JsonConvert.DeserializeObject(serializedString, jsonSerializerSettings);

            Assert.AreEqual(someValue, deserializedObject[contextKey]);
        }
		public void DeserializeExpandoObjectAsRoot()
		{
			dynamic library = new ExpandoObject();

			library.Name = "1Items";
			library.ArticleArray = new Article[] { new Article("Article1") };
			library.ArticleList = new List<Article>() { new Article("Article1") };
			library.ArticleIList = new List<Article>() { new Article("Article1") };
			library.ArticleCollection = new ArticleCollection() { new Article("Article1") };
			library.StringArray = new[] { "Article1" };

			Assert.AreEqual(1, library.ArticleArray.Length);
			Assert.AreEqual(1, library.ArticleCollection.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.StringArray.Length);

			var settings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.Auto
			};

			string json = JsonConvert.SerializeObject(library, Formatting.Indented, settings);

			//TODO: Fix this
			//var document = JsonConvert.DeserializeXNode(json, "root", false);

			var result = JsonConvert.DeserializeObject<dynamic>(json, settings);

			Assert.AreEqual(result.Name, library.Name);
			Assert.AreEqual(1, result.ArticleArray.Length);
			Assert.AreEqual(1, result.ArticleCollection.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.StringArray.Length);
		}
        public async void InternalStorageFileList()
        {
            nlog.Warn("InternalStorageFileList Started");
            workInternalStorage = true;
            StatusUpdate(Status.Working);

            try
            {
                ConfigSaveAllItem();
                dgvInternalStorage.InvokeIfRequired(s =>
                {
                    s.Rows.Clear();
                    s.RowHeadersVisible = false;
                    s.BackgroundColor   = Color.White;
                });

                string getObjectStorageBackupListResult = await getObjectStorageBackupListAsync();

                var settings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };

                if (getObjectStorageBackupListResult.Contains("server does not exists"))
                {
                    throw new Exception("There is no corresponding server. Perform the Configuration steps again.");
                }

                if (getObjectStorageBackupListResult.Contains("totalRows"))
                {
                    getObjectStorageBackupList getObjectStorageBackupList = JsonConvert.DeserializeObject <getObjectStorageBackupList>(getObjectStorageBackupListResult, settings);
                    List <DmsFileList>         files = getObjectStorageBackupList.getObjectStorageBackupListResponse.dmsFileList;

                    foreach (var file in files)
                    {
                        if (
                            (System.Text.RegularExpressions.Regex.IsMatch
                             (
                                 file.fileName
                                 , textFilterString.Text
                                 , System.Text.RegularExpressions.RegexOptions.IgnoreCase
                             )
                            ) ||
                            textFilterString.Text.Length == 0
                            )
                        {
                            string RequestNo         = string.Empty;
                            string RequestReturnCode = string.Empty;
                            string ReturnCode        = string.Empty;
                            string ReturnCodeName    = string.Empty;

                            dgvInternalStorage.InvokeIfRequired(s =>
                            {
                                int n = s.Rows.Add();
                                s.Rows[n].Cells[0].Value = "false";
                                s.Rows[n].Cells[1].Value = file.fileName;
                                s.Rows[n].Cells[2].Value = file.fileLength;
                                s.Rows[n].Cells[3].Value = String.Format("{0:yyyy-MM-dd HH:mm:ss}", System.DateTime.Parse(file.lastWriteTime));
                            });
                        }
                    }
                }
                else
                {
                    var    responseError = JsonConvert.DeserializeObject <ResponseError>(getObjectStorageBackupListResult, settings);
                    string errorMessage  = $@"returnMessage : {responseError.responseError.returnMessage}, returnCode : {responseError.responseError.returnCode}";
                    throw new Exception(errorMessage);
                }
            }
            catch (Exception ex)
            {
                nlog.Error(string.Format("{0},{1}", ex.Message, ex.StackTrace));
                workInternalStorage = false;
                MessageBox.Show(ex.Message);
            }

            StatusUpdate(Status.Completed);
            workInternalStorage = false;
            nlog.Warn("InternalStorageFileList Completed");
        }
Example #8
0
 public ObjectToJsonConverter(JsonSerializerSettings settings) : base(settings)
 {
     // there's nothing else to do
 }
Example #9
0
 protected JsonConverter(JsonSerializerSettings settings) : this(settings, new HashSet <Type>())
 {
 }
        public async Task <ActionResult> GetGridData()
        {
            try
            {
                string draw          = Request.Form["draw"];
                string start         = Request.Form["start"];
                string length        = Request.Form["length"];
                string sortColumn    = Request.Form["columns[" + Request.Form["order[0][column]"] + "][data]"];
                string sortColumnDir = Request.Form["order[0][dir]"];

                string searchValue = Request.Form["search[value]"];

                //Paging Size (10,20,50,100)
                int pageSize = length != null?Convert.ToInt32(length) : 0;

                int skip = start != null?Convert.ToInt32(start) : 0;

                int recordsTotal = 0;

                // Getting all Customer data
                var modelDataAll = (from temptable in _context.TaskMasterWaterMark
                                    select temptable);

                //filter the list by permitted roles
                if (!CanPerformCurrentActionGlobally())
                {
                    var permittedRoles = GetPermittedGroupsForCurrentAction();
                    var identity       = User.Identity.Name;

                    modelDataAll =
                        (from md in modelDataAll
                         join tm in _context.TaskMaster
                         on md.TaskMasterId equals tm.TaskMasterId
                         join tg in _context.TaskGroup
                         on tm.TaskGroupId equals tg.TaskGroupId
                         join rm in _context.SubjectAreaRoleMap
                         on tg.SubjectAreaId equals rm.SubjectAreaId
                         where
                         GetUserAdGroupUids().Contains(rm.AadGroupUid) &&
                         permittedRoles.Contains(rm.ApplicationRoleName) &&
                         rm.ExpiryDate > DateTimeOffset.Now &&
                         rm.ActiveYn
                         select md).Distinct();
                }

                //Sorting
                if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
                {
                    modelDataAll = modelDataAll.OrderBy(sortColumn + " " + sortColumnDir);
                }
                //Search
                if (!string.IsNullOrEmpty(searchValue))
                {
                    modelDataAll = modelDataAll.Where(m => m.TaskWaterMarkJson.Contains(searchValue) ||
                                                      m.TaskMaster.TaskMasterName.Contains(searchValue) ||
                                                      m.TaskMasterWaterMarkColumn.Contains(searchValue));
                }

                //Filter based on querystring params
                if (!(string.IsNullOrEmpty(Request.Form["QueryParams[TaskMasterId]"])))
                {
                    var taskMasterIdFilter = System.Convert.ToInt64(Request.Form["QueryParams[TaskMasterId]"]);
                    modelDataAll = modelDataAll.Where(t => t.TaskMasterId == taskMasterIdFilter);
                }

                //Custom Includes
                modelDataAll = modelDataAll
                               .Include(x => x.TaskMaster)
                               .AsNoTracking();


                //total number of rows count
                recordsTotal = await modelDataAll.CountAsync();


                //Paging
                var data = await modelDataAll.Skip(skip).Take(pageSize).ToListAsync();



                //Returning Json Data
                var jserl = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Converters            = { new Newtonsoft.Json.Converters.StringEnumConverter() }
                };

                return(new OkObjectResult(JsonConvert.SerializeObject(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, jserl)));
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid()
        {
            const string contextKey = "k1";
            var someValue = new Guid("5dd2dba0-20c0-49f8-a054-1fa3b0a8d774");

            Dictionary<string, Guid> inputContext = new Dictionary<string, Guid>();
            inputContext.Add(contextKey, someValue);

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.All,
                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
            };
            string serializedString = JsonConvert.SerializeObject(inputContext, jsonSerializerSettings);

            StringAssert.AreEqual(@"{
  ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Guid, mscorlib]], mscorlib"",
  ""k1"": ""5dd2dba0-20c0-49f8-a054-1fa3b0a8d774""
}", serializedString);

            var deserializedObject = (Dictionary<string, Guid>)JsonConvert.DeserializeObject(serializedString, jsonSerializerSettings);

            Assert.AreEqual(someValue, deserializedObject[contextKey]);
        }
        public void TestStoredProcedure()
        {
            // Create a document client with a customer json serializer settings
            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();

            serializerSettings.Converters.Add(new ObjectStringJsonConverter <SerializedObject>(_ => _.Name, _ => SerializedObject.Parse(_)));
            ConnectionPolicy connectionPolicy = new ConnectionPolicy {
                ConnectionMode = ConnectionMode.Gateway
            };
            ConsistencyLevel defaultConsistencyLevel = ConsistencyLevel.Session;
            DocumentClient   client = CreateDocumentClient(
                this.hostUri,
                this.masterKey,
                serializerSettings,
                connectionPolicy,
                defaultConsistencyLevel);

            // Create a simple stored procedure
            var scriptId = "bulkImportScript";
            var sproc    = new StoredProcedure
            {
                Id   = scriptId,
                Body = @"
function bulkImport(docs) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();

    // The count of imported docs, also used as current doc index.
    var count = 0;

    // Validate input.
    if (!docs) throw new Error(""The array is undefined or null."");

    var docsLength = docs.length;
            if (docsLength == 0)
            {
                getContext().getResponse().setBody(0);
            }

            // Call the CRUD API to create a document.
            tryCreate(docs[count], callback);

            // Note that there are 2 exit conditions:
            // 1) The createDocument request was not accepted. 
            //    In this case the callback will not be called, we just call setBody and we are done.
            // 2) The callback was called docs.length times.
            //    In this case all documents were created and we don't need to call tryCreate anymore. Just call setBody and we are done.
            function tryCreate(doc, callback) {
            // If you are sure that every document will contain its own (unique) id field then
            // disable the option to auto generate ids.
            // by leaving this on, the entire document is parsed to check if there is an id field or not
            // by disabling this, parsing of the document is skipped because you're telling DocumentDB 
            // that you are providing your own ids.
            // depending on the size of your documents making this change can have a significant 
            // improvement on document creation. 
            var options = {
            disableAutomaticIdGeneration: true
        };

        var isAccepted = collection.createDocument(collectionLink, doc, options, callback);

        // If the request was accepted, callback will be called.
        // Otherwise report current count back to the client, 
        // which will call the script again with remaining set of docs.
        // This condition will happen when this stored procedure has been running too long
        // and is about to get cancelled by the server. This will allow the calling client
        // to resume this batch from the point we got to before isAccepted was set to false
        if (!isAccepted) getContext().getResponse().setBody(count);
    }

    // This is called when collection.createDocument is done and the document has been persisted.
    function callback(err, doc, options)
    {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= docsLength)
        {
            // If we have created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        }
        else
        {
            // Create next document.
            tryCreate(docs[count], callback);
        }
    }
}
"
            };

            sproc = client.CreateStoredProcedureAsync(collectionUri, sproc).Result.Resource;

            var doc = new MyObject(1);

            var args = new dynamic[] { new dynamic[] { doc } };

            RequestOptions requestOptions = ApplyRequestOptions(new RequestOptions {
                PartitionKey = new PartitionKey("value")
            }, serializerSettings);

            StoredProcedureResponse <int> scriptResult = client.ExecuteStoredProcedureAsync <int>(
                sproc.SelfLink,
                requestOptions,
                args).Result;

            var docUri  = UriFactory.CreateDocumentUri(databaseName, collectionName, doc.id);
            var readDoc = client.ReadDocumentAsync <MyObject>(docUri, requestOptions).Result.Document;

            Assert.IsNotNull(readDoc.SerializedObject);
            Assert.AreEqual(doc.SerializedObject.Name, readDoc.SerializedObject.Name);
        }
		public void PopulateExpandoObjectAsAProperty()
		{
			var container = new MagicContainer();
			container.Name = "Container1";
			container.Library = new ExpandoObject();

			container.Library.Name = "1Items";
			container.Library.ArticleArray = new Article[] { new Article("Article1") };
			container.Library.ArticleList = new List<Article>() { new Article("Article1") };
			container.Library.ArticleIList = new List<Article>() { new Article("Article1") };
			container.Library.ArticleCollection = new ArticleCollection() { new Article("Article1") };
			container.Library.StringArray = new[] { "Article1" };

			Assert.AreEqual(1, container.Library.ArticleArray.Length);
			Assert.AreEqual(1, container.Library.ArticleCollection.Count);
			Assert.AreEqual(1, container.Library.ArticleList.Count);
			Assert.AreEqual(1, container.Library.ArticleList.Count);
			Assert.AreEqual(1, container.Library.StringArray.Length);

			var settings = new JsonSerializerSettings { };

			string json = JsonConvert.SerializeObject(container, Formatting.Indented, settings);

			MagicContainer result = new MagicContainer();
			JsonConvert.PopulateObject(json, result, settings);

			Assert.AreEqual(result.Library.Name, container.Library.Name);
			Assert.AreEqual(1, result.Library.ArticleArray.Length);
			Assert.AreEqual(1, result.Library.ArticleCollection.Count);
			Assert.AreEqual(1, result.Library.ArticleList.Count);
			Assert.AreEqual(1, result.Library.ArticleList.Count);
			Assert.AreEqual(1, result.Library.StringArray.Length);
		}
Example #14
0
 /// <summary>
 /// Zonky response resolver
 /// </summary>
 /// <param name="settings"></param>
 /// <param name="isAuthorizedRequest"></param>
 public ZonkyResponseResolver(JsonSerializerSettings settings, bool isAuthorizedRequest = false)
 {
     _settings            = settings;
     _isAuthorizedRequest = isAuthorizedRequest;
     _responces           = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <T> > >();
 }
Example #15
0
 public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration)
 {
     _serializerSettings = serializerSettings;
     _configuration      = configuration;
 }
Example #16
0
        public static GlobalSettings Load(string path, bool boolSkipSave = false)
        {
            GlobalSettings settings          = null;
            bool           isGui             = (AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(a => a.FullName.Contains("PoGo.NecroBot.GUI")) != null);
            var            profilePath       = Path.Combine(Directory.GetCurrentDirectory(), path);
            var            profileConfigPath = Path.Combine(profilePath, "config");
            var            configFile        = Path.Combine(profileConfigPath, "config.json");
            var            shouldExit        = false;

            if (File.Exists(configFile))
            {
                try
                {
                    //if the file exists, load the settings
                    var input = File.ReadAllText(configFile);

                    var jsonSettings = new JsonSerializerSettings();
                    jsonSettings.Converters.Add(new StringEnumConverter {
                        CamelCaseText = true
                    });
                    jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace;
                    jsonSettings.DefaultValueHandling   = DefaultValueHandling.Populate;

                    settings = JsonConvert.DeserializeObject <GlobalSettings>(input, jsonSettings);

                    //This makes sure that existing config files dont get null values which lead to an exception
                    foreach (var filter in settings.PokemonsTransferFilter.Where(x => x.Value.KeepMinOperator == null))
                    {
                        filter.Value.KeepMinOperator = "or";
                    }
                    foreach (var filter in settings.PokemonsTransferFilter.Where(x => x.Value.Moves == null))
                    {
                        filter.Value.Moves = new List <PokemonMove>();
                    }
                    foreach (var filter in settings.PokemonsTransferFilter.Where(x => x.Value.MovesOperator == null))
                    {
                        filter.Value.MovesOperator = "or";
                    }
                }
                catch (JsonReaderException exception)
                {
                    Logger.Write("JSON Exception: " + exception.Message, LogLevel.Error);
                    return(null);
                }
            }
            else
            {
                settings   = new GlobalSettings();
                shouldExit = true;
            }


            settings.ProfilePath       = profilePath;
            settings.ProfileConfigPath = profileConfigPath;
            settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config");
            settings.isGui             = isGui;
            settings.migratePercentages();

            if (!boolSkipSave || !settings.AutoUpdate)
            {
                settings.Save(configFile);
                settings.Auth.Load(Path.Combine(profileConfigPath, "auth.json"));
            }

            return(shouldExit ? null : settings);
        }
 public CustomParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor)
 {
     _jsonSerializerSettings = descriptor.Configuration.Formatters.JsonFormatter.SerializerSettings;
 }
 internal abstract FeedOptions ApplyFeedOptions(FeedOptions feedOptions, JsonSerializerSettings settings);
Example #19
0
        private static async Task <Object[]> Execute <T>(String request, Object requestData, Func <OrderContext, IEnumerable <T> > fromDbFunc)
        {
            var fixture = new RDBNull_DbFixtureInitDb();
            await fixture.Initalize();

            var parser         = new OeParser(new Uri("http://dummy/"), fixture.OeEdmModel);
            var responseStream = new MemoryStream();

            var requestUri = new Uri(@"http://dummy/" + request);

            if (requestData == null)
            {
                await parser.ExecuteGetAsync(requestUri, OeRequestHeaders.JsonDefault, responseStream, CancellationToken.None);
            }
            else
            {
                String data          = JsonConvert.SerializeObject(requestData);
                var    requestStream = new MemoryStream(Encoding.UTF8.GetBytes(data));
                await parser.ExecutePostAsync(requestUri, OeRequestHeaders.JsonDefault, requestStream, responseStream, CancellationToken.None);
            }

            ODataPath path   = OeParser.ParsePath(fixture.OeEdmModel, new Uri("http://dummy/"), requestUri);
            var       reader = new ResponseReader(fixture.OeEdmModel.GetEdmModel(path));

            responseStream.Position = 0;
            Object[] fromOe;
            if (typeof(T) == typeof(int))
            {
                String count = new StreamReader(responseStream).ReadToEnd();
                fromOe = count == "" ? null : new Object[] { int.Parse(count) };
            }
            else if (typeof(T) == typeof(String))
            {
                String json    = new StreamReader(responseStream).ReadToEnd();
                var    jobject = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(json);
                var    jarray  = (Newtonsoft.Json.Linq.JArray)jobject["value"];
                fromOe = jarray.Select(j => (String)j).ToArray();
            }
            else
            {
                fromOe = reader.Read(responseStream).Cast <Object>().ToArray();
            }

            if (fromDbFunc == null)
            {
                return(fromOe);
            }

            T[] fromDb;
            using (OrderContext orderContext = fixture.CreateContext())
                fromDb = fromDbFunc(orderContext).ToArray();

            var settings = new JsonSerializerSettings()
            {
                DateFormatString      = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffff",
                DateTimeZoneHandling  = DateTimeZoneHandling.Utc,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                NullValueHandling     = NullValueHandling.Ignore
            };
            String jsonOe = JsonConvert.SerializeObject(fromOe, settings);
            String jsonDb = JsonConvert.SerializeObject(fromDb, settings);

            Console.WriteLine(requestUri);
            Assert.Equal(jsonDb, jsonOe);

            return(fromOe);
        }
Example #20
0
		public void b_nJson_DeSerializer()
		{
			DateTime st = DateTime.Now;
			colclass c;
			colclass deserializedStore = null;
			JsonSerializerSettings s = null;
			string jsonText = null;
			c= CreateObject();
			s = new JsonSerializerSettings();
			s.TypeNameHandling = TypeNameHandling.All;
			jsonText = JsonConvert.SerializeObject(c, Formatting.Indented, s);
			for (int i = 0; i < count; i++)
			{
				deserializedStore = (colclass)JsonConvert.DeserializeObject(jsonText, typeof(colclass), s);
			}
			//WriteObject(deserializedStore);
			Console.WriteLine("time ms = " + DateTime.Now.Subtract(st).TotalMilliseconds);
		}
 /// <summary>
 /// Constructor of <see cref="SnapshotSerializer"/>
 /// </summary>
 /// <param name="settingsResolver">
 /// The snapshot settings resolver to find all snapshot serialization settings.
 /// </param>
 public SnapshotSerializer(ISnapshotSettingsResolver settingsResolver)
 {
     _jsonSerializerSettings = GetSettings(settingsResolver);
 }
Example #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultSerializer"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public NewtonsoftJsonSerializer(JsonSerializerSettings settings)
 {
     _settings = settings;
 }
Example #23
0
        public void ConfigureServices(IServiceCollection services)
        {
            // setup default json serializers
            JsonConvert.DefaultSettings = () => {
                var jsonSetting = new JsonSerializerSettings
                {
                    ContractResolver     = new CamelCasePropertyNamesContractResolver(),
                    NullValueHandling    = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Include
                };
                jsonSetting.Converters.Add(new StringEnumConverter(new CamelCaseNamingStrategy()));
                return(jsonSetting);
            };

            // setup json serializers for api controllers
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver     = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
                options.SerializerSettings.NullValueHandling    = NullValueHandling.Ignore;
                options.SerializerSettings.Converters.Add(new StringEnumConverter(new CamelCaseNamingStrategy()));
            });


            // setup Hangfire services.
            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseSqlServerStorage(Settings.Current.ArcmageConnectionString, new SqlServerStorageOptions
            {
                CommandBatchMaxTimeout       = TimeSpan.FromMinutes(5),
                SlidingInvisibilityTimeout   = TimeSpan.FromMinutes(5),
                QueuePollInterval            = TimeSpan.Zero,
                UseRecommendedIsolationLevel = true,
                UsePageLocksOnDequeue        = true,
                DisableGlobalLocks           = true,
                SchemaName = "hfo"
            }));

            // add the processing server as IHostedService
            services.AddHangfireServer();

            services.AddSendGrid(options =>
            {
                options.ApiKey = Settings.Current.SendGridApiKey;
            });

            // setup http context access in the middleware pipeline
            var httpContextAccessor = new HttpContextAccessor();

            services.AddSingleton <IHttpContextAccessor>(httpContextAccessor);

            // setup authentication validation
            var key = Encoding.ASCII.GetBytes(Settings.Current.TokenEncryptionKey);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // setup API controller
            services.AddMvcCore()
            .AddApiExplorer();

            // setup gzip compression response
            services.Configure <GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
            services.AddResponseCompression();

            // setup cors access control
            services.AddCors();
        }
Example #24
0
        //[NotNull]
        //private ISet<Type> _stringTypes;

        protected JsonConverter(JsonSerializerSettings settings, ISet <Type> stringTypes)
        {
            Settings    = settings;
            StringTypes = stringTypes;
        }
Example #25
0
        public App()
        {
            _mainViewModels = new List <MainViewModel>();

            InitializeComponent();

            UnhandledException += OnUnhandledException;

            var applicationDataContainers = new ApplicationDataContainers
            {
                LocalSettings   = new ApplicationDataContainerAdapter(ApplicationData.Current.LocalSettings),
                RoamingSettings = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings),
                KeyBindings     = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings.CreateContainer(Constants.KeyBindingsContainerName, ApplicationDataCreateDisposition.Always)),
                ShellProfiles   = new ApplicationDataContainerAdapter(ApplicationData.Current.LocalSettings.CreateContainer(Constants.ShellProfilesContainerName, ApplicationDataCreateDisposition.Always)),
                Themes          = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings.CreateContainer(Constants.ThemesContainerName, ApplicationDataCreateDisposition.Always)),
                SshProfiles     = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings.CreateContainer(Constants.SshProfilesContainerName, ApplicationDataCreateDisposition.Always))
            };
            var builder = new ContainerBuilder();

            builder.RegisterType <SettingsService>().As <ISettingsService>().SingleInstance();
            builder.RegisterType <DefaultValueProvider>().As <IDefaultValueProvider>().SingleInstance();
            builder.RegisterType <TrayProcessCommunicationService>().As <ITrayProcessCommunicationService>().SingleInstance();
            builder.RegisterType <DialogService>().As <IDialogService>().SingleInstance();
            builder.RegisterType <KeyboardCommandService>().As <IKeyboardCommandService>().InstancePerDependency();
            builder.RegisterType <NotificationService>().As <INotificationService>().InstancePerDependency();
            builder.RegisterType <UpdateService>().As <IUpdateService>().InstancePerDependency();
            builder.RegisterType <MainViewModel>().InstancePerDependency();
            builder.RegisterType <SettingsViewModel>().InstancePerDependency();
            builder.RegisterType <ThemeParserFactory>().As <IThemeParserFactory>().SingleInstance();
            builder.RegisterType <ITermThemeParser>().As <IThemeParser>().SingleInstance();
            builder.RegisterType <FluentTerminalThemeParser>().As <IThemeParser>().SingleInstance();
            builder.RegisterType <ClipboardService>().As <IClipboardService>().SingleInstance();
            builder.RegisterType <FileSystemService>().As <IFileSystemService>().SingleInstance();
            builder.RegisterType <SystemFontService>().As <ISystemFontService>().SingleInstance();
            builder.RegisterType <ShellProfileSelectionDialog>().As <IShellProfileSelectionDialog>().InstancePerDependency();
            builder.RegisterType <SshProfileSelectionDialog>().As <ISshProfileSelectionDialog>().InstancePerDependency();
            builder.RegisterType <CreateKeyBindingDialog>().As <ICreateKeyBindingDialog>().InstancePerDependency();
            builder.RegisterType <InputDialog>().As <IInputDialog>().InstancePerDependency();
            builder.RegisterType <MessageDialogAdapter>().As <IMessageDialog>().InstancePerDependency();
            builder.RegisterType <SshInfoDialog>().As <ISshConnectionInfoDialog>().InstancePerDependency();
            builder.RegisterType <ApplicationViewAdapter>().As <IApplicationView>().InstancePerDependency();
            builder.RegisterType <DispatcherTimerAdapter>().As <IDispatcherTimer>().InstancePerDependency();
            builder.RegisterType <StartupTaskService>().As <IStartupTaskService>().SingleInstance();
            builder.RegisterType <SshHelperService>().As <ISshHelperService>().SingleInstance();
            builder.RegisterType <ApplicationLanguageService>().As <IApplicationLanguageService>().SingleInstance();
            builder.RegisterInstance(applicationDataContainers);

            _container = builder.Build();

            _settingsService = _container.Resolve <ISettingsService>();
            _settingsService.ApplicationSettingsChanged += OnApplicationSettingsChanged;

            _trayProcessCommunicationService = _container.Resolve <ITrayProcessCommunicationService>();

            _sshHelperService = new Lazy <ISshHelperService>(() => _container.Resolve <ISshHelperService>());

            _dialogService = _container.Resolve <IDialogService>();

            _applicationSettings = _settingsService.GetApplicationSettings();

            JsonConvert.DefaultSettings = () =>
            {
                var settings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                };
                settings.Converters.Add(new StringEnumConverter(typeof(CamelCaseNamingStrategy)));

                return(settings);
            };

            _commandLineParser = new Parser(settings =>
            {
                settings.CaseSensitive             = false;
                settings.CaseInsensitiveEnumValues = true;
            });
        }
Example #26
0
        private static void Test2()
        {
            #if NETCORE

            //ProtoBufTest.Test();
            {
                object exobj = null;
                try
                {
                    var b = 3;
                    b = 0;
                    var c = 2 / b;
                }
                catch (Exception exs)
                {
                    exobj = exs;
                }
                //var ex = new Exception("test ex");
                var ex = exobj;
                //var ex = new ServiceTest.Contract.Product
                //{
                //	Id = 223,
                //	Name = "abc book",
                //	Category = "Book",
                //	ListDate = DateTime.Now,
                //	Price = 34,
                //	Tags = new List<string>
                //	{
                //		"book",
                //		"tech",
                //		"new"
                //	}
                //};

                {
                    try
                    {
                        var setting = new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                            ContractResolver = new SerializeContractResolver()
                        };
                        var json = JsonConvert.SerializeObject(ex, setting);
                        Console.WriteLine(json);
                        var dex = JsonConvert.DeserializeObject(json, ex.GetType(), setting);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }

                var dcs = new DataContractSerializer(ex.GetType());
                var ms = new MemoryStream();
                dcs.WriteObject(ms, ex);

                ms.Position = 0;
                var dex3 = dcs.ReadObject(ms);
                var xml = Encoding.UTF8.GetString(ms.ToArray());

                var jss = new System.Runtime.Serialization.Json.DataContractJsonSerializer(ex.GetType());
                var jsms = new MemoryStream();
                jss.WriteObject(jsms, ex);

                ms.Position = 0;
                var dexjs = dcs.ReadObject(ms);
                var jsss = Encoding.UTF8.GetString(ms.ToArray());

                var product = new ServiceTest.Contract.Product
                {
                    Id = 223,
                    Name = "abc book",
                    Category = "Book",
                    ListDate = DateTime.Now,
                    Price = 34,
                    Tags = new List<string>
                    {
                        "book",
                        "tech",
                        "new"
                    }
                };
                var xmlSeriaizer = new System.Xml.Serialization.XmlSerializer(product.GetType());
                var stringWriter = new StringWriter();
                //var xmlWriter = new XmlWriter();
                xmlSeriaizer.Serialize(stringWriter, (object)product);
            }
            #endif
        }
Example #27
0
 public CustomJsonSerializer(JsonSerializerSettings jsonSerializerSettings)
 {
     this.serializer = JsonSerializer.Create(jsonSerializerSettings);
 }
        public static void AddApiServices(this IServiceCollection services, IConfiguration configuration, IHostingEnvironment env)
        {
            JsonConvert.DefaultSettings = (() =>
            {
                var settings = new JsonSerializerSettings();
                settings.Converters.Add(new StringEnumConverter {
                    CamelCaseText = true
                });
                return(settings);
            });

            var httpClientConfiguration = configuration.GetSection("HttpClientFactory");

            foreach (var clientConfiguration in httpClientConfiguration.GetChildren())
            {
                var apiName = clientConfiguration.Key;
                services.AddHttpClient(apiName, client =>
                {
                    client.BaseAddress        = new Uri(clientConfiguration["BaseAddress"]);
                    var authenticationSection = clientConfiguration.GetSection("Authentication");
                    if (authenticationSection.GetChildren().Count() > 0)
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                            authenticationSection["Scheme"],
                            authenticationSection["Parameter"]);
                    }
                });
            }

            services.AddCors();

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                opt.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                opt.SerializerSettings.Converters.Add(new StringEnumConverter {
                    CamelCaseText = true
                });
            });

            if (configuration.GetValue <bool>("EnableSwagger"))
            {
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new Info {
                        Title = Assembly.GetEntryAssembly().GetName().Name, Version = "1"
                    });
                    options.EnableAnnotations();
                    options.CustomSchemaIds(x => x.Name);

                    if (configuration.GetSection("Auth0") != null)
                    {
                        options.OperationFilter <SecurityRequirementsOperationFilter>();
                        var authServerUrl = $"https://{configuration.GetValue<string>("Auth0:Domain")}";
                        options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                        {
                            Type             = "oauth2",
                            Flow             = "implicit",
                            AuthorizationUrl = authServerUrl + "/authorize",
                            TokenUrl         = authServerUrl + "/oauth/token",
                        });
                    }

                    options.OperationFilter <FileUploadOperationFilter>();
                });
            }

            services.AddSingleton <IDateTimeService, DateTimeService>();
        }
        public void SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid()
        {
            const string contextKey = "k1";
            var someValue = new Guid("5dd2dba0-20c0-49f8-a054-1fa3b0a8d774");

            Dictionary<string, Guid> inputContext = new Dictionary<string, Guid>();
            inputContext.Add(contextKey, someValue);

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.All,
                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
            };
            string serializedString = JsonConvert.SerializeObject(inputContext, jsonSerializerSettings);

            StringAssert.AreEqual(@"{
  ""$type"": """ + ReflectionUtils.GetTypeName(typeof(Dictionary<string, Guid>), 0, DefaultSerializationBinder.Instance) + @""",
  ""k1"": ""5dd2dba0-20c0-49f8-a054-1fa3b0a8d774""
}", serializedString);

            var deserializedObject = (Dictionary<string, Guid>)JsonConvert.DeserializeObject(serializedString, jsonSerializerSettings);

            Assert.AreEqual(someValue, deserializedObject[contextKey]);
        }
        /// <summary>
        /// Serializes the specified <paramref name="value"/> and writes the JSON structure using the specified <paramref name="writer"/>.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> used to write the JSON structure.</param>
        /// <param name="value">The <see cref="object"/> to serialize.</param>
        /// <param name="settings">The settings to associate with the specified <paramref name="writer"/>. Default is <see cref="JsonConvert.DefaultSettings"/>.</param>
        public static void WriteObject(this JsonWriter writer, object value, JsonSerializerSettings settings = null)
        {
            var serializer = settings == null?JsonSerializer.CreateDefault() : JsonSerializer.Create(settings);

            serializer.Serialize(writer, value);
        }
Example #31
0
 public WebSocketClient(string path, JsonSerializerSettings jsonSerializerSettings = null, ILog log = null) : this(path, jsonSerializerSettings)
 {
     _log = log;
 }
Example #32
0
 public static T JSONToObjectBySetting <T>(string input, JsonSerializerSettings settings)
 {
     return(JsonConvert.DeserializeObject <T>(input, settings));
 }
Example #33
0
        public CosmosSqlProviderV2( // TODO: use OptionsBuilder here
            ILogger <CosmosSqlProviderV2 <T> > logger,
            IDocumentClient client,
            string databaseId,
            Func <string> collectionIdFactory = null,
            string partitionKeyPath           = "/Discriminator",
            int throughput = 400,
            //Expression<Func<T, object>> idNameFactory = null,
            bool isMasterCollection       = true,
            IndexingPolicy indexingPolicy = null)
        {
            EnsureArg.IsNotNull(logger, nameof(logger));
            EnsureArg.IsNotNull(client, nameof(client));

            this.logger             = logger;
            this.client             = client;
            this.databaseId         = databaseId ?? "master";
            this.database           = new AsyncLazy <Database>(async() => await this.GetOrCreateDatabaseAsync().AnyContext());
            this.partitionKeyPath   = partitionKeyPath.EmptyToNull() ?? "/Discriminator";
            this.partitionKeyValue  = typeof(T).FullName;
            this.isMasterCollection = isMasterCollection;

            if (collectionIdFactory != null)
            {
                this.collectionId = collectionIdFactory();
            }

            if (string.IsNullOrEmpty(this.collectionId))
            {
                this.collectionId = isMasterCollection ? "master" : typeof(T).Name;
            }

            this.documentCollection = new AsyncLazy <DocumentCollection>(async() =>
                                                                         await this.GetOrCreateCollectionAsync(this.partitionKeyPath, throughput).AnyContext());

            if (this.documentCollection.Value.Result != null)
            {
                if (this.documentCollection.Value.Result.PartitionKey?.Paths?.Any() == true)
                {
                    this.isPartitioned = true;
                }

                if (indexingPolicy == null)
                {
                    // change the default indexingPolicy so ORDER BY works better with string fields
                    // https://github.com/Azure/azure-cosmos-dotnet-v2/blob/2e9a48b6a446b47dd6182606c8608d439b88b683/samples/code-samples/IndexManagement/Program.cs#L305-L340
                    indexingPolicy = new IndexingPolicy();
                    indexingPolicy.IncludedPaths.Add(
                        new IncludedPath
                    {
                        Path    = "/*",
                        Indexes = new Collection <Index>()
                        {
                            new RangeIndex(DataType.Number)
                            {
                                Precision = -1
                            },
                            new RangeIndex(DataType.String)
                            {
                                Precision = -1
                            }                                                      // needed for orderby on strings
                        }
                    });
                }

                this.documentCollection.Value.Result.IndexingPolicy = indexingPolicy;
            }

            this.jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new PrivateSetterContractResolver()
            };

            //if (idNameFactory != null)
            //{
            //    this.TryGetIdProperty(idNameFactory);
            //}

            // https://github.com/Azure/azure-cosmosdb-dotnet/blob/f374cc601f4cf08d11c88f0c3fa7dcefaf7ecfe8/samples/code-samples/DocumentManagement/Program.cs#L211
        }
Example #34
0
 private static void ConfigureJsonSerializerSettings(JsonSerializerSettings jsonSerializerSettings)
 {
     jsonSerializerSettings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
     jsonSerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
 }
Example #35
0
 internal VirusTotal(string apiKey, JsonSerializerSettings settings) : this(apiKey)
 {
     _serializer = JsonSerializer.Create(settings);
 }
 internal abstract DocumentClient CreateDocumentClient(
     Uri hostUri,
     string key,
     JsonSerializerSettings settings,
     ConnectionPolicy connectionPolicy,
     ConsistencyLevel consistencyLevel);
Example #37
0
 public NewtonsoftPrimitiveTypeHandler(JsonSerializerSettings serializerSettings)
 {
     _serializerSettings = serializerSettings;
 }
 internal abstract RequestOptions ApplyRequestOptions(RequestOptions readOptions, JsonSerializerSettings settings);
Example #39
0
 public MetricDataSerializer(JsonSerializerSettings jsonSerializerSettings)
 {
     _settings = jsonSerializerSettings;
 }
    public void NoPublicDefaultConstructor()
    {
      var settings = new JsonSerializerSettings();
      settings.NullValueHandling = NullValueHandling.Ignore;
      var json = @"{
  ""contributors"": null
}";
      
      JsonConvert.DeserializeObject<DynamicObject>(json, settings);
    }
Example #41
0
        public virtual JsonResult Json <T>([NotNull] T content, [NotNull] JsonSerializerSettings serializerSettings)
        {
            var formatter = new JsonOutputFormatter(serializerSettings);

            return(new JsonResult(content, formatter));
        }
Example #42
0
        public void TypeNameHandlingAuto()
        {
            var binder = new MyBinder();

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder = binder
            };

            Zoo zoo = new Zoo
            {
                Animals = new List<Animal>
                {
                    new Dog("Dog!")
                }
            };

            JsonSerializer serializer = JsonSerializer.Create(settings);

            MemoryStream ms = new MemoryStream();
            BsonWriter bsonWriter = new BsonWriter(ms);
            serializer.Serialize(bsonWriter, zoo);

            ms.Seek(0, SeekOrigin.Begin);

            var deserialized = serializer.Deserialize<Zoo>(new BsonReader(ms));

            Assert.AreEqual(1, deserialized.Animals.Count);
            Assert.AreEqual("Dog!", deserialized.Animals[0].Name);
            Assert.IsTrue(deserialized.Animals[0] is Dog);

#if !(NET20 || NET35)
            Assert.IsTrue(binder.BindToNameCalled);
#endif
            Assert.IsTrue(binder.BindToTypeCalled);
        }
Example #43
0
 public ObjectToJsonConverter(JsonSerializerSettings settings, ISet <Type> stringTypes) : base(settings, stringTypes)
 {
     // there's nothing else to do
 }
        public void ReadDatesAsDateTimeOffsetViaJsonConvert()
        {
            var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";

            var jsonSerializerSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind };
            JObject obj = (JObject)JsonConvert.DeserializeObject(content, jsonSerializerSettings);

            object startDateTime = obj["startDateTime"];

            CustomAssert.IsInstanceOfType(typeof(DateTimeOffset), startDateTime);
        }
    public void AllowNonPublicDefaultConstructor()
    {
      var settings = new JsonSerializerSettings();
      settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;

      var json = @"{
  ""contributors"": null,
  ""retweeted"": false,
  ""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
  ""in_reply_to_user_id_str"": null,
  ""retweet_count"": 0,
  ""geo"": null,
  ""id_str"": ""40678260320768000"",
  ""in_reply_to_status_id"": null,
  ""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
  ""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
  ""place"": null,
  ""coordinates"": null,
  ""truncated"": false,
  ""favorited"": false,
  ""user"": {
    ""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
    ""url"": ""http://bit.ly/dcFwWC"",
    ""screen_name"": ""marutisuzukisx4"",
    ""verified"": false,
    ""friends_count"": 45,
    ""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
    ""follow_request_sent"": null,
    ""time_zone"": ""Chennai"",
    ""profile_text_color"": ""333333"",
    ""location"": ""India"",
    ""notifications"": null,
    ""profile_sidebar_fill_color"": ""efefef"",
    ""id_str"": ""196143889"",
    ""contributors_enabled"": false,
    ""lang"": ""en"",
    ""profile_background_tile"": false,
    ""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
    ""followers_count"": 117,
    ""show_all_inline_media"": true,
    ""listed_count"": 1,
    ""geo_enabled"": true,
    ""profile_link_color"": ""009999"",
    ""profile_sidebar_border_color"": ""eeeeee"",
    ""protected"": false,
    ""name"": ""Maruti Suzuki SX4"",
    ""statuses_count"": 637,
    ""following"": null,
    ""profile_use_background_image"": true,
    ""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
    ""id"": 196143889,
    ""is_translator"": false,
    ""utc_offset"": 19800,
    ""favourites_count"": 0,
    ""profile_background_color"": ""131516""
  },
  ""in_reply_to_screen_name"": null,
  ""id"": 40678260320768000,
  ""in_reply_to_status_id_str"": null,
  ""in_reply_to_user_id"": null
}";

      DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);

      Assert.AreEqual(false, foo.Values["retweeted"]);
    }
        public void SerializeMultiValueEntityKey()
        {
            EntityKey e = new EntityKey("DataServicesTestDatabaseEntities.Folder",
                new List<EntityKeyMember>
                {
                    new EntityKeyMember("GuidId", new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E")),
                    new EntityKeyMember("IntId", int.MaxValue),
                    new EntityKeyMember("LongId", long.MaxValue),
                    new EntityKeyMember("StringId", "String!"),
                    new EntityKeyMember("DateTimeId", new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc))
                });

            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            string json = JsonConvert.SerializeObject(e, settings);

            StringAssert.AreEqual(@"{
  ""$id"": ""1"",
  ""entitySetName"": ""Folder"",
  ""entityContainerName"": ""DataServicesTestDatabaseEntities"",
  ""entityKeyValues"": [
    {
      ""key"": ""GuidId"",
      ""type"": ""System.Guid"",
      ""value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
    },
    {
      ""key"": ""IntId"",
      ""type"": ""System.Int32"",
      ""value"": ""2147483647""
    },
    {
      ""key"": ""LongId"",
      ""type"": ""System.Int64"",
      ""value"": ""9223372036854775807""
    },
    {
      ""key"": ""StringId"",
      ""type"": ""System.String"",
      ""value"": ""String!""
    },
    {
      ""key"": ""DateTimeId"",
      ""type"": ""System.DateTime"",
      ""value"": ""12/10/2000 10:50:00""
    }
  ]
}", json);

            EntityKey newKey = JsonConvert.DeserializeObject<EntityKey>(json);
            Assert.IsFalse(ReferenceEquals(e, newKey));

            Assert.AreEqual(5, newKey.EntityKeyValues.Length);
            Assert.AreEqual("GuidId", newKey.EntityKeyValues[0].Key);
            Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), newKey.EntityKeyValues[0].Value);
            Assert.AreEqual("IntId", newKey.EntityKeyValues[1].Key);
            Assert.AreEqual(int.MaxValue, newKey.EntityKeyValues[1].Value);
            Assert.AreEqual("LongId", newKey.EntityKeyValues[2].Key);
            Assert.AreEqual(long.MaxValue, newKey.EntityKeyValues[2].Value);
            Assert.AreEqual("StringId", newKey.EntityKeyValues[3].Key);
            Assert.AreEqual("String!", newKey.EntityKeyValues[3].Value);
            Assert.AreEqual("DateTimeId", newKey.EntityKeyValues[4].Key);
            Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), newKey.EntityKeyValues[4].Value);
        }
    public void NoPublicDefaultConstructor()
    {
      ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Path 'contributors', line 2, position 18.",
      () =>
      {
        var settings = new JsonSerializerSettings();
        settings.NullValueHandling = NullValueHandling.Ignore;
        var json = @"{
  ""contributors"": null
}";

        JsonConvert.DeserializeObject<DynamicObject>(json, settings);
      });
    }
        public void SerializeEntityCamelCase()
        {
            Folder rootFolder = CreateEntitiesTestData();

            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters = { new IsoDateTimeConverter() }
            };

            string json = JsonConvert.SerializeObject(rootFolder, settings);

            Console.WriteLine(json);

            string expected = @"{
  ""$id"": ""1"",
  ""folderId"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e"",
  ""name"": ""Root folder"",
  ""description"": ""Description!"",
  ""createdDate"": ""2000-12-10T10:50:00Z"",
  ""files"": [],
  ""childFolders"": [
    {
      ""$id"": ""2"",
      ""folderId"": ""484936e2-7cbb-4592-93ff-b2103e5705e4"",
      ""name"": ""Child folder"",
      ""description"": ""Description!"",
      ""createdDate"": ""2001-11-20T10:50:00Z"",
      ""files"": [
        {
          ""$id"": ""3"",
          ""fileId"": ""cc76d734-49f1-4616-bb38-41514228ac6c"",
          ""name"": ""File 1"",
          ""description"": ""Description!"",
          ""createdDate"": ""2002-10-30T10:50:00Z"",
          ""folder"": {
            ""$ref"": ""2""
          },
          ""entityKey"": {
            ""$id"": ""4"",
            ""entitySetName"": ""File"",
            ""entityContainerName"": ""DataServicesTestDatabaseEntities"",
            ""entityKeyValues"": [
              {
                ""key"": ""FileId"",
                ""type"": ""System.Guid"",
                ""value"": ""cc76d734-49f1-4616-bb38-41514228ac6c""
              }
            ]
          }
        }
      ],
      ""childFolders"": [],
      ""parentFolder"": {
        ""$ref"": ""1""
      },
      ""entityKey"": {
        ""$id"": ""5"",
        ""entitySetName"": ""Folder"",
        ""entityContainerName"": ""DataServicesTestDatabaseEntities"",
        ""entityKeyValues"": [
          {
            ""key"": ""FolderId"",
            ""type"": ""System.Guid"",
            ""value"": ""484936e2-7cbb-4592-93ff-b2103e5705e4""
          }
        ]
      }
    }
  ],
  ""parentFolder"": null,
  ""entityKey"": {
    ""$id"": ""6"",
    ""entitySetName"": ""Folder"",
    ""entityContainerName"": ""DataServicesTestDatabaseEntities"",
    ""entityKeyValues"": [
      {
        ""key"": ""FolderId"",
        ""type"": ""System.Guid"",
        ""value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
      }
    ]
  }
}";

            StringAssert.AreEqual(expected, json);
        }
        public void DeserializeDateTimeOffset()
        {
            var settings = new JsonSerializerSettings();
            settings.DateParseHandling = DateParseHandling.DateTimeOffset;
            settings.Converters.Add(new IsoDateTimeConverter());

            // Intentionally use an offset that is unlikely in the real world,
            // so the test will be accurate regardless of the local time zone setting.
            var offset = new TimeSpan(2, 15, 0);
            var dto = new DateTimeOffset(2014, 1, 1, 0, 0, 0, 0, offset);

            var test = JsonConvert.DeserializeObject<DateTimeOffset>("\"2014-01-01T00:00:00+02:15\"", settings);

            Assert.AreEqual(dto, test);
            Assert.AreEqual(dto.ToString("o"), test.ToString("o"));
        }
    public void FromObjectInsideConverterWithCustomSerializer()
    {
      var p = new Person
      {
        Name = "Daniel Wertheim",
      };

      var settings = new JsonSerializerSettings
      {
        Converters = new List<JsonConverter> { new FooJsonConverter() },
        ContractResolver = new CamelCasePropertyNamesContractResolver()
      };

      var json = JsonConvert.SerializeObject(p, settings);

      Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json);
    }
        public void WriteEndOnPropertyState2()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Error += (obj, args) =>
            {
                args.ErrorContext.Handled = true;
            };

            var data = new List<ErrorPerson2>
        {
          new ErrorPerson2 {FirstName = "Scott", LastName = "Hanselman"},
          new ErrorPerson2 {FirstName = "Scott", LastName = "Hunter"},
          new ErrorPerson2 {FirstName = "Scott", LastName = "Guthrie"},
          new ErrorPerson2 {FirstName = "James", LastName = "Newton-King"},
        };

            Dictionary<string, IEnumerable<IErrorPerson2>> dictionary = data.GroupBy(person => person.FirstName).ToDictionary(group => @group.Key, group => @group.Cast<IErrorPerson2>());
            string output = JsonConvert.SerializeObject(dictionary, Formatting.None, settings);

            Assert.AreEqual(@"{""Scott"":[],""James"":[]}", output);
        }
    public JsonSerializerSettings GetDefaultSerializerSettings()
    {
      if (_existingDefaultSettings != null)
      {
        // ensure any existing settings are preserved
        // and the existing trace writer is wrapped
        JsonSerializerSettings existingSettings = _existingDefaultSettings() ?? new JsonSerializerSettings();

        if (!IsGlimpseEnabled())
          return existingSettings;

        // anti-inception
        if (!(existingSettings.TraceWriter is GlimpseTraceWriter))
          existingSettings.TraceWriter = new GlimpseTraceWriter(_messageBroker, _timerStrategy, existingSettings.TraceWriter);

        return existingSettings;
      }
      else
      {
        JsonSerializerSettings settings = new JsonSerializerSettings();

        if (!IsGlimpseEnabled())
          return settings;

        settings.TraceWriter = new GlimpseTraceWriter(_messageBroker, _timerStrategy);

        return settings;
      }
    }
Example #53
-2
        private static void SerializationExample(IEnumerable<IItem> items)
        {
            // 1.
            /*    Console.WriteLine(JsonConvert.SerializeObject(items));

            // 2.
            Console.WriteLine(JsonConvert.SerializeObject(items, Formatting.Indented));
            */
            // 3.
            var settings = new JsonSerializerSettings() { Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Auto };
            Console.WriteLine(JsonConvert.SerializeObject(items, settings));

            // 4.
            var text = JsonConvert.SerializeObject(items, settings);
            var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var filename = Path.Combine(desktop, "items.json");
            File.WriteAllText(filename, text);

            // 5.

            var textFromFile = File.ReadAllText(filename);
            var itemsFromFile = JsonConvert.DeserializeObject<IItem[]>(textFromFile, settings);
            var currency = Currency.EUR;
            foreach (var x in itemsFromFile)
                Console.WriteLine($"{x.Description.Truncate(50),-50} {x.Price.ConvertTo(currency).Amount,8:0.00} {currency}");
            SerializationExample.Run(items);
        }