Serializes and deserializes objects into and from the JSON format. The JsonSerializer enables you to control how objects are encoded into JSON.
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken value = null;
            var response = new FindConnectedObjectsResponse();
            // status
            var json = JObject.ReadFrom(reader) as JObject;
            json.TryGetValue("status", out value);
            response.Status = serializer.Deserialize<Status>(value.CreateReader());
            if (response.Status.IsSuccessful == false)
                return response;
            json.Remove("status");

            // paging info
            // Extract paging info
            json.TryGetValue("paginginfo", out value);
            response.PagingInfo = serializer.Deserialize<PagingInfo>(value.CreateReader());
            json.Remove("paginginfo");

            // extract parent label
            json.TryGetValue("parent", out value);
            var parentLabel = value.ToString();

            // Extract graph node.
            json.TryGetValue("nodes", out value);
            if (value.Type != JTokenType.Null)
            {
                var nodes = value.Values<JObject>();
                ParseNodes(response, parentLabel, nodes, serializer);
            }
            else
                response.Nodes = new List<GraphNode>();
            return response;
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var representation = value as Representation;
            if (representation != null)
                representation.RepopulateHyperMedia();

            var list = (IRepresentationList)value;

            writer.WriteStartObject();
            writer.WritePropertyName("_links");
            serializer.Serialize(writer, list.Links);

            writer.WritePropertyName("_embedded");
            writer.WriteStartObject();
            writer.WritePropertyName(list.Rel);
            writer.WriteStartArray();
            foreach (Representation halResource in list)
            {
                serializer.Serialize(writer, halResource);
            }

            writer.WriteEndArray();
            writer.WriteEndObject();

            var listType = list.GetType();
            var propertyInfos = typeof(RepresentationList<>).GetProperties().Select(p => p.Name);
            foreach (var property in listType.GetProperties().Where(p => !propertyInfos.Contains(p.Name)))
            {
                writer.WritePropertyName(property.Name.ToLower());
                serializer.Serialize(writer, property.GetValue(value, null));
            }

            writer.WriteEndObject();
        }
		private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer)
		{
			JToken typeToken;
			serializer.TypeNameHandling = TypeNameHandling.None;
			if (po.TryGetValue("type", out typeToken))
			{
				var type = typeToken.Value<string>().ToLowerInvariant();
				switch (type)
				{
					case "string":
						return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
					case "float":
					case "double":
					case "byte":
					case "short":
					case "integer":
					case "long":
						return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
					case "date":
						return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
					case "boolean":
						return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
					case "binary":
						return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
				}
			}
			return null;
		}
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var j = JObject.Load(reader);
			if (j == null || !j.HasValues)
				return null;
			IRegexpFilter filter = new RegexpFilterDescriptor<object>();
			foreach (var jv in j)
			{
				switch (jv.Key)
				{
					case "_cache":
						filter.Cache = jv.Value.Value<bool>();
						break;
					case "_cache_key":
						filter.CacheKey = jv.Value.Value<string>();
						break;
					case "_name":
						filter.FilterName = jv.Value.Value<string>();
						break;
					default:
						filter.Field = jv.Key;
						var value = jv.Value["value"];
						if (value != null)
							filter.Value = value.Value<string>();
						var flags = jv.Value["flags"];
						if (flags != null)
							filter.Flags = flags.Value<string>();
						break;
				}
			}

			return filter;

		}
        /// <summary>
        /// Writes the json.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var serialize = true;

            if (_jsonSerializer.PreserveReferences)
            {
                var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName();
                using (var scopeManager = ScopeManager<ReferenceManager>.GetScopeManager(scopeName))
                {
                    var referenceManager = scopeManager.ScopeObject;

                    var referenceInfo = referenceManager.GetInfo(value);
                    if (referenceInfo != null && !referenceInfo.IsFirstUsage)
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName(Json.JsonSerializer.GraphRefId);
                        writer.WriteValue(referenceInfo.Id);
                        writer.WriteEndObject();

                        serialize = false;
                    }
                }
            }

            if (serialize)
            {
                _jsonSerializer.Serialize((ModelBase)value, writer);
            }
        }
示例#6
0
        /// <summary>
        ///     Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var coordinateElements = value as List<LineString>;
            if (coordinateElements != null && coordinateElements.Count > 0)
            {
                if (coordinateElements[0].Coordinates[0] != null)
                {
                    writer.WriteStartArray();

                    foreach (var subPolygon in coordinateElements)
                    {
                        LineStringConverter.WriteJson(writer, subPolygon.Coordinates, serializer);
                    }

                    writer.WriteEndArray();
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            else
            {
                serializer.Serialize(writer, value);
            }
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var relations = (Relations)value;

            writer.WriteStartObject();

            var groupedByRel = relations.Links
                .GroupBy(_ => _.Rel)
                .ToDictionary(_ => _.Key, _ => _.ToArray());

            var allRelsExceptWellKnown = groupedByRel.Keys
                .Where(key => key != Link.CuriesRel && key != Link.SelfRel).ToList();

            // Not strictly required, but we will write the nodes in a nice order.
            if (groupedByRel.ContainsKey(Link.SelfRel))
            {
                WriteLinks(writer, serializer, Link.SelfRel, links: groupedByRel[Link.SelfRel]);
            }

            if (groupedByRel.ContainsKey(Link.CuriesRel))
            {
                WriteLinks(writer, serializer, Link.CuriesRel, links: groupedByRel[Link.CuriesRel]);
            }

            foreach (var rel in allRelsExceptWellKnown)
            {
                WriteLinks(writer, serializer, rel, links: groupedByRel[rel]);
            }

            writer.WriteEndObject();
        }        
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            FeatureCollectionResult fc = (FeatureCollectionResult)value;

            serializer.Converters.Add(new FeatureResultJsonConverter());
            serializer.Converters.Add(new StringEnumConverter());
            //serializer.Converters.Add(new GeometryConverter());

            writer.WriteStartObject();

            if (fc.Id != null){
                writer.WritePropertyName("id");
                writer.WriteValue(fc.Id);
            }

            if (fc.Properties != null) {
                writer.WritePropertyName("properties");
                serializer.Serialize(writer, (fc.Properties));
            }

            if (fc.FeatureResults != null) {
                writer.WritePropertyName("features");
                serializer.Serialize(writer, fc.FeatureResults.ToArray());
            }

            writer.WritePropertyName("type");
            serializer.Serialize(writer, (fc.Type));

            writer.WriteEndObject();
        }
        public void ReadJsonWithInnerObjectTest()
        {
            const string json = "{\"properties\":{\"test1\":\"value1\",\"test2\": { \"innertest1\":\"innervalue1\" }}}";
            AttributesTableConverter target = new AttributesTableConverter();
            using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
            {
                JsonSerializer serializer = new JsonSerializer();

                // read start object token and prepare the next token
                reader.Read();
                reader.Read();
                AttributesTable result =
                    (AttributesTable)
                    target.ReadJson(reader, typeof(AttributesTable), new AttributesTable(), serializer);
                Assert.IsFalse(reader.Read()); // read the end of object and ensure there are no more tokens available
                Assert.IsNotNull(result);
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual("value1", result["test1"]);
                Assert.IsNotNull(result["test2"]);
                Assert.IsInstanceOf<IAttributesTable>(result["test2"]);
                IAttributesTable inner = (IAttributesTable)result["test2"];
                Assert.AreEqual(1, inner.Count);
                Assert.AreEqual("innervalue1", inner["innertest1"]);
            }
        }
        //TODO: This method can be removed if we used DateTimeOffsets instead
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                object o = base.ReadJson(reader, objectType, existingValue, serializer);

                //This is required because DateTime is really bad at parsing RFC1123 dates in C#.  Basically it parses the value but 
                //doesn't attach a DateTimeKind to it (even though RFC1123 specification says that the "Kind" should be UTC.  This results
                //in a DateTime WITHOUT a DateTimeKind specifier, which is bad bad bad.  We do the below in order to force the DateTimeKind
                //of the resulting DateTime to be DateTimeKind.Utc since that is what the RFC1123 specification implies.
                //See: http://stackoverflow.com/questions/1201378/how-does-datetime-touniversaltime-work
                //See: http://stackoverflow.com/questions/16442484/datetime-unspecified-kind
                DateTime? time = o as DateTime?;

                if (time.HasValue && time.Value.Kind == DateTimeKind.Unspecified)
                {
                    time = DateTime.SpecifyKind(time.Value, DateTimeKind.Utc);
                }

                return time;
            }
            catch (FormatException ex)
            {
                throw new JsonException("Unable to deserialize a Date.", ex);
            }
        }
示例#11
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.String)
            {
                return null;
            }

            var instance = Activator.CreateInstance(objectType) as ISafeEnum;

            if (instance == null) return null;

            var enumType = objectType.GetGenericArguments()[0];
            var value = reader.Value as string;

            try
            {
                if (value == null)
                {
                    instance.Value = null;
                }
                else
                {
                    instance.Object = Enum.Parse(enumType, value, true);
                }
            }
            catch (Exception)
            {
                instance.Value = value;
            }

            return instance;
        }
 /// <summary>
 ///     Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing value of object being read.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>The object value.</returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
     JsonSerializer serializer) {
     var result = new ItemOrders();
     serializer.Converters.Add(new EmdRowCollectionJsonConverter<ItemOrders.ItemOrderEntry>());
     result.Orders = serializer.Deserialize<EmdRowCollection<ItemOrders.ItemOrderEntry>>(reader);
     return result;
 }
示例#13
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
            }
            else
            {
                var id = (HiveId)value;
                
                writer.WriteStartObject();
                writer.WritePropertyName("htmlId");
                writer.WriteValue(id.GetHtmlId());

                writer.WritePropertyName("rawValue");
                writer.WriteValue(id.ToString());

                writer.WritePropertyName("value");
                writer.WriteValue(id.Value.Value == null ? "" : id.Value.Value.ToString());

                writer.WritePropertyName("valueType");
                writer.WriteValue(id.Value.Type);

                writer.WritePropertyName("provider");
                writer.WriteValue(id.ProviderId.IsNullOrWhiteSpace() ? "" : id.ProviderId);

                writer.WritePropertyName("scheme");
                writer.WriteValue(id.ProviderGroupRoot == null ? "" : id.ProviderGroupRoot.ToString());

                writer.WriteEndObject();                
            }

        }
        private void LoadJsonFilesIfNeeded()
        {
            if (_environmentDeployInfosByName != null)
              {
            return;
              }

              _environmentDeployInfosByName = new Dictionary<string, EnvironmentDeployInfo>();

              var jsonSerializer = new JsonSerializer();

              foreach (string jsonFilePath in Directory.GetFiles(_configurationFilesDirPath, "*.json", SearchOption.TopDirectoryOnly))
              {
            EnvironmentDeployInfoJson environmentDeployInfoJson = null;

            using (FileStream fileStream = File.OpenRead(jsonFilePath))
            using(var streamReader = new StreamReader(fileStream))
            using (var jsonReader = new JsonTextReader(streamReader))
            {
              environmentDeployInfoJson = jsonSerializer.Deserialize<EnvironmentDeployInfoJson>(jsonReader);
            }

            if (environmentDeployInfoJson != null)
            {
              EnvironmentDeployInfo environmentDeployInfo = ConvertToDomain(environmentDeployInfoJson);

              _environmentDeployInfosByName.Add(environmentDeployInfo.TargetEnvironment, environmentDeployInfo);
            }
              }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var relations = new Relations();
            
            var jToken = JToken.ReadFrom(reader);
            foreach (JProperty jProperty in jToken.Where(_ => _.GetType() == typeof(JProperty)).Cast<JProperty>())
            {
                if (jProperty.Value.GetType() == typeof (JArray))
                {
                    var links = serializer.Deserialize<Link[]>(jProperty.Value.CreateReader());
                    foreach (var link in links)
                    {
                        relations.Add(link);
                        link.Rel = jProperty.Name;
                    }
                }
                else
                {
                    var link = serializer.Deserialize<Link>(jProperty.Value.CreateReader());
                    link.Rel = jProperty.Name;
                    relations.Add(link);
                }
            }

            return relations;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var reference = SupportedTypes[objectType].Invoke();
            serializer.Populate(reader, reference);

            return reference;
        }
示例#17
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            int result = 0;

            // What's happening in this code? We express [Flags] enums in JSON as arrays of
            // strings. On deserialization, we walk the array, locate each string,
            // and convert it to its equivalent enum value. Because we don't have a strong
            // sense of the destination type, we simply treat the enum values as numbers
            // and OR them together. This number will eventually be unboxed and assigned
            // to the target enum property.

            // Read start of array
            reader.Read();

            while (reader.TokenType == JsonToken.String)
            {
                string enumName = EnumConverter.ConvertToPascalCase((string)reader.Value);
                result |= (int)Enum.Parse(objectType, enumName);
                reader.Read();
            }

            return result;
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var heartActivitiesIntraday = value as HeartActivitiesIntraday;

            //{
            writer.WriteStartObject();

            // "DatasetInterval" : "1"
            writer.WritePropertyName("DatasetInterval");
            writer.WriteValue(heartActivitiesIntraday.DatasetInterval);

            // "DatasetType" : "SecondsHeartrate"
            writer.WritePropertyName("DatasetType");
            writer.WriteValue(heartActivitiesIntraday.DatasetType);

            writer.WritePropertyName("Dataset");
            writer.WriteStartArray();
            foreach (var datasetInverval in heartActivitiesIntraday.Dataset)
            {
                // "Time" : "2008-09-22T14:01:54.9571247Z"
                writer.WritePropertyName("Time");
                writer.WriteValue(datasetInverval.Time.ToString("o"));

                // "Value": 1
                writer.WritePropertyName("Value");
                writer.WriteValue(datasetInverval.Value);

            }
            writer.WriteEndArray();
            
            //}
            writer.WriteEndObject();

        }
示例#19
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var token = JToken.Load(reader);
     if (token.Value<string>() != null)
     {
         var str = token.Value<string>();
         switch (str)
         {
             case "CLASSIC":
                 return GameMode.Classic;
             case "ODIN":
                 return GameMode.Dominion;
             case "ARAM":
                 return GameMode.Aram;
             case "TUTORIAL":
                 return GameMode.Tutorial;
             case "ONEFORALL":
                 return GameMode.OneForAll;
             case "FIRSTBLOOD":
                 return GameMode.FirstBlood;
             case "any":
                 return GameMode.Any;
             default:
                 return null;
         }
     }
     return null;
 }
示例#20
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var mode = (GameMode)value;
            string result;
            switch (mode)
            {
                case GameMode.Classic:
                    result = "CLASSIC";
                    break;
                case GameMode.Aram:
                    result = "ARAM";
                    break;
                case GameMode.Dominion:
                    result = "ODIN";
                    break;
                case GameMode.FirstBlood:
                    result = "FIRSTBLOOD";
                    break;
                case GameMode.OneForAll:
                    result = "ONEFORALL";
                    break;
                case GameMode.Tutorial:
                    result = "TUTORIAL";
                    break;

                //Fix for rengar
                case GameMode.Any:
                    result = "any";
                    break;
                default:
                    result = string.Empty;
                    break;
            }
            serializer.Serialize(writer, result);
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue
     , JsonSerializer serializer)
 {
     var token = JToken.Load(reader);
     if (token.Values<string>() == null) return null;
     var list = token.Values<string>();
     var tags = new List<TagStatic>();
     foreach (var str in list)
     {
         switch (str)
         {
             case "Fighter":
                 tags.Add(TagStatic.Fighter);
                 break;
             case "Tank":
                 tags.Add(TagStatic.Tank);
                 break;
             case "Mage":
                 tags.Add(TagStatic.Mage);
                 break;
             case "Assassin":
                 tags.Add(TagStatic.Assassin);
                 break;
             case "Support":
                 tags.Add(TagStatic.Support);
                 break;
             case "Marksman":
                 tags.Add(TagStatic.Marksman);
                 break;
         }
     }
     return tags;
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }

            List<DotaSchemaItem> leagues = new List<DotaSchemaItem>();

            JToken t = JToken.Load(reader);
            var properties = t.Children<JProperty>();
            foreach (var item in properties)
            {
                JObject o = (JObject)item.Value;

                bool isLeague = o["prefab"] != null && o["prefab"].ToString() == "league";

                bool isAdmin =
                    o["tool"] != null
                    && o["tool"]["usage"] != null
                    && o["tool"]["usage"]["admin"] != null
                    && o["tool"]["usage"]["admin"].ToString() == "1";

                if (isLeague && !isAdmin)
                {
                    var league = JsonConvert.DeserializeObject<DotaSchemaItem>(item.Value.ToString());
                    league.DefIndex = item.Name;
                    leagues.Add(league);
                }
            }

            return leagues;
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>
        /// The object value.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jobject = JObject.Load(reader);
            object target = null;

            if (jobject != null)
            {
                var keyType = jobject["key_type"].Value<string>();

                if (string.Equals(keyType, SSHKeyType.otp.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    target = new SSHOTPRoleDefinition();
                }
                else
                {
                    if (string.Equals(keyType, SSHKeyType.dynamic.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        target = new SSHDynamicRoleDefinition();
                    }
                }
            }

            if (target != null)
            {
                serializer.Populate(jobject.CreateReader(), target);
            }

            return target;
        }
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">Serializer</param>
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is DateTime || value is DateTime?)
            {
                DateTime date = value is DateTime ? (DateTime)value : (value as DateTime?).Value;

                if (date != DateTime.MinValue)
                {
                    writer.WriteValue(date.ToString(this.RenderMilliseconds ? DateTimeFormatMs : DateTimeFormat, CultureInfo.InvariantCulture));
                }
                else
                {
                    writer.WriteRawValue("null");
                }

                return;
            }
            else
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;

                if (dateTimeOffset != DateTimeOffset.MinValue)
                {
                    writer.WriteValue(dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture));
                }
                else
                {
                    writer.WriteRawValue("null");
                }
            }

            writer.WriteRawValue("null");
        }
示例#25
0
        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as Metadata;
            if(typedSource != null)
            {
                Name = typedSource.Name;
                Value = typedSource.Value;
                IsPublic = typedSource.IsPublic;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("Name", out token) && token.Type != JTokenType.Null)
                {
                    Name = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("Value", out token) && token.Type != JTokenType.Null)
                {
                    Value = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("IsPublic", out token) && token.Type != JTokenType.Null)
                {
                    IsPublic = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
                }
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var tokenArray = JToken.ReadFrom(reader);

            var children = new List<IChartOfAccountChild>();

            foreach (var token in tokenArray)
            {
                string type = token["type"].Value<string>();

                if (type == AccountGroup.typeName)
                {
                    var accountGroup = JsonConvert.DeserializeObject<AccountGroup>(token.ToString());
                    children.Add(accountGroup);
                }

                if (type == AccountIntervalGroup.typeName)
                {
                    var accountIntervalGroup = JsonConvert.DeserializeObject<AccountIntervalGroup>(token.ToString());
                    children.Add(accountIntervalGroup);
                }
            }

            return children;
        }
示例#27
0
 public static string Json(Message message)
 {
     JsonSerializer js = new JsonSerializer();
     StringWriter str=new StringWriter();
     js.Serialize(str, message);
     return str.ToString();
 }
示例#28
0
        public static void SaveToFile()
        {
            try
            {

                JsonSerializer serializer = new JsonSerializer();
                var prices = dataAccess.GetAllPrices();
                var sales = dataAccess.GetAllSales();
                var priceChanges = dataAccess.GetPriceChanges();

                string path = DataDir + "\\Prices.json";
                var writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, prices);
                writer.Close();

                path = DataDir + "\\Sales.json";
                writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, sales);
                writer.Close();

                path = DataDir + "\\priceChanges.json ";
                writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, priceChanges);
                writer.Close();

            }
            catch (Exception iException)
            {
                int x = 10;
                throw;
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            List<ResolvedAction> resolvedActions = new List<ResolvedAction>();

            JArray actionsArray = JArray.Load(reader);
            foreach (JObject jobject in actionsArray)
            {
                ResolvedAction resolvedAction = new ResolvedAction();
                serializer.Populate(jobject.CreateReader(), resolvedAction);
                resolvedAction.BeaconAction = new BeaconAction();
                serializer.Populate(jobject.CreateReader(), resolvedAction.BeaconAction);
                if (jobject["content"] != null)
                {
                    serializer.Populate(jobject["content"]?.CreateReader(), resolvedAction.BeaconAction);
                    resolvedAction.BeaconAction.PayloadString = jobject["content"]["payload"]?.ToString();
                    // create json object for fallback
                    if(!string.IsNullOrEmpty(resolvedAction.BeaconAction.PayloadString))
                    {
                        resolvedAction.BeaconAction.Payload = JsonObject.Parse(resolvedAction.BeaconAction.PayloadString);
                    }
                }
                resolvedActions.Add(resolvedAction);
            }

            return resolvedActions;
        }
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">Serializer</param>
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
        {
            string text;

            if (value is DateTime || value is DateTime?)
            {
                DateTime dateTime = value is DateTime ? (DateTime)value : (value as DateTime?).Value;

                if ((dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                  || (dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                {
                    dateTime = dateTime.ToUniversalTime();
                }

                text = dateTime.ToString(ISODateTimeJsonConverter.DateTimeFormat, CultureInfo.InvariantCulture);
            }
            else
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;

                if ((dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                  || (dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                    dateTimeOffset = dateTimeOffset.ToUniversalTime();

                text = dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture);
            }

            writer.WriteValue(text);
        }
示例#31
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
 {
     throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
 }
        public static void ConfigureJsonSettings(
            this IMvcBuilder mvc,
            IServiceCollection services,
            JsonSerializerEnum jsonSerializerMode,
            string timezoneHeaderName,
            TimeZoneInfo defaultTimeZone)
        {
            CaseUtility.JsonSerializerMode = jsonSerializerMode;

            JsonSerializerSettings = null;
            JsonSerializer         = null;

            EnumWithContractJsonConverter.IgnoreEnumCase = Api.ApiSettings.UseOriginalEnumValue;

            switch (jsonSerializerMode)
            {
            case JsonSerializerEnum.Camelcase:
                JsonSerializer         = JsonUtility.CamelCaseJsonSerializer;
                JsonSerializerSettings = JsonUtility.CamelCaseJsonSerializerSettings;
                break;

            case JsonSerializerEnum.Lowercase:
                JsonSerializer         = JsonUtility.LowerCaseJsonSerializer;
                JsonSerializerSettings = JsonUtility.LowerCaseJsonSerializerSettings;
                break;

            case JsonSerializerEnum.Snakecase:
                JsonSerializer         = JsonUtility.SnakeCaseJsonSerializer;
                JsonSerializerSettings = JsonUtility.SnakeCaseJsonSerializerSettings;
                break;

            default:
                break;
            }

            // for fluent validation in cqrs extensions
            PropertyName.Resolver = (propertyName) =>
            {
                var parts = propertyName.Split('.');
                return(string.Join(".", parts.Select(r => r.ToCase(jsonSerializerMode.ToString()))));
            };

            JsonConvert.DefaultSettings = () => JsonSerializerSettings;

            services.AddScoped((provider) => JsonSerializer);
            services.AddScoped((provider) => JsonSerializerSettings);

            DateTimeConverter.DefaultTimeZone = defaultTimeZone;
            mvc.AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver  = JsonSerializerSettings.ContractResolver;
                options.SerializerSettings.NullValueHandling = JsonSerializerSettings.NullValueHandling;
                options.SerializerSettings.Converters.Add(new DateTimeConverter(() =>
                {
                    var httpContextAccessor = services.BuildServiceProvider().GetService <IHttpContextAccessor>();
                    return(DateTimeConverter.GetTimeZoneByAspNetHeader(httpContextAccessor, timezoneHeaderName));
                }));
                foreach (var converter in JsonSerializerSettings.Converters)
                {
                    options.SerializerSettings.Converters.Add(converter);
                }
            });
        }
示例#33
0
        /// <summary>
        /// Reads the json.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value.</param>
        /// <param name="serializer">The serializer.</param>
        /// <returns>System.Object.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var obj = _jsonSerializer.Deserialize(objectType, reader, _configuration);

            return(obj);
        }
示例#34
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var option = existingValue as CustomOption ?? new CustomOption();

            serializer.Populate(reader, option);

            option.StartTracking();
            return(option);
        }
示例#35
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            bool   isNullableType = (objectType.GetTypeInfo().IsGenericType&& objectType.GetGenericTypeDefinition() == typeof(Nullable <>));
            object value          = reader.Value;

            DateTime result;

            if (value is DateTime)
            {
                result = (DateTime)value;
            }
            else if (value is string)
            {
                // ISO 8601 String
                result = DateTime.Parse((string)value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
            }
            else if (value is long)
            {
                // UNIX epoch timestamp (in seconds)
                result = UnixEpochBase.AddSeconds((long)value);
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "Deserializing {0} back to {1} is not handled.", value.GetType().FullName, objectType.FullName));
            }

            if (isNullableType && result == default(DateTime))
            {
                return(null); // do not set result on DateTime? field
            }

            return(result);
        }
示例#36
0
 public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
 {
     throw new NotImplementedException();
 }
        private void LoadProjects(string rootPath)
        {
            string[] file2s = Directory.GetFiles(rootPath, "*.fobj3");
            if (file2s != null && file2s.Length > 0)
            {
                bool loaded = false;

                foreach (string file in file2s)
                {
                    StreamReader writer = null;
                    try
                    {
                        writer = new StreamReader(file,
                                                  Encoding.UTF8, false);
                        var           serializer    = new Newtonsoft.Json.JsonSerializer();
                        FictionObject fictionObject = (FictionObject)serializer.Deserialize(writer, typeof(FictionObject));
                        fictionObject.RecalculatePreviousStepCount();
                        Add(fictionObject);
                        loaded = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (writer != null)
                        {
                            writer.Close();
                        }
                        writer = null;
                    }
                    if (loaded)
                    {
                        return;
                    }
                }
            }
            string[] files = Directory.GetFiles(rootPath, "*.fobj");
            if (files != null && files.Length > 0)
            {
                Stream stream = null;
                foreach (string file in files)
                {
                    try
                    {
                        stream = File.Open(file, FileMode.Open);
                        BinaryFormatter bf = new BinaryFormatter();

                        FictionObject fictionObject = (FictionObject)bf.Deserialize(stream);
                        String        location      = fictionObject.Location;
                        int           lastIndex     = location.LastIndexOf("\\");
                        if (lastIndex > 0)
                        {
                            fictionObject.Location = location.Substring(lastIndex + 1);
                        }
                        else
                        {
                            fictionObject.Location = location;
                        }
                        fictionObject.RecalculatePreviousStepCount();
                        Add(fictionObject);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (stream != null)
                        {
                            stream.Close();
                        }
                        stream = null;
                    }
                }
            }
        }
 /// <summary>
 /// Default serializer with overload for allowing custom Json.NET settings
 /// </summary>
 public NewtonsoftJsonSerializer(Newtonsoft.Json.JsonSerializer serializer)
 {
     ContentType = "application/json";
     _serializer = serializer;
 }
        public override byte[] ReadJson(JsonReader reader, Type objectType, byte[] existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            string s = (string)reader.Value;

            return(Bytes.FromHexString(s));
        }
示例#40
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // This custom provider allows able to use just [Authorize] instead of having to define [Authorize(AuthenticationSchemes = "Bearer")] above every API controller
            // without this Bearer authorization will not work
            services.AddSingleton <IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();

            services.AddRedis(Configuration);

            services.AddSignalR().AddPushNotifications(Configuration);

            services.AddOptions <PlatformOptions>().Bind(Configuration.GetSection("VirtoCommerce")).ValidateDataAnnotations();
            services.AddOptions <TranslationOptions>().Configure(options =>
            {
                options.PlatformTranslationFolderPath = WebHostEnvironment.MapPath(options.PlatformTranslationFolderPath);
            });
            //Get platform version from GetExecutingAssembly
            PlatformVersion.CurrentVersion = SemanticVersion.Parse(FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion);

            services.AddPlatformServices(Configuration);
            services.AddSecurityServices();
            services.AddSingleton <LicenseProvider>();

            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();
            services.AddApplicationInsightsTelemetryProcessor <IgnoreSignalRTelemetryProcessor>();

            var mvcBuilder = services.AddMvc(mvcOptions =>
            {
                //Disable 204 response for null result. https://github.com/aspnet/AspNetCore/issues/8847
                var noContentFormatter = mvcOptions.OutputFormatters.OfType <HttpNoContentOutputFormatter>().FirstOrDefault();
                if (noContentFormatter != null)
                {
                    noContentFormatter.TreatNullValueAsNoContent = false;
                }
            }
                                             )
                             .AddNewtonsoftJson(options =>
            {
                //Next line needs to represent custom derived types in the resulting swagger doc definitions. Because default SwaggerProvider used global JSON serialization settings
                //we should register this converter globally.
                options.SerializerSettings.ContractResolver = new PolymorphJsonContractResolver();
                //Next line allow to use polymorph types as parameters in API controller methods
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.Converters.Add(new PolymorphJsonConverter());
                options.SerializerSettings.Converters.Add(new ModuleIdentityJsonConverter());
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                options.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateTimeZoneHandling       = DateTimeZoneHandling.Utc;
                options.SerializerSettings.NullValueHandling          = NullValueHandling.Ignore;

                options.SerializerSettings.Formatting = Formatting.None;

                options.SerializerSettings.Error += (sender, args) =>
                {
                    // Expose any JSON serialization exception as HTTP error
                    throw new JsonException(args.ErrorContext.Error.Message);
                };
            }
                                                );

            services.AddSingleton(js =>
            {
                var serv = js.GetService <IOptions <MvcNewtonsoftJsonOptions> >();
                return(JsonSerializer.Create(serv.Value.SerializerSettings));
            });

            services.AddDbContext <SecurityDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("VirtoCommerce"));
                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });

            // Enable synchronous IO if using Kestrel:
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Enable synchronous IO if using IIS:
            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var authBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                              //Add the second ApiKey auth schema to handle api_key in query string
                              .AddScheme <ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationOptions.DefaultScheme, options => { })
                              .AddCookie();


            services.AddSecurityServices(options =>
            {
                options.NonEditableUsers = new[] { "admin" };
            });

            services.AddIdentity <ApplicationUser, Role>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores <SecurityDbContext>()
            .AddDefaultTokenProviders();

            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.UserIdClaimType   = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.RoleClaimType     = OpenIdConnectConstants.Claims.Role;
            });

            // Support commonly used forwarded headers
            // X-Forwarded-For - Holds Client IP (optionally port number) across proxies and ends up in HttpContext.Connection.RemoteIpAddress
            // X-Forwarded-Proto - Holds original scheme (HTTP or HTTPS) even if call traversed proxies and changed and ends up in HttpContext.Request.Scheme
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Clear();
                options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor;
            });

            //Create backup of token handler before default claim maps are cleared
            var defaultTokenHandler = new JwtSecurityTokenHandler();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            authBuilder.AddJwtBearer(options =>
            {
                options.Authority = Configuration["Auth:Authority"];
                options.Audience  = Configuration["Auth:Audience"];

                if (WebHostEnvironment.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }

                options.IncludeErrorDetails = true;

                X509SecurityKey publicKey = null;
                if (!Configuration["Auth:PublicCertPath"].IsNullOrEmpty())
                {
                    var publicCert = new X509Certificate2(Configuration["Auth:PublicCertPath"]);
                    publicKey      = new X509SecurityKey(publicCert);
                }

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType            = OpenIdConnectConstants.Claims.Subject,
                    RoleClaimType            = OpenIdConnectConstants.Claims.Role,
                    ValidateIssuer           = !string.IsNullOrEmpty(options.Authority),
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = publicKey
                };
            });

            var azureAdSection = Configuration.GetSection("AzureAd");

            if (azureAdSection.GetChildren().Any())
            {
                var options = new AzureAdOptions();
                azureAdSection.Bind(options);

                if (options.Enabled)
                {
                    //TODO: Need to check how this influence to OpennIddict Reference tokens activated by this line below  AddValidation(options => options.UseReferenceTokens());
                    authBuilder.AddOpenIdConnect(options.AuthenticationType, options.AuthenticationCaption,
                                                 openIdConnectOptions =>
                    {
                        openIdConnectOptions.ClientId               = options.ApplicationId;
                        openIdConnectOptions.Authority              = $"{options.AzureAdInstance}{options.TenantId}";
                        openIdConnectOptions.UseTokenLifetime       = true;
                        openIdConnectOptions.RequireHttpsMetadata   = false;
                        openIdConnectOptions.SignInScheme           = IdentityConstants.ExternalScheme;
                        openIdConnectOptions.SecurityTokenValidator = defaultTokenHandler;
                    });
                }
            }

            services.AddOptions <Core.Security.AuthorizationOptions>().Bind(Configuration.GetSection("Authorization")).ValidateDataAnnotations();
            var authorizationOptions = Configuration.GetSection("Authorization").Get <Core.Security.AuthorizationOptions>();
            var platformOptions      = Configuration.GetSection("VirtoCommerce").Get <PlatformOptions>();

            // Register the OpenIddict services.
            // Note: use the generic overload if you need
            // to replace the default OpenIddict entities.
            services.AddOpenIddict()
            .AddCore(options =>
            {
                options.UseEntityFrameworkCore()
                .UseDbContext <SecurityDbContext>();
            }).AddServer(options =>
            {
                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.UseMvc();

                // Enable the authorization, logout, token and userinfo endpoints.
                options.EnableTokenEndpoint("/connect/token")
                .EnableUserinfoEndpoint("/api/security/userinfo");

                // Note: the Mvc.Client sample only uses the code flow and the password flow, but you
                // can enable the other flows if you need to support implicit or client credentials.
                options.AllowPasswordFlow()
                .AllowRefreshTokenFlow()
                .AllowClientCredentialsFlow();

                options.SetRefreshTokenLifetime(authorizationOptions?.RefreshTokenLifeTime);
                options.SetAccessTokenLifetime(authorizationOptions?.AccessTokenLifeTime);

                options.AcceptAnonymousClients();

                // Configure Openiddict to issues new refresh token for each token refresh request.
                options.UseRollingTokens();

                // Make the "client_id" parameter mandatory when sending a token request.
                //options.RequireClientIdentification();

                // When request caching is enabled, authorization and logout requests
                // are stored in the distributed cache by OpenIddict and the user agent
                // is redirected to the same page with a single parameter (request_id).
                // This allows flowing large OpenID Connect requests even when using
                // an external authentication provider like Google, Facebook or Twitter.
                options.EnableRequestCaching();

                options.DisableScopeValidation();

                // During development or when you explicitly run the platform in production mode without https, need to disable the HTTPS requirement.
                if (WebHostEnvironment.IsDevelopment() || platformOptions.AllowInsecureHttp || !Configuration.IsHttpsServerUrlSet())
                {
                    options.DisableHttpsRequirement();
                }

                // Note: to use JWT access tokens instead of the default
                // encrypted format, the following lines are required:
                options.UseJsonWebTokens();

                var bytes = File.ReadAllBytes(Configuration["Auth:PrivateKeyPath"]);
                X509Certificate2 privateKey;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    // https://github.com/dotnet/corefx/blob/release/2.2/Documentation/architecture/cross-platform-cryptography.md
                    // macOS cannot load certificate private keys without a keychain object, which requires writing to disk. Keychains are created automatically for PFX loading, and are deleted when no longer in use. Since the X509KeyStorageFlags.EphemeralKeySet option means that the private key should not be written to disk, asserting that flag on macOS results in a PlatformNotSupportedException.
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet);
                }
                else
                {
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);
                }
                options.AddSigningCertificate(privateKey);
            });

            services.Configure <IdentityOptions>(Configuration.GetSection("IdentityOptions"));

            //always  return 401 instead of 302 for unauthorized  requests
            services.ConfigureApplicationCookie(options =>
            {
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
            });

            services.AddAuthorization(options =>
            {
                //We need this policy because it is a single way to implicitly use the two schema (JwtBearer and ApiKey)  authentication for resource based authorization.
                var mutipleSchemaAuthPolicy = new AuthorizationPolicyBuilder().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme)
                                              .RequireAuthenticatedUser()
                                              .Build();
                //The good article is described the meaning DefaultPolicy and FallbackPolicy
                //https://scottsauber.com/2020/01/20/globally-require-authenticated-users-by-default-using-fallback-policies-in-asp-net-core/
                options.DefaultPolicy = mutipleSchemaAuthPolicy;
            });
            // register the AuthorizationPolicyProvider which dynamically registers authorization policies for each permission defined in module manifest
            services.AddSingleton <IAuthorizationPolicyProvider, PermissionAuthorizationPolicyProvider>();
            //Platform authorization handler for policies based on permissions
            services.AddSingleton <IAuthorizationHandler, DefaultPermissionAuthorizationHandler>();
            // Default password validation service implementation
            services.AddScoped <IPasswordCheckService, PasswordCheckService>();

            services.AddOptions <LocalStorageModuleCatalogOptions>().Bind(Configuration.GetSection("VirtoCommerce"))
            .PostConfigure(options =>
            {
                options.DiscoveryPath = Path.GetFullPath(options.DiscoveryPath ?? "Modules");
            })
            .ValidateDataAnnotations();
            services.AddModules(mvcBuilder);

            services.AddOptions <ExternalModuleCatalogOptions>().Bind(Configuration.GetSection("ExternalModules")).ValidateDataAnnotations();
            services.AddExternalModules();

            //Assets
            var assetsProvider = Configuration.GetSection("Assets:Provider").Value;

            if (assetsProvider.EqualsInvariant(AzureBlobProvider.ProviderName))
            {
                services.AddOptions <AzureBlobOptions>().Bind(Configuration.GetSection("Assets:AzureBlobStorage")).ValidateDataAnnotations();
                services.AddAzureBlobProvider();
            }
            else
            {
                services.AddOptions <FileSystemBlobOptions>().Bind(Configuration.GetSection("Assets:FileSystem"))
                .PostConfigure(options =>
                {
                    options.RootPath = WebHostEnvironment.MapPath(options.RootPath);
                }).ValidateDataAnnotations();

                services.AddFileSystemBlobProvider();
            }

            //HangFire
            services.AddHangfire(Configuration);

            // Register the Swagger generator
            services.AddSwagger();
        }
示例#41
0
        public override long ReadJson(JsonReader reader, Type objectType, long existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (reader.Value is long || reader.Value is int)
            {
                return((long)reader.Value);
            }

            string s = (string)reader.Value;

            return(FromString(s));
        }
示例#42
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            switch (reader.TokenType)
            {
            case JsonToken.Null:
                return(null);    // fixme - or should we actually return a cache object that says please don't cache?

            case JsonToken.String:
                var profile = (string)serializer.Deserialize(reader, typeof(string));
                return(new CacheProfile(profile));

            default:
                return(serializer.Deserialize(reader, objectType));
            }
        }
示例#43
0
文件: Serializer.cs 项目: thoory/TA72
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     writer.WriteValue(value.ToString());
 }
 public override void WriteJson(JsonWriter writer, byte[] value, Newtonsoft.Json.JsonSerializer serializer)
 {
     writer.WriteValue(value.ToHexString(true));
 }
 /// <summary>
 /// Default serializer with overload for allowing custom Json.NET settings
 /// </summary>
 public RestSharpJsonNetSerializer(Newtonsoft.Json.JsonSerializer serializer)
 {
     ContentType = "application/json";
     _serializer = serializer;
 }
示例#46
0
文件: Serializer.cs 项目: thoory/TA72
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.Value == null)
     {
         return(null);
     }
     return(IPAddress.Parse((string)reader.Value));
 }
示例#47
0
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var password = (Password)value;

            writer.WriteValue(password.ToString());
        }
示例#48
0
文件: Serializer.cs 项目: thoory/TA72
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject   jo      = JObject.Load(reader);
            IPAddress address = jo["Address"].ToObject <IPAddress>(serializer);
            int       port    = (int)jo["Port"];

            return(new IPEndPoint(address, port));
        }
        public override Object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            // Load the JSON for the Result into a JObject
            JObject jo = JObject.Load(reader);

            // Read the properties which will be used as constructor parameters
            string value = (string)jo["Value"];

            string checksum = "";

            if (jo["Checksum"].Contains("Value") && jo["Checksum"]["Value"].Type == JTokenType.String)
            {
                checksum = (string)jo["Checksum"]["Value"];
            }

            // Construct the Result object using the non-default constructor
            Address result = new Address(value + checksum)
            {
                // (If anything else needs to be populated on the result object, do that here)
                Balance   = (long)jo["Balance"],
                KeyIndex  = (int)jo["KeyIndex"],
                SpentFrom = (bool)jo["SpentFrom"]
            };

            // Return the result
            return(result);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            // Load the JSON for the Result into a JObject
            JObject jo = JObject.Load(reader);

            // Read the properties which will be used as constructor parameters
            string value = (string)jo["Value"];

            // Construct the Result object using the non-default constructor
            TryteString result = new TryteString(value);

            // (If anything else needs to be populated on the result object, do that here)

            // Return the result
            return(result);
        }
示例#51
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
 {
     throw new NotImplementedException();
 }
示例#52
0
        public Initialize(string appName, out TestRunModel testRun)
        {
            try
            {
                Api         prefs;
                Preferences preferences;

                if (Dns.GetHostName() == "VDI-Automation0")
                {
                    // Get Queued User Prefs
                    prefs = new Api($"api/GetPreferences/{appName}/{Environment.UserName}/{true}");
                    JsonReader reader = new JsonTextReader(new StringReader(prefs.GetApi().Content));
                    preferences = new NewtonSoftSerializer().Deserialize <Preferences>(reader);
                }
                else
                {
                    // Get Normal User Prefs
                    prefs = new Api($"api/GetPreferences/{appName}/{Environment.UserName}/{false}");
                    JsonReader reader = new JsonTextReader(new StringReader(prefs.GetApi().Content));
                    preferences            = new NewtonSoftSerializer().Deserialize <Preferences>(reader);
                    preferences.TesterName = Environment.UserName;
                }
                //preferences.RemoteDriver = false;

                var appKeyRequest = new Api($"api/GetAppKey/{appName}");
                var appKey        = int.Parse(appKeyRequest.GetApi().Content);
                Debug.WriteLine($"Initializing Application: {appName} - Key: {appKey}");

                var testName = "";
                Debug.WriteLine("Initializing Test: " + GetTestName());
                var testKey        = new Api($"api/GetTestKey/{appName}/{GetTestName()}");
                var testKeyContent = testKey.GetApi().Content;
                if (testKeyContent.Contains("Test name not found"))
                {
                    Test newTest = new Test
                    {
                        ApplicationKey = appKey,
                        Active         = true,
                        TestName       = GetTestName()
                    };
                    testName = newTest.TestName;

                    Debug.WriteLine($"{GetTestName()} not found.. Creating new test.");
                    // Do some logic to create a new test for this test name.
                    var createTestRequest = new Api("api/CreateTest");
                    testKeyContent = createTestRequest.PostApi(JsonConvert.SerializeObject(newTest)).Content;;  // Set key to newly created test key

                    Debug.WriteLine($"Initializing Test: {GetTestName()} - Key: {testKeyContent}");
                }

                testRun = new TestRunModel
                {
                    ApplicationKey = appKey,
                    TestRunStatus  = RunStatus.Status.Initializing.ToString(),
                    Environment    = preferences.Environment,
                    EnvironmentUrl = preferences.EnvironmentUrl,
                    TestKey        = int.Parse(testKeyContent),
                    TesterKey      = preferences.TesterKey,
                    Browser        = preferences.BrowserName,
                };

                var createTestRunKey = new Api("api/CreateTestRun");
                testRun.TestRunKey = int.Parse(createTestRunKey.PostApi(JsonConvert.SerializeObject(testRun)).Content);
                TestRunKey         = testRun.TestRunKey;

                if (testName != string.Empty && !testName.ToUpper().Contains("API"))
                {
                    WebDriver driverData = new WebDriver();
                    TestRunModel.Driver = driverData.GetWebDriver(preferences);
                    Debug.WriteLine("Started Driver type: " + TestRunModel.Driver.GetType());

                    TestRunModel.Driver.Manage().Window.Maximize();

                    TestRunModel.Driver.Navigate().GoToUrl(testRun.EnvironmentUrl);
                    Debug.WriteLine($"Went to URL: {TestRunModel.Driver.Url}");
                }
                else
                {
                    TestRunModel.IsApiTest = true;
                    Debug.WriteLine("Started API Test.");
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
                throw;
            }
        }
示例#53
0
 public JsonSerializer(Newtonsoft.Json.JsonSerializer serializer)
 {
     _serializer = serializer;
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var valueInSeconds = (long?)reader.Value;

            if (!valueInSeconds.HasValue)
            {
                return(null);
            }

            return(TimeSpan.FromSeconds(valueInSeconds.Value));
        }
示例#55
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
 => Password.From(reader.Value.ToString());
 public override void WriteJson(JsonWriter writer, MyClass value, Newtonsoft.Json.JsonSerializer serializer)
 {
     serializer.Serialize(writer, value.DateTime.Ticks);
 }
示例#57
0
        public override ObservableList <ApplicationAPIModel> ParseDocument(string FileName, ObservableList <ApplicationAPIModel> SwaggerModels, bool avoidDuplicatesNodes = false)
        {
            string FinalFileName = "";
            Uri    url           = new Uri(FileName);

            string orignaljson = "";

            if (url.IsFile)
            {
                orignaljson = System.IO.File.ReadAllText(FileName);
            }
            {
                orignaljson = GeneralLib.HttpUtilities.Download(url);
            }
            try
            {
                JToken.Parse(orignaljson);
                FinalFileName = FileName;
            }
            catch
            {
                var          r            = new StringReader(orignaljson);
                var          deserializer = new Deserializer();
                var          yamlObject   = deserializer.Deserialize(r);
                StringWriter tw           = new StringWriter();
                var          serializer   = new Newtonsoft.Json.JsonSerializer();
                serializer.Serialize(tw, yamlObject);
                orignaljson = tw.ToString();
                string tempfile = System.IO.Path.GetTempFileName();

                System.IO.File.WriteAllText(tempfile, orignaljson);
                FinalFileName = tempfile;
            }


            Swaggerdoc = SwaggerDocument.FromJsonAsync(orignaljson).Result;
            foreach (var paths in Swaggerdoc.Paths)
            {
                SwaggerPathItem SPi = paths.Value;
                foreach (KeyValuePair <SwaggerOperationMethod, SwaggerOperation> so in SPi.AsEnumerable())
                {
                    SwaggerOperation Operation = so.Value;


                    bool supportBody = true;
                    if (Operation.RequestBody == null && Operation.ActualConsumes.Count() == 0)
                    {
                        ApplicationAPIModel basicModal = GenerateBasicModel(Operation, so.Key, ref supportBody, paths.Key);
                        SwaggerModels.Add(basicModal);
                        GenerateResponse(Operation, basicModal);
                    }


                    else if (Operation.ActualConsumes.Count() == 0 && Operation.RequestBody.Content.Count() != 0)
                    {
                        foreach (var body in Operation.RequestBody.Content)
                        {
                            ApplicationAPIModel AAM = GenerateBasicModel(Operation, so.Key, ref supportBody, paths.Key);



                            if (supportBody)
                            {
                                switch (body.Key)
                                {
                                case "application/x-www-form-urlencoded":
                                    GenerateFormParameters(AAM, Operation);
                                    break;

                                case "multipart/form-data":
                                    GenerateFormParameters(AAM, Operation, true);
                                    break;

                                case "application/json":
                                    AAM.ContentType         = ApplicationAPIUtils.eContentType.JSon;
                                    AAM.ResponseContentType = ApplicationAPIUtils.eContentType.JSon;
                                    if (Operation.RequestBody != null)
                                    {
                                        AAM.AppModelParameters.Append(GenerateJsonBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                    }
                                    if (Operation.ActualConsumes.Count() > 1)
                                    {
                                        AAM.Name += "-JSON"; AAM.Description = "Body Type is JSON";
                                    }

                                    break;

                                case "application/xml":
                                    AAM.ContentType         = ApplicationAPIUtils.eContentType.XML;
                                    AAM.ResponseContentType = ApplicationAPIUtils.eContentType.XML;
                                    if (Operation.RequestBody != null)
                                    {
                                        AAM.AppModelParameters.Append(GenerateXMLBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                    }
                                    if (Operation.ActualConsumes.Count() > 1)
                                    {
                                        AAM.Name       += "-XML";
                                        AAM.Description = "Body Type is XML";
                                    }

                                    break;
                                }
                            }
                            GenerateResponse(Operation, AAM);
                            SwaggerModels.Add(AAM);
                        }
                    }

                    foreach (var body in    Operation.ActualConsumes)
                    {
                        ApplicationAPIModel AAM = GenerateBasicModel(Operation, so.Key, ref supportBody, paths.Key);



                        if (supportBody)
                        {
                            switch (body)
                            {
                            case "application/x-www-form-urlencoded":
                                GenerateFormParameters(AAM, Operation);
                                break;

                            case "multipart/form-data":
                                GenerateFormParameters(AAM, Operation, true);
                                break;

                            case "application/json":
                                AAM.ContentType         = ApplicationAPIUtils.eContentType.JSon;
                                AAM.ResponseContentType = ApplicationAPIUtils.eContentType.JSon;
                                if (Operation.RequestBody != null)
                                {
                                    AAM.AppModelParameters.Append(GenerateJsonBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                }
                                if (Operation.ActualConsumes.Count() > 1)
                                {
                                    AAM.Name       += "-JSON";
                                    AAM.Description = "Body Type is JSON";
                                }

                                break;

                            case "application/xml":
                                AAM.ContentType         = ApplicationAPIUtils.eContentType.XML;
                                AAM.ResponseContentType = ApplicationAPIUtils.eContentType.XML;
                                if (Operation.RequestBody != null)
                                {
                                    AAM.AppModelParameters.Append(GenerateXMLBody(AAM, Operation.RequestBody.Content.ElementAt(0).Value.Schema));
                                }
                                if (Operation.ActualConsumes.Count() > 1)
                                {
                                    AAM.Name       += "-XML";
                                    AAM.Description = "Body Type is XML";
                                }
                                break;
                            }
                        }
                        GenerateResponse(Operation, AAM);

                        SwaggerModels.Add(AAM);
                    }
                }
            }
            return(SwaggerModels);
        }
示例#58
0
 public NewtonsoftJsonSerializer(Newtonsoft.Json.JsonSerializer serializer)
 {
     this.serializer = serializer;
 }
示例#59
0
 public TextFileRepository()
 {
     mJsonSerializer = new Newtonsoft.Json.JsonSerializer();
     mJsonSerializer.NullValueHandling = NullValueHandling.Ignore;
 }
 public override MyClass ReadJson(JsonReader reader, Type objectType, MyClass existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer)
 {
     return(new MyClass()
     {
         DateTime = new DateTime((long)reader.Value)
     });
 }